context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//-----------------------------------------------------------------------
// <copyright file="GraphInterpreterPortsSpec.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 Akka.Streams.TestKit.Tests;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using Cancel = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.Cancel;
using OnComplete = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnComplete;
using OnError = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnError;
using OnNext = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnNext;
using RequestOne = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.RequestOne;
namespace Akka.Streams.Tests.Implementation.Fusing
{
public class GraphInterpreterPortsSpec : GraphInterpreterSpecKit
{
// ReSharper disable InconsistentNaming
private readonly PortTestSetup.DownstreamPortProbe<int> inlet;
private readonly PortTestSetup.UpstreamPortProbe<int> outlet;
private readonly Func<ISet<TestSetup.ITestEvent>> lastEvents;
private readonly Action stepAll;
private readonly Action step;
private readonly Action clearEvents;
public GraphInterpreterPortsSpec(ITestOutputHelper output = null) : base(output)
{
var setup = new PortTestSetup(Sys);
inlet = setup.In;
outlet = setup.Out;
lastEvents = setup.LastEvents;
stepAll = setup.StepAll;
step = setup.Step;
clearEvents = setup.ClearEvents;
}
// TODO FIXME test failure scenarios
[Fact]
public void Port_states_should_properly_transition_on_push_and_pull()
{
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Pull();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new RequestOne(outlet));
outlet.IsAvailable().Should().Be(true);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Push(0);
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(true);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Grab().Should().Be(0);
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
// Cycle completed
}
[Fact]
public void Port_states_should_drop_ungrabbed_element_on_pull()
{
inlet.Pull();
step();
clearEvents();
outlet.Push(0);
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
inlet.Pull();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_complete_while_downstream_is_active()
{
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Complete();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnComplete(inlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_complete_while_upstream_is_active()
{
inlet.Pull();
stepAll();
lastEvents().Should().BeEquivalentTo(new RequestOne(outlet));
outlet.IsAvailable().Should().Be(true);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Complete();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnComplete(inlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_complete_while_pull_is_in_flight()
{
inlet.Pull();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Complete();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnComplete(inlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_complete_while_push_is_in_flight()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Complete();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(true);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Grab().Should().Be(0);
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
step();
lastEvents().Should().BeEquivalentTo(new OnComplete(inlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_complete_while_push_is_in_flight_and_keep_ungrabbed_element()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
outlet.Complete();
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
step();
lastEvents().Should().BeEquivalentTo(new OnComplete(inlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(true);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Grab().Should().Be(0);
}
[Fact]
public void Port_states_should_propagate_complete_while_push_is_in_flight_and_pulled_after_the_push()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
outlet.Complete();
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
inlet.Grab().Should().Be(0);
inlet.Pull();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnComplete(inlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_pull_while_completing()
{
outlet.Complete();
inlet.Pull();
// While the pull event is not enqueue at this point, we should still report the state correctly
inlet.HasBeenPulled().Should().Be(true);
stepAll();
lastEvents().Should().BeEquivalentTo(new OnComplete(inlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_cancel_while_downstream_is_active()
{
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
inlet.Cancel();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new Cancel(outlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_cancel_while_upstream_is_active()
{
inlet.Pull();
stepAll();
lastEvents().Should().BeEquivalentTo(new RequestOne(outlet));
outlet.IsAvailable().Should().Be(true);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
inlet.Cancel();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(true);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new Cancel(outlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_cancel_while_pull_is_in_flight()
{
inlet.Pull();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
inlet.Cancel();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new Cancel(outlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_cancel_while_push_is_in_flight()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
inlet.Cancel();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new Cancel(outlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_push_while_cancelling()
{
inlet.Pull();
stepAll();
clearEvents();
inlet.Cancel();
outlet.Push(0);
// While the push event is not enqueued at this point, we should still report the state correctly
outlet.IsAvailable().Should().Be(false);
stepAll();
lastEvents().Should().BeEquivalentTo(new Cancel(outlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_clear_ungrabbed_element_even_when_cancelled()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
stepAll();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
inlet.Cancel();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new Cancel(outlet));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_any_completion_if_they_are_concurrent_cancel_first()
{
inlet.Cancel();
outlet.Complete();
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_any_completion_if_they_are_concurrent_complete_first()
{
outlet.Complete();
inlet.Cancel();
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_completion_from_a_push_complete_if_cancelled_while_in_flight()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
outlet.Complete();
inlet.Cancel();
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_completion_from_a_push_complete_if_cancelled_after_OnPush()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
outlet.Complete();
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(true);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Grab().Should().Be(0);
inlet.Cancel();
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_not_allow_to_grab_element_before_it_arrives()
{
inlet.Pull();
stepAll();
outlet.Push(0);
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_not_allow_to_grab_element_if_already_cancelled()
{
inlet.Pull();
stepAll();
outlet.Push(0);
inlet.Cancel();
stepAll();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_failure_while_downstream_is_active()
{
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Fail(new TestException("test"));
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test")));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_failure_while_upstream_is_active()
{
inlet.Pull();
stepAll();
lastEvents().Should().BeEquivalentTo(new RequestOne(outlet));
outlet.IsAvailable().Should().Be(true);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Fail(new TestException("test"));
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test")));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_failure_while_pull_is_in_flight()
{
inlet.Pull();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Fail(new TestException("test"));
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
stepAll();
lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test")));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
inlet.Cancel(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_failure_while_push_is_in_flight()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(false);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Fail(new TestException("test"));
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(true);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(true);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Grab().Should().Be(0);
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
step();
lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test")));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
outlet.Complete(); // This should have no effect now
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_propagate_failure_while_push_is_in_flight_and_keep_ungrabbed_element()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
outlet.Fail(new TestException("test"));
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
step();
lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test")));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(true);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Grab().Should().Be(0);
}
[Fact]
public void Port_states_should_ignore_pull_while_failing()
{
outlet.Fail(new TestException("test"));
inlet.Pull();
inlet.HasBeenPulled().Should().Be(true);
stepAll();
lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test")));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_any_failure_completion_if_they_are_concurrent_cancel_first()
{
inlet.Cancel();
outlet.Fail(new TestException("test"));
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_any_failure_completion_if_they_are_concurrent_complete_first()
{
outlet.Fail(new TestException("test"));
inlet.Cancel();
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_any_failure_from_a_push_then_fail_if_cancelled_while_in_flight()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
outlet.Fail(new TestException("test"));
inlet.Cancel();
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
[Fact]
public void Port_states_should_ignore_any_failure_from_a_push_then_fail_if_cancelled_after_OnPush()
{
inlet.Pull();
stepAll();
clearEvents();
outlet.Push(0);
outlet.Fail(new TestException("test"));
step();
lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0));
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(true);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(false);
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Grab().Should().Be(0);
inlet.Cancel();
stepAll();
lastEvents().Should().BeEmpty();
outlet.IsAvailable().Should().Be(false);
outlet.IsClosed().Should().Be(true);
inlet.IsAvailable().Should().Be(false);
inlet.HasBeenPulled().Should().Be(false);
inlet.IsClosed().Should().Be(true);
inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>();
outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>();
inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>();
}
}
}
| |
// 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 Xunit;
namespace System.Tests
{
public partial class Int32Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new int();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
int i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFFFFFF, int.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((int)0x80000000), int.MinValue);
}
[Theory]
[InlineData(234, 234, 0)]
[InlineData(234, int.MinValue, 1)]
[InlineData(234, -123, 1)]
[InlineData(234, 0, 1)]
[InlineData(234, 123, 1)]
[InlineData(234, 456, -1)]
[InlineData(234, int.MaxValue, -1)]
[InlineData(-234, -234, 0)]
[InlineData(-234, 234, -1)]
[InlineData(-234, -432, 1)]
[InlineData(234, null, 1)]
public void CompareTo_Other_ReturnsExpected(int i, object value, int expected)
{
if (value is int intValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(intValue)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData((long)234)]
public void CompareTo_ObjectNotInt_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => 123.CompareTo(value));
}
[Theory]
[InlineData(789, 789, true)]
[InlineData(789, -789, false)]
[InlineData(789, 0, false)]
[InlineData(0, 0, true)]
[InlineData(-789, -789, true)]
[InlineData(-789, 789, false)]
[InlineData(789, null, false)]
[InlineData(789, "789", false)]
[InlineData(789, (long)789, false)]
public static void Equals(int i1, object obj, bool expected)
{
if (obj is int)
{
int i2 = (int)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsInt32()
{
Assert.Equal(TypeCode.Int32, 1.GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo })
{
foreach (string defaultSpecifier in new[] { "G", "G\0", "\0N222", "\0", "" })
{
yield return new object[] { int.MinValue, defaultSpecifier, defaultFormat, "-2147483648" };
yield return new object[] { -4567, defaultSpecifier, defaultFormat, "-4567" };
yield return new object[] { 0, defaultSpecifier, defaultFormat, "0" };
yield return new object[] { 4567, defaultSpecifier, defaultFormat, "4567" };
yield return new object[] { int.MaxValue, defaultSpecifier, defaultFormat, "2147483647" };
}
yield return new object[] { 4567, "D", defaultFormat, "4567" };
yield return new object[] { 4567, "D99", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { 4567, "D99\09", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004567" };
yield return new object[] { 0x2468, "x", defaultFormat, "2468" };
yield return new object[] { 2468, "N", defaultFormat, string.Format("{0:N}", 2468.00) };
}
var customFormat = new NumberFormatInfo()
{
NegativeSign = "#",
NumberDecimalSeparator = "~",
NumberGroupSeparator = "*",
PositiveSign = "&",
NumberDecimalDigits = 2,
PercentSymbol = "@",
PercentGroupSeparator = ",",
PercentDecimalSeparator = ".",
PercentDecimalDigits = 5
};
yield return new object[] { -2468, "N", customFormat, "#2*468~00" };
yield return new object[] { 2468, "N", customFormat, "2*468~00" };
yield return new object[] { 123, "E", customFormat, "1~230000E&002" };
yield return new object[] { 123, "F", customFormat, "123~00" };
yield return new object[] { 123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(int i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
int i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberFormatInfo samePositiveNegativeFormat = new NumberFormatInfo()
{
PositiveSign = "|",
NegativeSign = "|"
};
NumberFormatInfo emptyPositiveFormat = new NumberFormatInfo() { PositiveSign = "" };
NumberFormatInfo emptyNegativeFormat = new NumberFormatInfo() { NegativeSign = "" };
// None
yield return new object[] { "0", NumberStyles.None, null, 0 };
yield return new object[] { "0000000000000000000000000000000000000000000000000000000000", NumberStyles.None, null, 0 };
yield return new object[] { "0000000000000000000000000000000000000000000000000000000001", NumberStyles.None, null, 1 };
yield return new object[] { "2147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "02147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "00000000000000000000000000000000000000000000000002147483647", NumberStyles.None, null, 2147483647 };
yield return new object[] { "123\0\0", NumberStyles.None, null, 123 };
// All lengths decimal
foreach (bool neg in new[] { false, true })
{
string s = neg ? "-" : "";
int result = 0;
for (int i = 1; i <= 10; i++)
{
result = result * 10 + (i % 10);
s += (i % 10).ToString();
yield return new object[] { s, NumberStyles.Integer, null, neg ? result * -1 : result };
}
}
// All lengths hexadecimal
{
string s = "";
int result = 0;
for (int i = 1; i <= 8; i++)
{
result = (result * 16) + (i % 16);
s += (i % 16).ToString("X");
yield return new object[] { s, NumberStyles.HexNumber, null, result };
}
}
// HexNumber
yield return new object[] { "123", NumberStyles.HexNumber, null, 0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, 0xabc };
yield return new object[] { "12", NumberStyles.HexNumber, null, 0x12 };
yield return new object[] { "80000000", NumberStyles.HexNumber, null, int.MinValue };
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, -1 };
// Currency
NumberFormatInfo currencyFormat = new NumberFormatInfo()
{
CurrencySymbol = "$",
CurrencyGroupSeparator = "|",
NumberGroupSeparator = "/"
};
yield return new object[] { "$1|000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$ 1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "1000", NumberStyles.Currency, currencyFormat, 1000 };
yield return new object[] { "$(1000)", NumberStyles.Currency, currencyFormat, -1000};
yield return new object[] { "($1000)", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "$-1000", NumberStyles.Currency, currencyFormat, -1000 };
yield return new object[] { "-$1000", NumberStyles.Currency, currencyFormat, -1000 };
NumberFormatInfo emptyCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "" };
yield return new object[] { "100", NumberStyles.Currency, emptyCurrencyFormat, 100 };
// If CurrencySymbol and Negative are the same, NegativeSign is preferred
NumberFormatInfo sameCurrencyNegativeSignFormat = new NumberFormatInfo()
{
NegativeSign = "|",
CurrencySymbol = "|"
};
yield return new object[] { "|1000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, -1000 };
// Any
yield return new object[] { "123", NumberStyles.Any, null, 123 };
// AllowLeadingSign
yield return new object[] { "-2147483648", NumberStyles.AllowLeadingSign, null, -2147483648 };
yield return new object[] { "-123", NumberStyles.AllowLeadingSign, null, -123 };
yield return new object[] { "+0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "-0", NumberStyles.AllowLeadingSign, null, 0 };
yield return new object[] { "+123", NumberStyles.AllowLeadingSign, null, 123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "|123", NumberStyles.AllowLeadingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyNegativeFormat, 100 };
// AllowTrailingSign
yield return new object[] { "123", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123+", NumberStyles.AllowTrailingSign, null, 123 };
yield return new object[] { "123-", NumberStyles.AllowTrailingSign, null, -123 };
// If PositiveSign and NegativeSign are the same, PositiveSign is preferred
yield return new object[] { "123|", NumberStyles.AllowTrailingSign, samePositiveNegativeFormat, 123 };
// Empty PositiveSign or NegativeSign
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyPositiveFormat, 100 };
yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyNegativeFormat, 100 };
// AllowLeadingWhite and AllowTrailingWhite
yield return new object[] { " 123", NumberStyles.AllowLeadingWhite, null, 123 };
yield return new object[] { " 123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { "123 ", NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { "123 \0\0", NumberStyles.AllowTrailingWhite, null, 123 };
yield return new object[] { " 2147483647 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 2147483647 };
yield return new object[] { " -2147483648 ", NumberStyles.Integer, null, -2147483648 };
foreach (char c in new[] { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD })
{
string cs = c.ToString();
yield return new object[] { cs + cs + "123" + cs + cs, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 };
}
yield return new object[] { " 0 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 0 };
yield return new object[] { " 000000000 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 0 };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "1000", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|0|0|0", NumberStyles.AllowThousands, thousandsFormat, 1000 };
yield return new object[] { "1|||", NumberStyles.AllowThousands, thousandsFormat, 1 };
NumberFormatInfo integerNumberSeparatorFormat = new NumberFormatInfo() { NumberGroupSeparator = "1" };
yield return new object[] { "1111", NumberStyles.AllowThousands, integerNumberSeparatorFormat, 1111 };
// AllowExponent
yield return new object[] { "1E2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E+2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1e2", NumberStyles.AllowExponent, null, 100 };
yield return new object[] { "1E0", NumberStyles.AllowExponent, null, 1 };
yield return new object[] { "(1E2)", NumberStyles.AllowExponent | NumberStyles.AllowParentheses, null, -100 };
yield return new object[] { "-1E2", NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign, null, -100 };
NumberFormatInfo negativeFormat = new NumberFormatInfo() { PositiveSign = "|" };
yield return new object[] { "1E|2", NumberStyles.AllowExponent, negativeFormat, 100 };
// AllowParentheses
yield return new object[] { "123", NumberStyles.AllowParentheses, null, 123 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, -123 };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "|" };
yield return new object[] { "67|", NumberStyles.AllowDecimalPoint, decimalFormat, 67 };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, 123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "1" }, 23123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "1" }, -23123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "123" }, 123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "123" }, -123 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "12312" }, 3 };
yield return new object[] { "123123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "12312" }, -3 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, int expected)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.True(int.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Equal(expected, int.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.True(int.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Equal(expected, int.Parse(value, provider));
}
// Full overloads
Assert.True(int.TryParse(value, style, provider, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, int.Parse(value, style, provider));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
// String is null, empty or entirely whitespace
yield return new object[] { null, NumberStyles.Integer, null, typeof(ArgumentNullException) };
yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) };
yield return new object[] { "", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "", NumberStyles.Any, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", NumberStyles.Any, null, typeof(FormatException) };
yield return new object[] { " \0\0", NumberStyles.Integer, null, typeof(FormatException) };
// Leading or trailing chars for which char.IsWhiteSpace is true but that's not valid for leading/trailing whitespace
foreach (string c in new[] { "\x0085", "\x00A0", "\x1680", "\x2000", "\x2001", "\x2002", "\x2003", "\x2004", "\x2005", "\x2006", "\x2007", "\x2008", "\x2009", "\x200A", "\x2028", "\x2029", "\x202F", "\x205F", "\x3000" })
{
yield return new object[] { c + "123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "123" + c, NumberStyles.Integer, null, typeof(FormatException) };
}
// String contains garbage
foreach (NumberStyles style in new[] { NumberStyles.Integer, NumberStyles.HexNumber, NumberStyles.Any })
{
yield return new object[] { "Garbage", style, null, typeof(FormatException) };
yield return new object[] { "g", style, null, typeof(FormatException) };
yield return new object[] { "g1", style, null, typeof(FormatException) };
yield return new object[] { "1g", style, null, typeof(FormatException) };
yield return new object[] { "123g", style, null, typeof(FormatException) };
yield return new object[] { "g123", style, null, typeof(FormatException) };
yield return new object[] { "214748364g", style, null, typeof(FormatException) };
}
// String has leading zeros
yield return new object[] { "\0\0123", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "\0\0123", NumberStyles.Any, null, typeof(FormatException) };
// String has internal zeros
yield return new object[] { "1\023", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1\023", NumberStyles.Any, null, typeof(FormatException) };
// String has trailing zeros but with whitespace after
yield return new object[] { "123\0\0 ", NumberStyles.Integer, null, typeof(FormatException) };
// Integer doesn't allow hex, exponents, paretheses, currency, thousands, decimal
yield return new object[] { "abc", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "1E23", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "(123)", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("C0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 1000.ToString("N0"), NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { 678.90.ToString("F2"), NumberStyles.Integer, null, typeof(FormatException) };
// HexNumber
yield return new object[] { "0xabc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "&habc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "G1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "g1", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
// None doesn't allow hex or leading or trailing whitespace
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { "123 ", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123", NumberStyles.None, null, typeof(FormatException) };
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) };
// AllowLeadingSign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+-123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-+123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "- 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "+ 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
// AllowTrailingSign
yield return new object[] { "123-+", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123+-", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 -", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "123 +", NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// Parentheses has priority over CurrencySymbol and PositiveSign
NumberFormatInfo currencyNegativeParenthesesFormat = new NumberFormatInfo()
{
CurrencySymbol = "(",
PositiveSign = "))"
};
yield return new object[] { "(100))", NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowTrailingSign, currencyNegativeParenthesesFormat, typeof(FormatException) };
// AllowTrailingSign and AllowLeadingSign
yield return new object[] { "+123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "+123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
yield return new object[] { "-123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) };
// AllowLeadingSign and AllowParentheses
yield return new object[] { "-(1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
yield return new object[] { "(-1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) };
// AllowLeadingWhite
yield return new object[] { "1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
yield return new object[] { " 1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) };
// AllowTrailingWhite
yield return new object[] { " 1 ", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
yield return new object[] { " 1", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) };
// AllowThousands
NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" };
yield return new object[] { "|||1", NumberStyles.AllowThousands, null, typeof(FormatException) };
// AllowExponent
yield return new object[] { "65E", NumberStyles.AllowExponent, null, typeof(FormatException) };
yield return new object[] { "65E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E+10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
yield return new object[] { "65E-1", NumberStyles.AllowExponent, null, typeof(OverflowException) };
// AllowDecimalPoint
NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "." };
yield return new object[] { "67.9", NumberStyles.AllowDecimalPoint, decimalFormat, typeof(OverflowException) };
// Parsing integers doesn't allow NaN, PositiveInfinity or NegativeInfinity
NumberFormatInfo doubleFormat = new NumberFormatInfo()
{
NaNSymbol = "NaN",
PositiveInfinitySymbol = "Infinity",
NegativeInfinitySymbol = "-Infinity"
};
yield return new object[] { "NaN", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
yield return new object[] { "-Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) };
// Only has a leading sign
yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) };
yield return new object[] { " +", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { " -", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "+ ", NumberStyles.Integer, null, typeof(FormatException) };
yield return new object[] { "- ", NumberStyles.Integer, null, typeof(FormatException) };
// NumberFormatInfo has a custom property with length > 1
NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" };
yield return new object[] { "123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, typeof(FormatException) };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { PositiveSign = "123" }, typeof(FormatException) };
yield return new object[] { "123", NumberStyles.AllowLeadingSign, new NumberFormatInfo() { NegativeSign = "123" }, typeof(FormatException) };
// Decimals not in range of Int32
foreach (string s in new[]
{
"2147483648", // int.MaxValue + 1
"2147483650", // 10s digit incremented above int.MaxValue
"10000000000", // extra digit after int.MaxValue
"4294967296", // uint.MaxValue + 1
"4294967300", // 100s digit incremented above uint.MaxValue
"9223372036854775808", // long.MaxValue + 1
"9223372036854775810", // 10s digit incremented above long.MaxValue
"10000000000000000000", // extra digit after long.MaxValue
"18446744073709551616", // ulong.MaxValue + 1
"18446744073709551620", // 10s digit incremented above ulong.MaxValue
"100000000000000000000", // extra digit after ulong.MaxValue
"-2147483649", // int.MinValue - 1
"-2147483650", // 10s digit decremented below int.MinValue
"-10000000000", // extra digit after int.MinValue
"-9223372036854775809", // long.MinValue - 1
"-9223372036854775810", // 10s digit decremented below long.MinValue
"-10000000000000000000", // extra digit after long.MinValue
"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000", // really big
"-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000" // really small
})
{
foreach (NumberStyles styles in new[] { NumberStyles.Any, NumberStyles.Integer })
{
yield return new object[] { s, styles, null, typeof(OverflowException) };
yield return new object[] { s + " ", styles, null, typeof(OverflowException) };
yield return new object[] { s + " " + "\0\0\0", styles, null, typeof(OverflowException) };
yield return new object[] { s + "g", styles, null, typeof(FormatException) };
yield return new object[] { s + "\0g", styles, null, typeof(FormatException) };
yield return new object[] { s + " g", styles, null, typeof(FormatException) };
}
}
// Hexadecimals not in range of Int32
foreach (string s in new[]
{
"100000000", // uint.MaxValue + 1
"FFFFFFFF0", // extra digit after uint.MaxValue
"10000000000000000", // ulong.MaxValue + 1
"FFFFFFFFFFFFFFFF0", // extra digit after ulong.MaxValue
"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000" // really big
})
{
yield return new object[] { s, NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + " ", NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + " " + "\0\0", NumberStyles.HexNumber, null, typeof(OverflowException) };
yield return new object[] { s + "g", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { s + "\0g", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { s + " g", NumberStyles.HexNumber, null, typeof(FormatException) };
}
yield return new object[] { "2147483649-", NumberStyles.AllowTrailingSign, null, typeof(OverflowException) };
yield return new object[] { "(2147483649)", NumberStyles.AllowParentheses, null, typeof(OverflowException) };
yield return new object[] { "2E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
int result;
// Default style and provider
if (style == NumberStyles.Integer && provider == null)
{
Assert.False(int.TryParse(value, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value));
}
// Default provider
if (provider == null)
{
Assert.Throws(exceptionType, () => int.Parse(value, style));
// Substitute default NumberFormatInfo
Assert.False(int.TryParse(value, style, new NumberFormatInfo(), out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value, style, new NumberFormatInfo()));
}
// Default style
if (style == NumberStyles.Integer)
{
Assert.Throws(exceptionType, () => int.Parse(value, provider));
}
// Full overloads
Assert.False(int.TryParse(value, style, provider, out result));
Assert.Equal(default, result);
Assert.Throws(exceptionType, () => int.Parse(value, style, provider));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
int result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => int.TryParse("1", style, null, out result));
Assert.Equal(default(int), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => int.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => int.Parse("1", style, null));
}
[Theory]
[InlineData("N")]
[InlineData("F")]
public static void ToString_N_F_EmptyNumberGroup_Success(string specifier)
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.NumberGroupSizes = new int[0];
nfi.NumberGroupSeparator = ",";
Assert.Equal("1234", 1234.ToString($"{specifier}0", nfi));
}
[Fact]
public static void ToString_P_EmptyPercentGroup_Success()
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.PercentGroupSizes = new int[0];
nfi.PercentSymbol = "%";
Assert.Equal("123400 %", 1234.ToString("P0", nfi));
}
[Fact]
public static void ToString_C_EmptyPercentGroup_Success()
{
var nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.CurrencyGroupSizes = new int[0];
nfi.CurrencySymbol = "$";
Assert.Equal("$1234", 1234.ToString("C0", nfi));
}
}
}
| |
using Foundation;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using UIKit;
using zsquared;
using static zsquared.C_MessageBox;
namespace vitaadmin
{
public partial class VC_Calendar : UIViewController
{
C_Global Global;
C_VitaUser LoggedInUser;
C_VitaSite SelectedSite;
bool DirtyExc;
C_CalendarEntry SelectedCalendarEntry;
C_TimePicker OpenShift;
C_TimePicker CloseShift;
C_ItemPicker DateInSeasonPicker;
C_WorkShift SelectedShift;
C_CalendarEntryTableManager CalendarEntriesTableManager;
C_ShiftTableManager ShiftTableManager;
List<C_SignUp> AllSignUps;
public VC_Calendar (IntPtr handle) : base (handle)
{
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
AllSignUps = new List<C_SignUp>();
AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
Global = myAppDelegate.Global;
LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId);
SelectedSite = Global.GetSiteFromSlugNoFetch(Global.SelectedSiteSlug);
L_ExcSite.Text = SelectedSite.Name;
OpenShift = new C_TimePicker(TB_ExcOpenShift);
OpenShift.TimePickerDone += (sender, e) =>
{
B_ExcSave.Enabled = true;
};
CloseShift = new C_TimePicker(TB_ExcCloseShift);
CloseShift.TimePickerDone += (sender, e) =>
{
B_ExcSave.Enabled = true;
};
CalendarEntriesTableManager = new C_CalendarEntryTableManager(this, TV_Exceptions, Global, SelectedSite.SiteCalendar);
CalendarEntriesTableManager.RowSelect += async (sender, e) =>
{
SelectedCalendarEntry = e.CalendarEntry;
if (!SelectedCalendarEntry.HaveShifts)
{
List<C_WorkShift> shifts = await Global.FetchAllShiftsForCalendarEntry(LoggedInUser.Token, SelectedSite.Slug, SelectedCalendarEntry);
}
PopulateCalendarEntry(e.CalendarEntry);
};
CalendarEntriesTableManager.RowDeselect += (sender, e) =>
{
DePopulateCalendarEntry(e.CalendarEntry);
SelectedCalendarEntry = null;
};
CalendarEntriesTableManager.RowDelete += async (sender, e) =>
{
C_CalendarEntry ceToDel = e.CalendarEntry;
if (ceToDel.WorkShifts.Count != 0)
{
var ok = await C_MessageBox.MessageBox(this, "Work Shifts Remain", "Cannot delete a Calendar Entry that still has shifts.", E_MessageBoxButtons.Ok);
}
else
{
C_IOResult ior = await Global.RemoveCalendarEntry(SelectedSite, LoggedInUser.Token, ceToDel);
if (!ior.Success)
{
var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok);
}
TV_Exceptions.ReloadData();
}
};
List<string> daysInSeason = new List<string>();
C_YMD date = SelectedSite.SeasonFirstDate;
do
{
daysInSeason.Add(date.ToString("yyyy-mm-dd"));
date = date.AddDays(1);
} while (date != SelectedSite.SeasonLastDate);
daysInSeason.Add(date.ToString("yyyy-mm-dd"));
DateInSeasonPicker = new C_ItemPicker(TB_DateForCalendarEntry, daysInSeason);
if ((C_YMD.Now >= SelectedSite.SeasonFirstDate) && (C_YMD.Now <= SelectedSite.SeasonLastDate))
DateInSeasonPicker.SetSelection(C_YMD.Now.ToString("yyyy-mm-dd"));
B_NewException.TouchUpInside += async (sender, e) =>
{
C_YMD newDate = null;
try
{
newDate = new C_YMD(TB_DateForCalendarEntry.Text);
}
catch (Exception e2)
{
#if DEBUG
Console.WriteLine(e2.Message);
#endif
}
if (newDate != null)
{
C_CalendarEntry newCE = new C_CalendarEntry
{
Date = newDate,
Dirty = false,
SiteID = SelectedSite.id,
SiteIsOpen = false
};
C_IOResult ior = await Global.CreateCalendarEntry(SelectedSite, LoggedInUser.Token, newCE);
if (!ior.Success)
{
var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok);
}
TV_Exceptions.ReloadData();
}
};
B_Back.TouchUpInside += (sender, e) =>
{
PerformSegue("Segue_CalendarToSite", this);
};
B_ExcSave.TouchUpInside += async (sender, e) =>
{
SelectedShift.OpenTime = OpenShift.Value;
SelectedShift.CloseTime = CloseShift.Value;
try { SelectedShift.NumBasicEFilers = Convert.ToInt32(TB_ExcBasicShift.Text); }
catch {}
try { SelectedShift.NumAdvEFilers = Convert.ToInt32(TB_ExcAdvShift.Text); }
catch { }
C_IOResult ior = await Global.UpdateShift(LoggedInUser.Token, SelectedSite.Slug, SelectedShift, SelectedCalendarEntry);
if (!ior.Success)
{
var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok);
}
B_ExcSave.Enabled = false;
CalendarEntriesTableManager.ReloadData();
TV_ExcShifts.ReloadData();
};
B_ExcNewShift.TouchUpInside += async (sender, e) =>
{
C_WorkShift nws = new C_WorkShift()
{
CalendarId = SelectedCalendarEntry.id,
CloseTime = new C_HMS(17, 00, 00),
OpenTime = new C_HMS(8, 0, 0),
NumBasicEFilers = 5,
NumAdvEFilers = 5,
SiteSlug = SelectedSite.Slug
};
AI_Busy.StartAnimating();
C_IOResult ior = await Global.CreateShift(LoggedInUser.Token, SelectedSite.Slug, nws, SelectedCalendarEntry);
AI_Busy.StopAnimating();
if (!ior.Success)
{
var ok = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, E_MessageBoxButtons.Ok);
}
ShiftTableManager.ReloadData();
};
SW_ExcIsOpen.ValueChanged += async (sender, e) =>
{
SelectedCalendarEntry.SiteIsOpen = SW_ExcIsOpen.On;
AI_Busy.StartAnimating();
C_IOResult ior = await Global.UpdateCalendarEntry(SelectedSite, LoggedInUser.Token, SelectedCalendarEntry);
AI_Busy.StopAnimating();
if (!ior.Success)
{
var ok = await C_MessageBox.MessageBox(this, "Error", "Unable to create new shift.", E_MessageBoxButtons.Ok);
}
CalendarEntriesTableManager.ReloadData();
};
TB_ExcBasicShift.AddTarget(TextField_ValueChanged, UIControlEvent.EditingChanged);
TB_ExcAdvShift.AddTarget(TextField_ValueChanged, UIControlEvent.EditingChanged);
DirtyExc = false;
EnableCalendarEntry(false);
EnableShift(false);
}
void TextField_ValueChanged(object sender, EventArgs e) => B_ExcSave.Enabled = true;
private void EnableCalendarEntry(bool en)
{
L_CalendarEntryFor.Hidden = !en;
TB_ExcDate.Hidden = !en;
TB_ExcDate.Enabled = en;
SW_ExcIsOpen.Hidden = !en;
SW_ExcIsOpen.Enabled = en;
L_SiteIsOpen.Hidden = !en;
L_Shifts.Hidden = !en;
TV_ExcShifts.Hidden = !en;
TV_ExcShifts.UserInteractionEnabled = en;
L_DeleteShift.Hidden = !en;
B_ExcNewShift.Hidden = !en;
B_ExcNewShift.Enabled = en;
}
private void PopulateCalendarEntry(C_CalendarEntry ce)
{
EnableCalendarEntry(true);
SW_ExcIsOpen.On = ce.SiteIsOpen;
TB_ExcDate.Text = ce.Date.ToString("yyyy-mm-dd");
ShiftTableManager = new C_ShiftTableManager(this, TV_ExcShifts, Global, ce.WorkShifts, ce);
ShiftTableManager.RowSelect += (sender, e) =>
{
SelectedShift = e.Shift;
PopulateShift(e.Shift);
};
ShiftTableManager.RowDeselect += (sender, e) =>
{
DePopulateShift(e.Shift);
SelectedShift = null;
};
ShiftTableManager.RowDelete += async (sender, e) =>
{
C_WorkShift shiftToDelete = e.Shift;
List<C_SignUp> sus = Global.GetSignUpsByShiftId(shiftToDelete.id);
if (sus.Count == 0)
{
C_IOResult ior = await Global.RemoveShift(LoggedInUser.Token, SelectedSite.Slug, shiftToDelete, SelectedCalendarEntry);
if (ior.Success)
SelectedCalendarEntry.WorkShifts.Remove(shiftToDelete);
ShiftTableManager.ReloadData();
}
else
{
C_MessageBox.E_MessageBoxResults mbresx = await C_MessageBox.MessageBox(this, "Users Signed Up", "We can't delete a shift with users signed up.", C_MessageBox.E_MessageBoxButtons.Ok);
}
};
DePopulateShift(SelectedShift);
}
private void DePopulateCalendarEntry(C_CalendarEntry ce)
{
ce.SiteIsOpen = SW_ExcIsOpen.On;
DePopulateShift(SelectedShift);
EnableCalendarEntry(false);
}
private void EnableShift(bool en)
{
L_ShiftDetails.Hidden = !en;
L_Open.Hidden = !en;
L_Close.Hidden = !en;
L_Basic.Hidden = !en;
L_Advanced.Hidden = !en;
TB_ExcOpenShift.Hidden = !en;
TB_ExcOpenShift.Enabled = en;
TB_ExcCloseShift.Hidden = !en;
TB_ExcCloseShift.Enabled = en;
TB_ExcBasicShift.Hidden = !en;
TB_ExcBasicShift.Enabled = en;
TB_ExcAdvShift.Hidden = !en;
TB_ExcAdvShift.Enabled = en;
B_ExcSave.Hidden = !en;
B_ExcSave.Enabled = en && DirtyExc;
}
private void PopulateShift(C_WorkShift s)
{
EnableShift(true);
OpenShift.SetValue(s.OpenTime);
CloseShift.SetValue(s.CloseTime);
List<C_SignUp> sus = Global.GetSignUpsByShiftId(s.id);
L_UsersOnShift.Text = sus.Count.ToString() + " users signed up.";
TB_ExcBasicShift.Text = s.NumBasicEFilers.ToString();
TB_ExcAdvShift.Text = s.NumAdvEFilers.ToString();
}
private void DePopulateShift(C_WorkShift s)
{
EnableShift(false);
if (s == null)
return;
s.OpenTime = OpenShift.Value;
s.CloseTime = CloseShift.Value;
try { s.NumBasicEFilers = Convert.ToInt32(TB_ExcBasicShift.Text); }
catch { }
try { s.NumAdvEFilers = Convert.ToInt32(TB_ExcAdvShift.Text); }
catch { }
}
public class C_CalendarEntryTableManager
{
C_Global Global;
UIViewController OurVC;
UITableView TableView;
C_CalendarEntryTableSource TableSource;
C_CalendarEntryTableDelegate TableDelegate;
List<C_CalendarEntry> CalendarEntries;
public event CalendarEntryEventHandler RowSelect;
public event CalendarEntryEventHandler RowDeselect;
public event CalendarEntryEventHandler RowDelete;
public C_CalendarEntryTableManager(UIViewController vc, UITableView tableView, C_Global global, List<C_CalendarEntry> entries)
{
TableView = tableView;
Global = global;
CalendarEntries = entries;
OurVC = vc;
TableSource = new C_CalendarEntryTableSource(Global, CalendarEntries);
TableDelegate = new C_CalendarEntryTableDelegate(Global, OurVC, TableSource);
TableDelegate.RowSelect += (sender, e) =>
{
RowSelect?.Invoke(sender, e);
};
TableDelegate.RowDeselect += (sender, e) =>
{
RowDeselect?.Invoke(sender, e);
};
TableDelegate.RowDelete += (sender, e) =>
{
RowDelete?.Invoke(sender, e);
};
TableView.Source = TableSource;
TableView.Delegate = TableDelegate;
TableView.ReloadData();
}
public void ReloadData()
{
TableView.ReloadData();
}
public class C_CalendarEntryTableDelegate : UITableViewDelegate
{
readonly C_Global Global;
readonly UIViewController OurVC;
readonly C_CalendarEntryTableSource TableSource;
public event CalendarEntryEventHandler RowSelect;
public event CalendarEntryEventHandler RowDeselect;
public event CalendarEntryEventHandler RowDelete;
public C_CalendarEntryTableDelegate(C_Global global, UIViewController vc, C_CalendarEntryTableSource tsource)
{
Global = global;
OurVC = vc;
TableSource = tsource;
}
public override UITableViewRowAction[] EditActionsForRow(UITableView tableView, NSIndexPath indexPath)
{
UITableViewRowAction hiButton = UITableViewRowAction.Create(UITableViewRowActionStyle.Default, "Remove",
delegate
{
C_CalendarEntry ce = TableSource.CalendarEntries[indexPath.Row];
RowDelete?.Invoke(this, new C_CalendarEntryEventArgs(ce));
});
return new UITableViewRowAction[] { hiButton };
}
public override void RowDeselected(UITableView tableView, NSIndexPath indexPath)
{
C_CalendarEntry ce = TableSource.CalendarEntries[indexPath.Row];
RowDeselect?.Invoke(this, new C_CalendarEntryEventArgs(ce));
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
C_CalendarEntry ce = TableSource.CalendarEntries[indexPath.Row];
RowSelect?.Invoke(this, new C_CalendarEntryEventArgs(ce));
}
}
public class C_CalendarEntryTableSource : UITableViewSource
{
const string CellIdentifier = "TableCell_CalendarEntryTableSource";
readonly C_Global Global;
public readonly List<C_CalendarEntry> CalendarEntries;
public C_CalendarEntryTableSource(C_Global global, List<C_CalendarEntry> ce)
{
Global = global;
CalendarEntries = ce;
CalendarEntries.Sort(C_CalendarEntry.CompareByDate);
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return CalendarEntries.Count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
//---- if there are no cells to reuse, create a new one
if (cell == null)
cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier);
C_CalendarEntry ce = CalendarEntries[indexPath.Row];
string dow = C_YMD.DayOfWeekNames[(int)ce.Date.DayOfWeek];
cell.TextLabel.Text = dow + ", " + ce.Date.ToString("mmm dd, yyyy");
cell.DetailTextLabel.Text = ce.SiteIsOpen ? "Open" : "Closed";
return cell;
}
}
}
public class C_CalendarEntryEventArgs : EventArgs
{
public C_CalendarEntry CalendarEntry;
public C_CalendarEntryEventArgs(C_CalendarEntry ce)
{
CalendarEntry = ce;
}
}
public delegate void CalendarEntryEventHandler(object sender, C_CalendarEntryEventArgs e);
public class C_ShiftTableManager
{
C_Global Global;
UIViewController OurVC;
UITableView TableView;
C_CalendarEntry SelectedCalendarEntry;
C_ShiftTableSource TableSource;
C_ShiftTableDelegate TableDelegate;
List<C_WorkShift> Shifts;
public event ShiftEventHandler RowSelect;
public event ShiftEventHandler RowDeselect;
public event ShiftEventHandler RowDelete;
public C_ShiftTableManager(UIViewController vc, UITableView tableView, C_Global global, List<C_WorkShift> entries, C_CalendarEntry calEntry)
{
TableView = tableView;
Global = global;
Shifts = entries;
OurVC = vc;
SelectedCalendarEntry = calEntry;
TableSource = new C_ShiftTableSource(Global, Shifts, SelectedCalendarEntry);
TableDelegate = new C_ShiftTableDelegate(Global, OurVC, TableSource);
TableDelegate.RowSelect += (sender, e) =>
{
RowSelect?.Invoke(sender, e);
};
TableDelegate.RowDeselect += (sender, e) =>
{
RowDeselect?.Invoke(sender, e);
};
TableDelegate.RowDelete += (sender, e) =>
{
RowDelete?.Invoke(sender, e);
};
TableView.Source = TableSource;
TableView.Delegate = TableDelegate;
TableView.ReloadData();
}
public void ReloadData()
{
TableView.ReloadData();
}
public class C_ShiftTableDelegate : UITableViewDelegate
{
readonly C_Global Global;
readonly UIViewController OurVC;
readonly C_ShiftTableSource TableSource;
public event ShiftEventHandler RowSelect;
public event ShiftEventHandler RowDeselect;
public event ShiftEventHandler RowDelete;
public C_ShiftTableDelegate(C_Global global, UIViewController vc, C_ShiftTableSource tsource)
{
Global = global;
OurVC = vc;
TableSource = tsource;
}
public override UITableViewRowAction[] EditActionsForRow(UITableView tableView, NSIndexPath indexPath)
{
UITableViewRowAction hiButton = UITableViewRowAction.Create(UITableViewRowActionStyle.Default, "Remove",
delegate
{
C_WorkShift ce = TableSource.Shifts[indexPath.Row];
RowDelete?.Invoke(this, new C_ShiftEventArgs(ce));
});
return new UITableViewRowAction[] { hiButton };
}
public override void RowDeselected(UITableView tableView, NSIndexPath indexPath)
{
C_WorkShift ce = TableSource.Shifts[indexPath.Row];
RowDeselect?.Invoke(this, new C_ShiftEventArgs(ce));
}
public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
C_WorkShift ce = TableSource.Shifts[indexPath.Row];
RowSelect?.Invoke(this, new C_ShiftEventArgs(ce));
}
}
public class C_ShiftTableSource : UITableViewSource
{
const string CellIdentifier = "TableCell_CalendarEntryTableSource";
readonly C_Global Global;
public readonly List<C_WorkShift> Shifts;
readonly C_CalendarEntry SelectedCalendarEntry;
public C_ShiftTableSource(C_Global global, List<C_WorkShift> ce, C_CalendarEntry calEntry)
{
Global = global;
Shifts = ce;
SelectedCalendarEntry = calEntry;
}
public override nint RowsInSection(UITableView tableview, nint section)
{
return Shifts.Count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier);
//---- if there are no cells to reuse, create a new one
if (cell == null)
cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier);
C_WorkShift ce = Shifts[indexPath.Row];
cell.TextLabel.Text = SelectedCalendarEntry.Date.ToString("mmm dd, yyyy");
cell.DetailTextLabel.Text = ce.OpenTime.ToString("hh:mm p") + " - " + ce.CloseTime.ToString("hh:mm p");
return cell;
}
}
}
public class C_ShiftEventArgs : EventArgs
{
public C_WorkShift Shift;
public C_ShiftEventArgs(C_WorkShift ws)
{
Shift = ws;
}
}
public delegate void ShiftEventHandler(object sender, C_ShiftEventArgs e);
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.WebSecurityScanner.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedWebSecurityScannerClientTest
{
[xunit::FactAttribute]
public void CreateScanConfigRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
CreateScanConfigRequest request = new CreateScanConfigRequest
{
Parent = "parent7858e4d0",
ScanConfig = new ScanConfig(),
};
ScanConfig expectedResponse = new ScanConfig
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
MaxQps = -1198236314,
StartingUrls =
{
"starting_urls75fa5e9e",
},
Authentication = new ScanConfig.Types.Authentication(),
UserAgent = ScanConfig.Types.UserAgent.SafariIphone,
BlacklistPatterns =
{
"blacklist_patterns7a899f15",
},
Schedule = new ScanConfig.Types.Schedule(),
ExportToSecurityCommandCenter = ScanConfig.Types.ExportToSecurityCommandCenter.Unspecified,
RiskLevel = ScanConfig.Types.RiskLevel.Unspecified,
ManagedScan = true,
StaticIpScan = false,
};
mockGrpcClient.Setup(x => x.CreateScanConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanConfig response = client.CreateScanConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateScanConfigRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
CreateScanConfigRequest request = new CreateScanConfigRequest
{
Parent = "parent7858e4d0",
ScanConfig = new ScanConfig(),
};
ScanConfig expectedResponse = new ScanConfig
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
MaxQps = -1198236314,
StartingUrls =
{
"starting_urls75fa5e9e",
},
Authentication = new ScanConfig.Types.Authentication(),
UserAgent = ScanConfig.Types.UserAgent.SafariIphone,
BlacklistPatterns =
{
"blacklist_patterns7a899f15",
},
Schedule = new ScanConfig.Types.Schedule(),
ExportToSecurityCommandCenter = ScanConfig.Types.ExportToSecurityCommandCenter.Unspecified,
RiskLevel = ScanConfig.Types.RiskLevel.Unspecified,
ManagedScan = true,
StaticIpScan = false,
};
mockGrpcClient.Setup(x => x.CreateScanConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ScanConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanConfig responseCallSettings = await client.CreateScanConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ScanConfig responseCancellationToken = await client.CreateScanConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteScanConfigRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
DeleteScanConfigRequest request = new DeleteScanConfigRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteScanConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
client.DeleteScanConfig(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteScanConfigRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
DeleteScanConfigRequest request = new DeleteScanConfigRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteScanConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
await client.DeleteScanConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteScanConfigAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetScanConfigRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
GetScanConfigRequest request = new GetScanConfigRequest
{
Name = "name1c9368b0",
};
ScanConfig expectedResponse = new ScanConfig
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
MaxQps = -1198236314,
StartingUrls =
{
"starting_urls75fa5e9e",
},
Authentication = new ScanConfig.Types.Authentication(),
UserAgent = ScanConfig.Types.UserAgent.SafariIphone,
BlacklistPatterns =
{
"blacklist_patterns7a899f15",
},
Schedule = new ScanConfig.Types.Schedule(),
ExportToSecurityCommandCenter = ScanConfig.Types.ExportToSecurityCommandCenter.Unspecified,
RiskLevel = ScanConfig.Types.RiskLevel.Unspecified,
ManagedScan = true,
StaticIpScan = false,
};
mockGrpcClient.Setup(x => x.GetScanConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanConfig response = client.GetScanConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetScanConfigRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
GetScanConfigRequest request = new GetScanConfigRequest
{
Name = "name1c9368b0",
};
ScanConfig expectedResponse = new ScanConfig
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
MaxQps = -1198236314,
StartingUrls =
{
"starting_urls75fa5e9e",
},
Authentication = new ScanConfig.Types.Authentication(),
UserAgent = ScanConfig.Types.UserAgent.SafariIphone,
BlacklistPatterns =
{
"blacklist_patterns7a899f15",
},
Schedule = new ScanConfig.Types.Schedule(),
ExportToSecurityCommandCenter = ScanConfig.Types.ExportToSecurityCommandCenter.Unspecified,
RiskLevel = ScanConfig.Types.RiskLevel.Unspecified,
ManagedScan = true,
StaticIpScan = false,
};
mockGrpcClient.Setup(x => x.GetScanConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ScanConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanConfig responseCallSettings = await client.GetScanConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ScanConfig responseCancellationToken = await client.GetScanConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateScanConfigRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
UpdateScanConfigRequest request = new UpdateScanConfigRequest
{
ScanConfig = new ScanConfig(),
UpdateMask = new wkt::FieldMask(),
};
ScanConfig expectedResponse = new ScanConfig
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
MaxQps = -1198236314,
StartingUrls =
{
"starting_urls75fa5e9e",
},
Authentication = new ScanConfig.Types.Authentication(),
UserAgent = ScanConfig.Types.UserAgent.SafariIphone,
BlacklistPatterns =
{
"blacklist_patterns7a899f15",
},
Schedule = new ScanConfig.Types.Schedule(),
ExportToSecurityCommandCenter = ScanConfig.Types.ExportToSecurityCommandCenter.Unspecified,
RiskLevel = ScanConfig.Types.RiskLevel.Unspecified,
ManagedScan = true,
StaticIpScan = false,
};
mockGrpcClient.Setup(x => x.UpdateScanConfig(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanConfig response = client.UpdateScanConfig(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateScanConfigRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
UpdateScanConfigRequest request = new UpdateScanConfigRequest
{
ScanConfig = new ScanConfig(),
UpdateMask = new wkt::FieldMask(),
};
ScanConfig expectedResponse = new ScanConfig
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
MaxQps = -1198236314,
StartingUrls =
{
"starting_urls75fa5e9e",
},
Authentication = new ScanConfig.Types.Authentication(),
UserAgent = ScanConfig.Types.UserAgent.SafariIphone,
BlacklistPatterns =
{
"blacklist_patterns7a899f15",
},
Schedule = new ScanConfig.Types.Schedule(),
ExportToSecurityCommandCenter = ScanConfig.Types.ExportToSecurityCommandCenter.Unspecified,
RiskLevel = ScanConfig.Types.RiskLevel.Unspecified,
ManagedScan = true,
StaticIpScan = false,
};
mockGrpcClient.Setup(x => x.UpdateScanConfigAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ScanConfig>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanConfig responseCallSettings = await client.UpdateScanConfigAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ScanConfig responseCancellationToken = await client.UpdateScanConfigAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StartScanRunRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
StartScanRunRequest request = new StartScanRunRequest
{
Name = "name1c9368b0",
};
ScanRun expectedResponse = new ScanRun
{
Name = "name1c9368b0",
ExecutionState = ScanRun.Types.ExecutionState.Unspecified,
ResultState = ScanRun.Types.ResultState.Killed,
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UrlsCrawledCount = 2307837720024124869L,
UrlsTestedCount = -373604950692105735L,
HasVulnerabilities = true,
ProgressPercent = -412774427,
ErrorTrace = new ScanRunErrorTrace(),
WarningTraces =
{
new ScanRunWarningTrace(),
},
};
mockGrpcClient.Setup(x => x.StartScanRun(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanRun response = client.StartScanRun(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StartScanRunRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
StartScanRunRequest request = new StartScanRunRequest
{
Name = "name1c9368b0",
};
ScanRun expectedResponse = new ScanRun
{
Name = "name1c9368b0",
ExecutionState = ScanRun.Types.ExecutionState.Unspecified,
ResultState = ScanRun.Types.ResultState.Killed,
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UrlsCrawledCount = 2307837720024124869L,
UrlsTestedCount = -373604950692105735L,
HasVulnerabilities = true,
ProgressPercent = -412774427,
ErrorTrace = new ScanRunErrorTrace(),
WarningTraces =
{
new ScanRunWarningTrace(),
},
};
mockGrpcClient.Setup(x => x.StartScanRunAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ScanRun>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanRun responseCallSettings = await client.StartScanRunAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ScanRun responseCancellationToken = await client.StartScanRunAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetScanRunRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
GetScanRunRequest request = new GetScanRunRequest
{
Name = "name1c9368b0",
};
ScanRun expectedResponse = new ScanRun
{
Name = "name1c9368b0",
ExecutionState = ScanRun.Types.ExecutionState.Unspecified,
ResultState = ScanRun.Types.ResultState.Killed,
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UrlsCrawledCount = 2307837720024124869L,
UrlsTestedCount = -373604950692105735L,
HasVulnerabilities = true,
ProgressPercent = -412774427,
ErrorTrace = new ScanRunErrorTrace(),
WarningTraces =
{
new ScanRunWarningTrace(),
},
};
mockGrpcClient.Setup(x => x.GetScanRun(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanRun response = client.GetScanRun(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetScanRunRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
GetScanRunRequest request = new GetScanRunRequest
{
Name = "name1c9368b0",
};
ScanRun expectedResponse = new ScanRun
{
Name = "name1c9368b0",
ExecutionState = ScanRun.Types.ExecutionState.Unspecified,
ResultState = ScanRun.Types.ResultState.Killed,
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UrlsCrawledCount = 2307837720024124869L,
UrlsTestedCount = -373604950692105735L,
HasVulnerabilities = true,
ProgressPercent = -412774427,
ErrorTrace = new ScanRunErrorTrace(),
WarningTraces =
{
new ScanRunWarningTrace(),
},
};
mockGrpcClient.Setup(x => x.GetScanRunAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ScanRun>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanRun responseCallSettings = await client.GetScanRunAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ScanRun responseCancellationToken = await client.GetScanRunAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void StopScanRunRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
StopScanRunRequest request = new StopScanRunRequest
{
Name = "name1c9368b0",
};
ScanRun expectedResponse = new ScanRun
{
Name = "name1c9368b0",
ExecutionState = ScanRun.Types.ExecutionState.Unspecified,
ResultState = ScanRun.Types.ResultState.Killed,
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UrlsCrawledCount = 2307837720024124869L,
UrlsTestedCount = -373604950692105735L,
HasVulnerabilities = true,
ProgressPercent = -412774427,
ErrorTrace = new ScanRunErrorTrace(),
WarningTraces =
{
new ScanRunWarningTrace(),
},
};
mockGrpcClient.Setup(x => x.StopScanRun(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanRun response = client.StopScanRun(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task StopScanRunRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
StopScanRunRequest request = new StopScanRunRequest
{
Name = "name1c9368b0",
};
ScanRun expectedResponse = new ScanRun
{
Name = "name1c9368b0",
ExecutionState = ScanRun.Types.ExecutionState.Unspecified,
ResultState = ScanRun.Types.ResultState.Killed,
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
UrlsCrawledCount = 2307837720024124869L,
UrlsTestedCount = -373604950692105735L,
HasVulnerabilities = true,
ProgressPercent = -412774427,
ErrorTrace = new ScanRunErrorTrace(),
WarningTraces =
{
new ScanRunWarningTrace(),
},
};
mockGrpcClient.Setup(x => x.StopScanRunAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ScanRun>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ScanRun responseCallSettings = await client.StopScanRunAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ScanRun responseCancellationToken = await client.StopScanRunAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFindingRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
GetFindingRequest request = new GetFindingRequest
{
Name = "name1c9368b0",
};
Finding expectedResponse = new Finding
{
FindingName = FindingName.FromProjectScanConfigScanRunFinding("[PROJECT]", "[SCAN_CONFIG]", "[SCAN_RUN]", "[FINDING]"),
FindingType = "finding_type0aa10781",
HttpMethod = "http_method901a5d34",
FuzzedUrl = "fuzzed_urlf49dd7ba",
Body = "body682d1a84",
Description = "description2cf9da67",
ReproductionUrl = "reproduction_url0e37b71f",
FrameUrl = "frame_urlbbc6a753",
FinalUrl = "final_url01c3df1e",
TrackingId = "tracking_idc631de68",
OutdatedLibrary = new OutdatedLibrary(),
ViolatingResource = new ViolatingResource(),
VulnerableParameters = new VulnerableParameters(),
Xss = new Xss(),
VulnerableHeaders = new VulnerableHeaders(),
Form = new Form(),
Severity = Finding.Types.Severity.Medium,
};
mockGrpcClient.Setup(x => x.GetFinding(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
Finding response = client.GetFinding(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFindingRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
GetFindingRequest request = new GetFindingRequest
{
Name = "name1c9368b0",
};
Finding expectedResponse = new Finding
{
FindingName = FindingName.FromProjectScanConfigScanRunFinding("[PROJECT]", "[SCAN_CONFIG]", "[SCAN_RUN]", "[FINDING]"),
FindingType = "finding_type0aa10781",
HttpMethod = "http_method901a5d34",
FuzzedUrl = "fuzzed_urlf49dd7ba",
Body = "body682d1a84",
Description = "description2cf9da67",
ReproductionUrl = "reproduction_url0e37b71f",
FrameUrl = "frame_urlbbc6a753",
FinalUrl = "final_url01c3df1e",
TrackingId = "tracking_idc631de68",
OutdatedLibrary = new OutdatedLibrary(),
ViolatingResource = new ViolatingResource(),
VulnerableParameters = new VulnerableParameters(),
Xss = new Xss(),
VulnerableHeaders = new VulnerableHeaders(),
Form = new Form(),
Severity = Finding.Types.Severity.Medium,
};
mockGrpcClient.Setup(x => x.GetFindingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Finding>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
Finding responseCallSettings = await client.GetFindingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Finding responseCancellationToken = await client.GetFindingAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void ListFindingTypeStatsRequestObject()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
ListFindingTypeStatsRequest request = new ListFindingTypeStatsRequest
{
Parent = "parent7858e4d0",
};
ListFindingTypeStatsResponse expectedResponse = new ListFindingTypeStatsResponse
{
FindingTypeStats =
{
new FindingTypeStats(),
},
};
mockGrpcClient.Setup(x => x.ListFindingTypeStats(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ListFindingTypeStatsResponse response = client.ListFindingTypeStats(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task ListFindingTypeStatsRequestObjectAsync()
{
moq::Mock<WebSecurityScanner.WebSecurityScannerClient> mockGrpcClient = new moq::Mock<WebSecurityScanner.WebSecurityScannerClient>(moq::MockBehavior.Strict);
ListFindingTypeStatsRequest request = new ListFindingTypeStatsRequest
{
Parent = "parent7858e4d0",
};
ListFindingTypeStatsResponse expectedResponse = new ListFindingTypeStatsResponse
{
FindingTypeStats =
{
new FindingTypeStats(),
},
};
mockGrpcClient.Setup(x => x.ListFindingTypeStatsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListFindingTypeStatsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WebSecurityScannerClient client = new WebSecurityScannerClientImpl(mockGrpcClient.Object, null);
ListFindingTypeStatsResponse responseCallSettings = await client.ListFindingTypeStatsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ListFindingTypeStatsResponse responseCancellationToken = await client.ListFindingTypeStatsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Globalization;
using System.Abstract.Parts;
namespace System.Abstract
{
/// <summary>
/// ServiceLogExtensions
/// </summary>
public static class ServiceLogExtensions
{
// get
/// <summary>
/// Gets the specified service.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <returns></returns>
public static IServiceLog Get<T>(this IServiceLog service) { return service.Get(typeof(T)); }
// log
/// <summary>
/// Fatals the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
public static void Fatal(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Fatal, null, s); }
/// <summary>
/// Fatals the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
public static void Fatal(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Fatal, ex, null); }
/// <summary>
/// Fatals the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void FatalFormat(this IServiceLog service, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Fatal, null, s);
}
/// <summary>
/// Fatals the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void FatalFormat(this IServiceLog service, Exception ex, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Fatal, ex, s);
}
/// <summary>
/// Errors the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
public static void Error(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Error, null, s); }
/// <summary>
/// Errors the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
public static void Error(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Error, ex, null); }
/// <summary>
/// Errors the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void ErrorFormat(this IServiceLog service, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Error, null, s);
}
/// <summary>
/// Errors the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void ErrorFormat(this IServiceLog service, Exception ex, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Error, ex, s);
}
/// <summary>
/// Warnings the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
public static void Warning(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Warning, null, s); }
/// <summary>
/// Warnings the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
public static void Warning(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Warning, ex, null); }
/// <summary>
/// Warnings the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void WarningFormat(this IServiceLog service, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Warning, null, s);
}
/// <summary>
/// Warnings the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void WarningFormat(this IServiceLog service, Exception ex, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Warning, ex, s);
}
/// <summary>
/// Informations the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
public static void Information(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Information, null, s); }
/// <summary>
/// Informations the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
public static void Information(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Information, ex, null); }
/// <summary>
/// Informations the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void InformationFormat(this IServiceLog service, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Information, null, s);
}
/// <summary>
/// Informations the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void InformationFormat(this IServiceLog service, Exception ex, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Information, ex, s);
}
/// <summary>
/// Debugs the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
public static void Debug(this IServiceLog service, string s) { service.Write(ServiceLog.LogLevel.Debug, null, s); }
/// <summary>
/// Debugs the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
public static void Debug(this IServiceLog service, Exception ex) { service.Write(ServiceLog.LogLevel.Debug, ex, null); }
/// <summary>
/// Debugs the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void DebugFormat(this IServiceLog service, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Debug, null, s);
}
/// <summary>
/// Debugs the specified service.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ex">The ex.</param>
/// <param name="s">The s.</param>
/// <param name="args">The args.</param>
public static void DebugFormat(this IServiceLog service, Exception ex, string s, params object[] args)
{
s = (!string.IsNullOrEmpty(s) ? string.Format(CultureInfo.CurrentCulture, s, args) : string.Empty);
service.Write(ServiceLog.LogLevel.Debug, ex, s);
}
#region BehaveAs
/// <summary>
/// Behaves as.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <returns></returns>
public static T BehaveAs<T>(this IServiceLog service)
where T : class, IServiceLog
{
IServiceWrapper<IServiceLog> serviceWrapper;
do
{
serviceWrapper = (service as IServiceWrapper<IServiceLog>);
if (serviceWrapper != null)
service = serviceWrapper.Parent;
} while (serviceWrapper != null);
return (service as T);
}
#endregion
#region Lazy Setup
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service)
where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, ServiceLocatorManager.Lazy, null); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, string name)
where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, ServiceLocatorManager.Lazy, name); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator)
where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, null); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator, string name)
where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, name); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, ServiceLocatorManager.Lazy, null); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, string name) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, ServiceLocatorManager.Lazy, name); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, null); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, Lazy<IServiceLocator> locator, string name) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, name); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, IServiceLocator locator)
where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, null); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator<T>(this Lazy<IServiceLog> service, IServiceLocator locator, string name)
where T : class, IServiceLog { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, name); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, IServiceLocator locator) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, null); return service; }
/// <summary>
/// Registers the with service locator.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="locator">The locator.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Lazy<IServiceLog> RegisterWithServiceLocator(this Lazy<IServiceLog> service, IServiceLocator locator, string name) { ServiceLogManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, name); return service; }
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
public partial struct ImmutableArray<T>
{
/// <summary>
/// A writable array accessor that can be converted into an <see cref="ImmutableArray{T}"/>
/// instance without allocating memory.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))]
public sealed class Builder : IList<T>, IReadOnlyList<T>
{
/// <summary>
/// The backing array for the builder.
/// </summary>
private T[] _elements;
/// <summary>
/// The number of initialized elements in the array.
/// </summary>
private int _count;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="capacity">The initial capacity of the internal array.</param>
internal Builder(int capacity)
{
Requires.Range(capacity >= 0, "capacity");
_elements = new T[capacity];
_count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
internal Builder()
: this(8)
{
}
/// <summary>
/// Get and sets the length of the internal array. When set the internal array is
/// reallocated to the given capacity if it is not already the specified length.
/// </summary>
public int Capacity
{
get { return _elements.Length; }
set
{
if (value < _count)
{
throw new ArgumentException(SR.CapacityMustBeGreaterThanOrEqualToCount, paramName: "value");
}
if (value != _elements.Length)
{
if (value > 0)
{
var temp = new T[value];
if (_count > 0)
{
Array.Copy(_elements, 0, temp, 0, _count);
}
_elements = temp;
}
else
{
_elements = ImmutableArray<T>.Empty.array;
}
}
}
}
/// <summary>
/// Gets or sets the length of the builder.
/// </summary>
/// <remarks>
/// If the value is decreased, the array contents are truncated.
/// If the value is increased, the added elements are initialized to the default value of type <typeparamref name="T"/>.
/// </remarks>
public int Count
{
get
{
return _count;
}
set
{
Requires.Range(value >= 0, "value");
if (value < _count)
{
// truncation mode
// Clear the elements of the elements that are effectively removed.
// PERF: Array.Clear works well for big arrays,
// but may have too much overhead with small ones (which is the common case here)
if (_count - value > 64)
{
Array.Clear(_elements, value, _count - value);
}
else
{
for (int i = value; i < this.Count; i++)
{
_elements[i] = default(T);
}
}
}
else if (value > _count)
{
// expansion
this.EnsureCapacity(value);
}
_count = value;
}
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// </exception>
public T this[int index]
{
get
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
return _elements[index];
}
set
{
if (index >= this.Count)
{
throw new IndexOutOfRangeException();
}
_elements[index] = value;
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Returns an immutable copy of the current contents of this collection.
/// </summary>
/// <returns>An immutable array.</returns>
public ImmutableArray<T> ToImmutable()
{
if (Count == 0)
{
return Empty;
}
return new ImmutableArray<T>(this.ToArray());
}
/// <summary>
/// Extracts the internal array as an <see cref="ImmutableArray{T}"/> and replaces it
/// with a zero length array.
/// </summary>
/// <exception cref="InvalidOperationException">When <see cref="ImmutableArray{T}.Builder.Count"/> doesn't
/// equal <see cref="ImmutableArray{T}.Builder.Capacity"/>.</exception>
public ImmutableArray<T> MoveToImmutable()
{
if (Capacity != Count)
{
throw new InvalidOperationException(SR.CapacityMustEqualCountOnMove);
}
T[] temp = _elements;
_elements = ImmutableArray<T>.Empty.array;
_count = 0;
return new ImmutableArray<T>(temp);
}
/// <summary>
/// Removes all items from the <see cref="ICollection{T}"/>.
/// </summary>
public void Clear()
{
this.Count = 0;
}
/// <summary>
/// Inserts an item to the <see cref="IList{T}"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="IList{T}"/>.</param>
public void Insert(int index, T item)
{
Requires.Range(index >= 0 && index <= this.Count, "index");
this.EnsureCapacity(this.Count + 1);
if (index < this.Count)
{
Array.Copy(_elements, index, _elements, index + 1, this.Count - index);
}
_count++;
_elements[index] = item;
}
/// <summary>
/// Adds an item to the <see cref="ICollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param>
public void Add(T item)
{
this.EnsureCapacity(this.Count + 1);
_elements[_count++] = item;
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(IEnumerable<T> items)
{
Requires.NotNull(items, "items");
int count;
if (items.TryGetCount(out count))
{
this.EnsureCapacity(this.Count + count);
}
foreach (var item in items)
{
this.Add(item);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(params T[] items)
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(TDerived[] items) where TDerived : T
{
Requires.NotNull(items, "items");
var offset = this.Count;
this.Count += items.Length;
Array.Copy(items, 0, _elements, offset, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(T[] items, int length)
{
Requires.NotNull(items, "items");
Requires.Range(length >= 0 && length <= items.Length, "length");
var offset = this.Count;
this.Count += length;
Array.Copy(items, 0, _elements, offset, length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(ImmutableArray<T> items)
{
this.AddRange(items, items.Length);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="length">The number of elements from the source array to add.</param>
public void AddRange(ImmutableArray<T> items, int length)
{
Requires.Range(length >= 0, "length");
if (items.array != null)
{
this.AddRange(items.array, length);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T
{
if (items.array != null)
{
this.AddRange(items.array);
}
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange(Builder items)
{
Requires.NotNull(items, "items");
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Adds the specified items to the end of the array.
/// </summary>
/// <param name="items">The items.</param>
public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T
{
Requires.NotNull(items, "items");
this.AddRange(items._elements, items.Count);
}
/// <summary>
/// Removes the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>A value indicating whether the specified element was found and removed from the collection.</returns>
public bool Remove(T element)
{
int index = this.IndexOf(element);
if (index >= 0)
{
this.RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Removes the <see cref="IList{T}"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
Requires.Range(index >= 0 && index < this.Count, "index");
if (index < this.Count - 1)
{
Array.Copy(_elements, index + 1, _elements, index, this.Count - index - 1);
}
this.Count--;
}
/// <summary>
/// Determines whether the <see cref="ICollection{T}"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false.
/// </returns>
public bool Contains(T item)
{
return this.IndexOf(item) >= 0;
}
/// <summary>
/// Creates a new array with the current contents of this Builder.
/// </summary>
public T[] ToArray()
{
T[] result = new T[this.Count];
Array.Copy(_elements, 0, result, 0, this.Count);
return result;
}
/// <summary>
/// Copies the current contents to the specified array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="index">The starting index of the target array.</param>
public void CopyTo(T[] array, int index)
{
Requires.NotNull(array, "array");
Requires.Range(index >= 0 && index + this.Count <= array.Length, "start");
Array.Copy(_elements, 0, array, index, this.Count);
}
/// <summary>
/// Resizes the array to accommodate the specified capacity requirement.
/// </summary>
/// <param name="capacity">The required capacity.</param>
private void EnsureCapacity(int capacity)
{
if (_elements.Length < capacity)
{
int newCapacity = Math.Max(_elements.Length * 2, capacity);
Array.Resize(ref _elements, newCapacity);
}
}
/// <summary>
/// Determines the index of a specific item in the <see cref="IList{T}"/>.
/// </summary>
/// <param name="item">The object to locate in the <see cref="IList{T}"/>.</param>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
[Pure]
public int IndexOf(T item)
{
return this.IndexOf(item, 0, _count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex)
{
return this.IndexOf(item, startIndex, this.Count - startIndex, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count)
{
return this.IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">
/// The equality comparer to use in the search.
/// If <c>null</c>, <see cref="EqualityComparer{T}.Default"/> is used.
/// </param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex + count <= this.Count, "count");
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.IndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i < startIndex + count; i++)
{
if (equalityComparer.Equals(_elements[i], item))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item)
{
if (this.Count == 0)
{
return -1;
}
return this.LastIndexOf(item, this.Count - 1, this.Count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex)
{
if (this.Count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
return this.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count)
{
return this.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Searches the array for the specified item in reverse.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <param name="startIndex">The index at which to begin the search.</param>
/// <param name="count">The number of elements to search.</param>
/// <param name="equalityComparer">The equality comparer to use in the search.</param>
/// <returns>The 0-based index into the array where the item was found; or -1 if it could not be found.</returns>
[Pure]
public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T> equalityComparer)
{
if (count == 0 && startIndex == 0)
{
return -1;
}
Requires.Range(startIndex >= 0 && startIndex < this.Count, "startIndex");
Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count");
equalityComparer = equalityComparer ?? EqualityComparer<T>.Default;
if (equalityComparer == EqualityComparer<T>.Default)
{
return Array.LastIndexOf(_elements, item, startIndex, count);
}
else
{
for (int i = startIndex; i >= startIndex - count + 1; i--)
{
if (equalityComparer.Equals(item, _elements[i]))
{
return i;
}
}
return -1;
}
}
/// <summary>
/// Reverses the order of elements in the collection.
/// </summary>
public void Reverse()
{
// The non-generic Array.Reverse is not used because it does not perform
// well for non-primitive value types.
// If/when a generic Array.Reverse<T> becomes available, the below code
// can be deleted and replaced with a call to Array.Reverse<T>.
int i = 0;
int j = _count - 1;
T[] array = _elements;
while (i < j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
/// <summary>
/// Sorts the array.
/// </summary>
public void Sort()
{
if (Count > 1)
{
Array.Sort(_elements, 0, this.Count, Comparer<T>.Default);
}
}
/// <summary>
/// Sorts the elements in the entire array using
/// the specified <see cref="Comparison{T}"/>.
/// </summary>
/// <param name="comparison">
/// The <see cref="Comparison{T}"/> to use when comparing elements.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception>
[Pure]
public void Sort(Comparison<T> comparison)
{
Requires.NotNull(comparison, "comparison");
if (Count > 1)
{
Array.Sort(_elements, comparison);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(IComparer<T> comparer)
{
if (Count > 1)
{
Array.Sort(_elements, 0, _count, comparer);
}
}
/// <summary>
/// Sorts the array.
/// </summary>
/// <param name="index">The index of the first element to consider in the sort.</param>
/// <param name="count">The number of elements to include in the sort.</param>
/// <param name="comparer">The comparer to use in sorting. If <c>null</c>, the default comparer is used.</param>
public void Sort(int index, int count, IComparer<T> comparer)
{
// Don't rely on Array.Sort's argument validation since our internal array may exceed
// the bounds of the publicly addressable region.
Requires.Range(index >= 0, "index");
Requires.Range(count >= 0 && index + count <= this.Count, "count");
if (count > 1)
{
Array.Sort(_elements, index, count, comparer);
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < this.Count; i++)
{
yield return this[i];
}
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Returns an enumerator for the contents of the array.
/// </summary>
/// <returns>An enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Adds items to this collection.
/// </summary>
/// <typeparam name="TDerived">The type of source elements.</typeparam>
/// <param name="items">The source array.</param>
/// <param name="length">The number of elements to add to this array.</param>
private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T
{
this.EnsureCapacity(this.Count + length);
var offset = this.Count;
this.Count += length;
var nodes = _elements;
for (int i = 0; i < length; i++)
{
nodes[offset + i] = items[i];
}
}
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal sealed class ImmutableArrayBuilderDebuggerProxy<T>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableArray<T>.Builder _builder;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableArrayBuilderDebuggerProxy{T}"/> class.
/// </summary>
/// <param name="builder">The collection to display in the debugger</param>
public ImmutableArrayBuilderDebuggerProxy(ImmutableArray<T>.Builder builder)
{
_builder = builder;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public T[] A
{
get
{
return _builder.ToArray();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.SubCommands
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DocAsCode;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Exceptions;
using Microsoft.DocAsCode.Plugins;
using Newtonsoft.Json;
internal sealed class InitCommand : ISubCommand
{
#region private members
private const string ConfigName = Constants.ConfigFileName;
private const string DefaultOutputFolder = "docfx_project";
private const string DefaultMetadataOutputFolder = "api";
private static readonly string[] DefaultExcludeFiles = new string[] { "obj/**" };
private static readonly string[] DefaultSrcExcludeFiles = new string[] { "**/obj/**", "**/bin/**" };
private readonly InitCommandOptions _options;
private static readonly IEnumerable<IQuestion> _metadataQuestions = new IQuestion[]
{
new MultiAnswerQuestion(
"What are the locations of your source code files?", (s, m, c) =>
{
if (s != null)
{
var exclude = new FileItems(DefaultSrcExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
var item = new FileMapping(new FileMappingItem(s) { Exclude = exclude });
m.Metadata.Add(new MetadataJsonItemConfig
{
Source = item,
Destination = DefaultMetadataOutputFolder,
});
m.Build.Content = new FileMapping(new FileMappingItem("api/**.yml", "api/index.md"));
}
},
new string[] { "src/**.csproj" }) {
Descriptions = new string[]
{
"Supported project files could be .sln, .csproj, .vbproj project files or .cs, .vb source files",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"What are the locations of your markdown files overwriting triple slash comments?", (s, m, c) =>
{
if (s != null)
{
var exclude = new FileItems(DefaultExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
m.Build.Overwrite = new FileMapping(new FileMappingItem(s) { Exclude = exclude });
}
},
new string[] { "apidoc/**.md" }) {
Descriptions = new string[]
{
"You can specify markdown files with a YAML header to overwrite summary, remarks and description for parameters",
Hints.Glob,
Hints.Enter,
}
},
};
private static readonly IEnumerable<IQuestion> _overallQuestion = new IQuestion[]
{
new SingleAnswerQuestion(
"Where to save the generated documentation?", (s, m, c) => {
m.Build.Destination = s;
},
"_site") {
Descriptions = new string[]
{
Hints.Enter,
}
},
};
private static readonly IEnumerable<IQuestion> _buildQuestions = new IQuestion[]
{
// TODO: Check if the input glob pattern matches any files
// IF no matching: WARN [init]: There is no file matching this pattern.
new MultiAnswerQuestion(
"What are the locations of your conceptual files?", (s, m, c) =>
{
if (s != null)
{
if (m.Build.Content == null)
{
m.Build.Content = new FileMapping();
}
var exclude = new FileItems(DefaultExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
m.Build.Content.Add(new FileMappingItem(s) { Exclude = exclude });
}
},
new string[] { "articles/**.md", "articles/**/toc.yml", "toc.yml", "*.md" }) {
Descriptions = new string[]
{
"Supported conceptual files could be any text files. Markdown format is also supported.",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"What are the locations of your resource files?", (s, m, c) =>
{
if (s != null)
{
var exclude = new FileItems(DefaultExcludeFiles);
if(!string.IsNullOrEmpty(m.Build.Destination))
{
exclude.Add($"{m.Build.Destination}/**");
}
m.Build.Resource = new FileMapping(new FileMappingItem(s) { Exclude = exclude });
}
},
new string[] { "images/**" }) {
Descriptions = new string[]
{
"The resource files which conceptual files are referencing, e.g. images.",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"Do you want to specify external API references?", (s, m, c) =>
{
if (s != null)
{
m.Build.ExternalReference = new FileMapping(new FileMappingItem(s));
}
},
null) {
Descriptions = new string[]
{
"Supported external API references can be in either JSON or YAML format.",
Hints.Glob,
Hints.Enter,
}
},
new MultiAnswerQuestion(
"What documentation templates do you want to use?", (s, m, c) => { if (s != null) m.Build.Templates.AddRange(s); },
new string[] { "default" }) {
Descriptions = new string[]
{
"You can define multiple templates in order. The latter one will overwrite the former one if names collide",
"Predefined templates in docfx are now: default, statictoc",
Hints.Enter,
}
}
};
private static readonly IEnumerable<IQuestion> _selectorQuestions = new IQuestion[]
{
new YesOrNoQuestion(
"Does the website contain API documentation from source code?", (s, m, c) =>
{
m.Build = new BuildJsonConfig();
if (s)
{
m.Metadata = new MetadataJsonConfig();
c.ContainsMetadata = true;
}
else
{
c.ContainsMetadata = false;
}
}),
};
#endregion
public string Name { get; } = nameof(InitCommand);
public bool AllowReplay => false;
public InitCommand(InitCommandOptions options)
{
_options = options;
}
public void Exec(SubCommandRunningContext context)
{
string outputFolder = null;
try
{
var config = new DefaultConfigModel();
var questionContext = new QuestionContext
{
Quiet = _options.Quiet
};
foreach (var question in _selectorQuestions)
{
question.Process(config, questionContext);
}
foreach (var question in _overallQuestion)
{
question.Process(config, questionContext);
}
if (questionContext.ContainsMetadata)
{
foreach (var question in _metadataQuestions)
{
question.Process(config, questionContext);
}
}
foreach (var question in _buildQuestions)
{
question.Process(config, questionContext);
}
if (_options.OnlyConfigFile)
{
GenerateConfigFile(_options.OutputFolder, config);
}
else
{
outputFolder = StringExtension.ToDisplayPath(Path.GetFullPath(string.IsNullOrEmpty(_options.OutputFolder) ? DefaultOutputFolder : _options.OutputFolder));
GenerateSeedProject(outputFolder, config);
}
}
catch (Exception e)
{
throw new DocfxInitException($"Error with init docfx project under \"{outputFolder}\" : {e.Message}", e);
}
}
private static void GenerateConfigFile(string outputFolder, object config)
{
var path = StringExtension.ToDisplayPath(Path.Combine(outputFolder ?? string.Empty, ConfigName));
if (File.Exists(path))
{
if (!ProcessOverwriteQuestion($"Config file \"{path}\" already exists, do you want to overwrite this file?"))
{
return;
}
}
SaveConfigFile(path, config);
$"Successfully generated default docfx config file to {path}".WriteLineToConsole(ConsoleColor.Green);
}
private static void GenerateSeedProject(string outputFolder, DefaultConfigModel config)
{
if (Directory.Exists(outputFolder))
{
if (!ProcessOverwriteQuestion($"Output folder \"{outputFolder}\" already exists. Do you still want to generate files into this folder? You can use -o command option to specify the folder name"))
{
return;
}
}
else
{
Directory.CreateDirectory(outputFolder);
}
// 1. Create default files
var srcFolder = Path.Combine(outputFolder, "src");
var apiFolder = Path.Combine(outputFolder, "api");
var apidocFolder = Path.Combine(outputFolder, "apidoc");
var articleFolder = Path.Combine(outputFolder, "articles");
var imageFolder = Path.Combine(outputFolder, "images");
var folders = new string[] { srcFolder, apiFolder, apidocFolder, articleFolder, imageFolder };
foreach (var folder in folders)
{
Directory.CreateDirectory(folder);
$"Created folder {StringExtension.ToDisplayPath(folder)}".WriteLineToConsole(ConsoleColor.Gray);
}
// 2. Create default files
// a. toc.yml
// b. index.md
// c. articles/toc.yml
// d. articles/index.md
// e. .gitignore
// f. api/.gitignore
// TODO: move api/index.md out to some other folder
var tocYaml = Tuple.Create("toc.yml", @"- name: Articles
href: articles/
- name: Api Documentation
href: api/
homepage: api/index.md
");
var indexMarkdownFile = Tuple.Create("index.md", @"# This is the **HOMEPAGE**.
Refer to [Markdown](http://daringfireball.net/projects/markdown/) for how to write markdown files.
## Quick Start Notes:
1. Add images to the *images* folder if the file is referencing an image.
");
var apiTocFile = Tuple.Create("api/toc.yml", @"- name: TO BE REPLACED
- href: index.md
");
var apiIndexFile = Tuple.Create("api/index.md", @"# PLACEHOLDER
TODO: Add .NET projects to the *src* folder and run `docfx` to generate **REAL** *API Documentation*!
");
var articleTocFile = Tuple.Create("articles/toc.yml", @"- name: Introduction
href: intro.md
");
var articleMarkdownFile = Tuple.Create("articles/intro.md", @"# Add your introductions here!
");
var gitignore = Tuple.Create(".gitignore", $@"###############
# folder #
###############
/**/DROP/
/**/TEMP/
/**/packages/
/**/bin/
/**/obj/
{config.Build.Destination}
");
var apiGitignore = Tuple.Create("api/.gitignore", $@"###############
# temp file #
###############
*.yml
");
var files = new Tuple<string, string>[] { tocYaml, indexMarkdownFile, apiTocFile, apiIndexFile, articleTocFile, articleMarkdownFile, gitignore, apiGitignore };
foreach (var file in files)
{
var filePath = Path.Combine(outputFolder, file.Item1);
var content = file.Item2;
var dir = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(filePath, content);
$"Created File {StringExtension.ToDisplayPath(filePath)}".WriteLineToConsole(ConsoleColor.Gray);
}
// 2. Create docfx.json
var path = Path.Combine(outputFolder ?? string.Empty, ConfigName);
SaveConfigFile(path, config);
$"Created config file {StringExtension.ToDisplayPath(path)}".WriteLineToConsole(ConsoleColor.Gray);
$"Successfully generated default docfx project to {StringExtension.ToDisplayPath(outputFolder)}".WriteLineToConsole(ConsoleColor.Green);
"Please run:".WriteLineToConsole(ConsoleColor.Gray);
$"\tdocfx \"{StringExtension.ToDisplayPath(path)}\" --serve".WriteLineToConsole(ConsoleColor.White);
"To generate a default docfx website.".WriteLineToConsole(ConsoleColor.Gray);
}
private static void SaveConfigFile(string path, object config)
{
JsonUtility.Serialize(path, config, Formatting.Indented);
}
private static bool ProcessOverwriteQuestion(string message)
{
bool overwrited = true;
var overwriteQuestion = new NoOrYesQuestion(
message,
(s, m, c) =>
{
if (!s)
{
overwrited = false;
}
});
overwriteQuestion.Process(null, new QuestionContext { NeedWarning = overwrited });
return overwrited;
}
#region Question classes
private static class YesOrNoOption
{
public const string YesAnswer = "Yes";
public const string NoAnswer = "No";
}
/// <summary>
/// the default option is Yes
/// </summary>
private sealed class YesOrNoQuestion : SingleChoiceQuestion<bool>
{
private static readonly string[] YesOrNoAnswer = { YesOrNoOption.YesAnswer, YesOrNoOption.NoAnswer };
public YesOrNoQuestion(string content, Action<bool, DefaultConfigModel, QuestionContext> setter) : base(content, setter, Converter, YesOrNoAnswer)
{
}
private static bool Converter(string input)
{
return input == YesOrNoOption.YesAnswer;
}
}
/// <summary>
/// the default option is No
/// </summary>
private sealed class NoOrYesQuestion : SingleChoiceQuestion<bool>
{
private static readonly string[] NoOrYesAnswer = { YesOrNoOption.NoAnswer, YesOrNoOption.YesAnswer };
public NoOrYesQuestion(string content, Action<bool, DefaultConfigModel, QuestionContext> setter) : base(content, setter, Converter, NoOrYesAnswer)
{
}
private static bool Converter(string input)
{
return input == YesOrNoOption.YesAnswer;
}
}
private class SingleChoiceQuestion<T> : Question<T>
{
private Func<string, T> _converter;
/// <summary>
/// Options, the first one as the default one
/// </summary>
public string[] Options { get; set; }
public SingleChoiceQuestion(string content, Action<T, DefaultConfigModel, QuestionContext> setter, Func<string, T> converter, params string[] options)
: base(content, setter)
{
if (options == null || options.Length == 0) throw new ArgumentNullException(nameof(options));
if (converter == null) throw new ArgumentNullException(nameof(converter));
_converter = converter;
Options = options;
DefaultAnswer = options[0];
DefaultValue = converter(DefaultAnswer);
}
protected override T GetAnswer()
{
var options = Options;
Console.Write("Choose Answer ({0}): ", string.Join("/", options));
Console.Write(DefaultAnswer[0]);
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
string matched = null;
var line = Console.ReadLine();
while (!string.IsNullOrEmpty(line))
{
matched = GetMatchedOption(options, line);
if (matched == null)
{
Console.Write("Invalid Answer, please reenter: ");
}
else
{
return _converter(matched);
}
line = Console.ReadLine();
}
return DefaultValue;
}
private static string GetMatchedOption(string[] options, string input)
{
return options.FirstOrDefault(s => s.Equals(input, StringComparison.OrdinalIgnoreCase) || s.Substring(0, 1).Equals(input, StringComparison.OrdinalIgnoreCase));
}
}
private sealed class MultiAnswerQuestion : Question<string[]>
{
public MultiAnswerQuestion(string content, Action<string[], DefaultConfigModel, QuestionContext> setter, string[] defaultValue = null)
: base(content, setter)
{
DefaultValue = defaultValue;
DefaultAnswer = ConvertToString(defaultValue);
}
protected override string[] GetAnswer()
{
var line = Console.ReadLine();
List<string> answers = new List<string>();
while (!string.IsNullOrEmpty(line))
{
answers.Add(line);
line = Console.ReadLine();
}
if (answers.Count > 0)
{
return answers.ToArray();
}
else
{
return DefaultValue;
}
}
private static string ConvertToString(string[] array)
{
if (array == null) return null;
return string.Join(",", array);
}
}
private sealed class SingleAnswerQuestion : Question<string>
{
public SingleAnswerQuestion(string content, Action<string, DefaultConfigModel, QuestionContext> setter, string defaultAnswer = null)
: base(content, setter)
{
DefaultValue = defaultAnswer;
DefaultAnswer = defaultAnswer;
}
protected override string GetAnswer()
{
var line = Console.ReadLine();
if (!string.IsNullOrEmpty(line))
{
return line;
}
else
{
return DefaultValue;
}
}
}
private abstract class Question<T> : IQuestion
{
private Action<T, DefaultConfigModel, QuestionContext> _setter { get; }
public string Content { get; }
/// <summary>
/// Each string stands for one line
/// </summary>
public string[] Descriptions { get; set; }
public T DefaultValue { get; protected set; }
public string DefaultAnswer { get; protected set; }
public Question(string content, Action<T, DefaultConfigModel, QuestionContext> setter)
{
if (setter == null) throw new ArgumentNullException(nameof(setter));
Content = content;
_setter = setter;
}
public void Process(DefaultConfigModel model, QuestionContext context)
{
if (context.Quiet)
{
_setter(DefaultValue, model, context);
}
else
{
WriteQuestion(context);
var value = GetAnswer();
_setter(value, model, context);
}
}
protected abstract T GetAnswer();
private void WriteQuestion(QuestionContext context)
{
Content.WriteToConsole(context.NeedWarning ? ConsoleColor.Yellow : ConsoleColor.White);
WriteDefaultAnswer();
Descriptions.WriteLinesToConsole(ConsoleColor.Gray);
}
private void WriteDefaultAnswer()
{
if (DefaultAnswer == null)
{
Console.WriteLine();
return;
}
" (Default: ".WriteToConsole(ConsoleColor.Gray);
DefaultAnswer.WriteToConsole(ConsoleColor.Green);
")".WriteLineToConsole(ConsoleColor.Gray);
}
}
private interface IQuestion
{
void Process(DefaultConfigModel model, QuestionContext context);
}
private sealed class QuestionContext
{
public bool Quiet { get; set; }
public bool ContainsMetadata { get; set; }
public bool NeedWarning { get; set; }
}
#endregion
private static class Hints
{
public const string Tab = "Press TAB to list possible options.";
public const string Enter = "Press ENTER to move to the next question.";
public const string Glob = "You can use glob patterns, e.g. src/**";
}
private class DefaultConfigModel
{
[JsonProperty("metadata")]
public MetadataJsonConfig Metadata { get; set; }
[JsonProperty("build")]
public BuildJsonConfig Build { get; set; }
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Util;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Base class for all graphs */
public abstract class NavGraph {
/** Reference to the AstarPath object in the scene.
* Might not be entirely safe to use, it's better to use AstarPath.active
*/
public AstarPath active;
/** Used as an ID of the graph, considered to be unique.
* \note This is Pathfinding.Util.Guid not System.Guid. A replacement for System.Guid was coded for better compatibility with iOS
*/
[JsonMember]
public Guid guid;
/** Default penalty to apply to all nodes */
[JsonMember]
public uint initialPenalty;
/** Is the graph open in the editor */
[JsonMember]
public bool open;
/** Index of the graph, used for identification purposes */
public uint graphIndex;
/** Name of the graph.
* Can be set in the unity editor
*/
[JsonMember]
public string name;
[JsonMember]
public bool drawGizmos = true;
/** Used in the editor to check if the info screen is open.
* Should be inside UNITY_EDITOR only \#ifs but just in case anyone tries to serialize a NavGraph instance using Unity, I have left it like this as it would otherwise cause a crash when building.
* Version 3.0.8.1 was released because of this bug only
*/
[JsonMember]
public bool infoScreenOpen;
/** Count nodes in the graph.
* Note that this is, unless the graph type has overriden it, an O(n) operation.
*
* \todo GridGraph should override this
*/
public virtual int CountNodes () {
int count = 0;
GraphNodeDelegateCancelable del = node => {
count++;
return true;
};
GetNodes(del);
return count;
}
/** Calls a delegate with all nodes in the graph.
* This is the primary way of "looping" through all nodes in a graph.
*
* This function should not change anything in the graph structure.
*
* \code
* myGraph.GetNodes ((node) => {
* Debug.Log ("I found a node at position " + (Vector3)node.Position);
* return true;
* });
* \endcode
*/
public abstract void GetNodes (GraphNodeDelegateCancelable del);
/** A matrix for translating/rotating/scaling the graph.
* Not all graph generators sets this variable though.
*
* \note Do not set directly, use SetMatrix
*
* \note This value is not serialized. It is expected that graphs regenerate this
* field after deserialization has completed.
*/
public Matrix4x4 matrix = Matrix4x4.identity;
/** Inverse of \a matrix.
*
* \note Do not set directly, use SetMatrix
*
* \see matrix
*/
public Matrix4x4 inverseMatrix = Matrix4x4.identity;
/** Use to set both matrix and inverseMatrix at the same time */
public void SetMatrix (Matrix4x4 m) {
matrix = m;
inverseMatrix = m.inverse;
}
/** Relocates the nodes in this graph.
* Assumes the nodes are already transformed using the "oldMatrix", then transforms them
* such that it will look like they have only been transformed using the "newMatrix".
* The "oldMatrix" is not required by all implementations of this function though (e.g the NavMesh generator).
*
* The matrix the graph is transformed with is typically stored in the #matrix field, so the typical usage for this method is
* \code
* var myNewMatrix = Matrix4x4.TRS (...);
* myGraph.RelocateNodes (myGraph.matrix, myNewMatrix);
* \endcode
*
* So for example if you want to move all your nodes in e.g a point graph 10 units along the X axis from the initial position
* \code
* var graph = AstarPath.astarData.pointGraph;
* var m = Matrix4x4.TRS (new Vector3(10,0,0), Quaternion.identity, Vector3.one);
* graph.RelocateNodes (graph.matrix, m);
* \endcode
*
* \note For grid graphs it is recommended to use the helper method RelocateNodes which takes parameters for
* center and nodeSize (and additional parameters) instead since it is both easier to use and is less likely
* to mess up pathfinding.
*
* \warning This method is lossy, so calling it many times may cause node positions to lose precision.
* For example if you set the scale to 0 in one call, and then to 1 in the next call, it will not be able to
* recover the correct positions since when the scale was 0, all nodes were scaled/moved to the same point.
* The same thing happens for other - less extreme - values as well, but to a lesser degree.
*
* \version Prior to version 3.6.1 the oldMatrix and newMatrix parameters were reversed by mistake.
*/
public virtual void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) {
Matrix4x4 inv = oldMatrix.inverse;
Matrix4x4 m = newMatrix * inv;
GetNodes(delegate(GraphNode node) {
//Vector3 tmp = inv.MultiplyPoint3x4 ((Vector3)nodes[i].position);
node.position = ((Int3)m.MultiplyPoint((Vector3)node.position));
return true;
});
SetMatrix(newMatrix);
}
/** Returns the nearest node to a position using the default NNConstraint.
* \param position The position to try to find a close node to
* \see Pathfinding.NNConstraint.None
*/
public NNInfo GetNearest (Vector3 position) {
return GetNearest(position, NNConstraint.None);
}
/** Returns the nearest node to a position using the specified NNConstraint.
* \param position The position to try to find a close node to
* \param constraint Can for example tell the function to try to return a walkable node. If you do not get a good node back, consider calling GetNearestForce. */
public NNInfo GetNearest (Vector3 position, NNConstraint constraint) {
return GetNearest(position, constraint, null);
}
/** Returns the nearest node to a position using the specified NNConstraint.
* \param position The position to try to find a close node to
* \param hint Can be passed to enable some graph generators to find the nearest node faster.
* \param constraint Can for example tell the function to try to return a walkable node. If you do not get a good node back, consider calling GetNearestForce. */
public virtual NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
// This is a default implementation and it is pretty slow
// Graphs usually override this to provide faster and more specialised implementations
float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
float minDist = float.PositiveInfinity;
GraphNode minNode = null;
float minConstDist = float.PositiveInfinity;
GraphNode minConstNode = null;
// Loop through all nodes and find the closest suitable node
GetNodes(node => {
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
minNode = node;
}
if (dist < minConstDist && dist < maxDistSqr && constraint.Suitable(node)) {
minConstDist = dist;
minConstNode = node;
}
return true;
});
var nnInfo = new NNInfo(minNode);
nnInfo.constrainedNode = minConstNode;
if (minConstNode != null) {
nnInfo.constClampedPosition = (Vector3)minConstNode.position;
} else if (minNode != null) {
nnInfo.constrainedNode = minNode;
nnInfo.constClampedPosition = (Vector3)minNode.position;
}
return nnInfo;
}
/**
* Returns the nearest node to a position using the specified \link Pathfinding.NNConstraint constraint \endlink.
* \returns an NNInfo. This method will only return an empty NNInfo if there are no nodes which comply with the specified constraint.
*/
public virtual NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) {
return GetNearest(position, constraint);
}
/**
* This will be called on the same time as Awake on the gameObject which the AstarPath script is attached to. (remember, not in the editor)
* Use this for any initialization code which can't be placed in Scan
*/
public virtual void Awake () {
}
/** Function for cleaning up references.
* This will be called on the same time as OnDisable on the gameObject which the AstarPath script is attached to (remember, not in the editor).
* Use for any cleanup code such as cleaning up static variables which otherwise might prevent resources from being collected.
* Use by creating a function overriding this one in a graph class, but always call base.OnDestroy () in that function.
* All nodes should be destroyed in this function otherwise a memory leak will arise.
*/
public virtual void OnDestroy () {
//Destroy all nodes
GetNodes(delegate(GraphNode node) {
node.Destroy();
return true;
});
}
/*
* Consider using AstarPath.Scan () instead since this function might screw things up if there is more than one graph.
* This function does not perform all necessary postprocessing for the graph to work with pathfinding (e.g flood fill).
* See the source of the AstarPath.Scan function to see how it can be used.
* In almost all cases you should use AstarPath.Scan instead.
*/
public void ScanGraph () {
if (AstarPath.OnPreScan != null) {
AstarPath.OnPreScan(AstarPath.active);
}
if (AstarPath.OnGraphPreScan != null) {
AstarPath.OnGraphPreScan(this);
}
ScanInternal();
if (AstarPath.OnGraphPostScan != null) {
AstarPath.OnGraphPostScan(this);
}
if (AstarPath.OnPostScan != null) {
AstarPath.OnPostScan(AstarPath.active);
}
}
[System.Obsolete("Please use AstarPath.active.Scan or if you really want this.ScanInternal which has the same functionality as this method had")]
public void Scan () {
throw new System.Exception("This method is deprecated. Please use AstarPath.active.Scan or if you really want this.ScanInternal which has the same functionality as this method had.");
}
/** Internal method for scanning graphs */
public void ScanInternal () {
ScanInternal(null);
}
/**
* Scans the graph, called from AstarPath.ScanLoop.
* Override this function to implement custom scanning logic
* The statusCallback may be optionally called to show progress info in the editor
*/
public abstract void ScanInternal (OnScanStatus statusCallback);
/* Color to use for gizmos.
* Returns a color to be used for the specified node with the current debug settings (editor only).
*
* \version Since 3.6.1 this method will not handle null nodes
*/
public virtual Color NodeColor (GraphNode node, PathHandler data) {
Color c = AstarColor.NodeConnection;
switch (AstarPath.active.debugMode) {
case GraphDebugMode.Areas:
c = AstarColor.GetAreaColor(node.Area);
break;
case GraphDebugMode.Penalty:
c = Color.Lerp(AstarColor.ConnectionLowLerp, AstarColor.ConnectionHighLerp, ((float)node.Penalty-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
case GraphDebugMode.Tags:
c = AstarColor.GetAreaColor(node.Tag);
break;
default:
if (data == null) return AstarColor.NodeConnection;
PathNode nodeR = data.GetPathNode(node);
switch (AstarPath.active.debugMode) {
case GraphDebugMode.G:
c = Color.Lerp(AstarColor.ConnectionLowLerp, AstarColor.ConnectionHighLerp, ((float)nodeR.G-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
case GraphDebugMode.H:
c = Color.Lerp(AstarColor.ConnectionLowLerp, AstarColor.ConnectionHighLerp, ((float)nodeR.H-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
case GraphDebugMode.F:
c = Color.Lerp(AstarColor.ConnectionLowLerp, AstarColor.ConnectionHighLerp, ((float)nodeR.F-AstarPath.active.debugFloor) / (AstarPath.active.debugRoof-AstarPath.active.debugFloor));
break;
}
break;
}
c.a *= 0.5F;
return c;
}
/** Serializes graph type specific node data.
* This function can be overriden to serialize extra node information (or graph information for that matter)
* which cannot be serialized using the standard serialization.
* Serialize the data in any way you want and return a byte array.
* When loading, the exact same byte array will be passed to the DeserializeExtraInfo function.\n
* These functions will only be called if node serialization is enabled.\n
*/
public virtual void SerializeExtraInfo (GraphSerializationContext ctx) {
}
/** Deserializes graph type specific node data.
* \see SerializeExtraInfo
*/
public virtual void DeserializeExtraInfo (GraphSerializationContext ctx) {
}
/** Called after all deserialization has been done for all graphs.
* Can be used to set up more graph data which is not serialized
*/
public virtual void PostDeserialization () {
}
/** An old format for serializing settings.
* \deprecated This is deprecated now, but the deserialization code is kept to
* avoid loosing data when upgrading from older versions.
*/
public virtual void DeserializeSettingsCompatibility (GraphSerializationContext ctx) {
guid = new Guid(ctx.reader.ReadBytes(16));
initialPenalty = ctx.reader.ReadUInt32();
open = ctx.reader.ReadBoolean();
name = ctx.reader.ReadString();
drawGizmos = ctx.reader.ReadBoolean();
infoScreenOpen = ctx.reader.ReadBoolean();
for (int i = 0; i < 4; i++) {
Vector4 row = Vector4.zero;
for (int j = 0; j < 4; j++) {
row[j] = ctx.reader.ReadSingle();
}
matrix.SetRow(i, row);
}
}
/** Returns if the node is in the search tree of the path.
* Only guaranteed to be correct if \a path is the latest path calculated.
* Use for gizmo drawing only.
*/
public static bool InSearchTree (GraphNode node, Path path) {
if (path == null || path.pathHandler == null) return true;
PathNode nodeR = path.pathHandler.GetPathNode(node);
return nodeR.pathID == path.pathID;
}
/** Draw gizmos for the graph */
public virtual void OnDrawGizmos (bool drawNodes) {
if (!drawNodes) {
return;
}
// This is the relatively slow default implementation
// subclasses of the base graph class may override
// this method to draw gizmos in a more optimized way
PathHandler data = AstarPath.active.debugPathData;
GraphNode node = null;
// Use this delegate to draw connections
// from the #node variable to #otherNode
GraphNodeDelegate drawConnection = otherNode => Gizmos.DrawLine((Vector3)node.position, (Vector3)otherNode.position);
GetNodes(_node => {
// Set the #node variable so that #drawConnection can use it
node = _node;
Gizmos.color = NodeColor(node, AstarPath.active.debugPathData);
if (AstarPath.active.showSearchTree && !InSearchTree(node, AstarPath.active.debugPath)) return true;
PathNode nodeR = data != null ? data.GetPathNode(node) : null;
if (AstarPath.active.showSearchTree && nodeR != null && nodeR.parent != null) {
Gizmos.DrawLine((Vector3)node.position, (Vector3)nodeR.parent.node.position);
} else {
node.GetConnections(drawConnection);
}
return true;
});
}
/** Called when temporary meshes used in OnDrawGizmos need to be unloaded to prevent memory leaks */
internal virtual void UnloadGizmoMeshes () {
}
}
/** Handles collision checking for graphs.
* Mostly used by grid based graphs */
[System.Serializable]
public class GraphCollision {
/** Collision shape to use.
* Pathfinding.ColliderType */
public ColliderType type = ColliderType.Capsule;
/** Diameter of capsule or sphere when checking for collision.
* 1 equals \link Pathfinding.GridGraph.nodeSize nodeSize \endlink.
* If #type is set to Ray, this does not affect anything */
public float diameter = 1F;
/** Height of capsule or length of ray when checking for collision.
* If #type is set to Sphere, this does not affect anything
*/
public float height = 2F;
public float collisionOffset;
/** Direction of the ray when checking for collision.
* If #type is not Ray, this does not affect anything
* \note This variable is not used currently, it does not affect anything
*/
public RayDirection rayDirection = RayDirection.Both;
/** Layer mask to use for collision check.
* This should only contain layers of objects defined as obstacles */
public LayerMask mask;
/** Layer mask to use for height check. */
public LayerMask heightMask = -1;
/** The height to check from when checking height */
public float fromHeight = 100;
/** Toggles thick raycast */
public bool thickRaycast;
/** Diameter of the thick raycast in nodes.
* 1 equals \link Pathfinding.GridGraph.nodeSize nodeSize \endlink */
public float thickRaycastDiameter = 1;
/** Make nodes unwalkable when no ground was found with the height raycast. If height raycast is turned off, this doesn't affect anything. */
public bool unwalkableWhenNoGround = true;
/** Use Unity 2D Physics API.
* \see http://docs.unity3d.com/ScriptReference/Physics2D.html
*/
public bool use2D;
/** Toggle collision check */
public bool collisionCheck = true;
/** Toggle height check. If false, the grid will be flat */
public bool heightCheck = true;
/** Direction to use as \a UP.
* \see Initialize */
public Vector3 up;
/** #up * #height.
* \see Initialize */
private Vector3 upheight;
/** #diameter * scale * 0.5.
* Where \a scale usually is \link Pathfinding.GridGraph.nodeSize nodeSize \endlink
* \see Initialize */
private float finalRadius;
/** #thickRaycastDiameter * scale * 0.5. Where \a scale usually is \link Pathfinding.GridGraph.nodeSize nodeSize \endlink \see Initialize */
private float finalRaycastRadius;
/** Offset to apply after each raycast to make sure we don't hit the same point again in CheckHeightAll */
public const float RaycastErrorMargin = 0.005F;
/** Sets up several variables using the specified matrix and scale.
* \see GraphCollision.up
* \see GraphCollision.upheight
* \see GraphCollision.finalRadius
* \see GraphCollision.finalRaycastRadius
*/
public void Initialize (Matrix4x4 matrix, float scale) {
up = matrix.MultiplyVector(Vector3.up);
upheight = up*height;
finalRadius = diameter*scale*0.5F;
finalRaycastRadius = thickRaycastDiameter*scale*0.5F;
}
/** Returns if the position is obstructed.
* If #collisionCheck is false, this will always return true.\n
*/
public bool Check (Vector3 position) {
if (!collisionCheck) {
return true;
}
if (use2D) {
switch (type) {
case ColliderType.Capsule:
throw new System.Exception("Capsule mode cannot be used with 2D since capsules don't exist in 2D. Please change the Physics Testing -> Collider Type setting.");
case ColliderType.Sphere:
return Physics2D.OverlapCircle(position, finalRadius, mask) == null;
default:
return Physics2D.OverlapPoint(position, mask) == null;
}
}
position += up*collisionOffset;
switch (type) {
case ColliderType.Capsule:
return !Physics.CheckCapsule(position, position+upheight, finalRadius, mask);
case ColliderType.Sphere:
return !Physics.CheckSphere(position, finalRadius, mask);
default:
switch (rayDirection) {
case RayDirection.Both:
return !Physics.Raycast(position, up, height, mask) && !Physics.Raycast(position+upheight, -up, height, mask);
case RayDirection.Up:
return !Physics.Raycast(position, up, height, mask);
default:
return !Physics.Raycast(position+upheight, -up, height, mask);
}
}
}
/** Returns the position with the correct height. If #heightCheck is false, this will return \a position.\n */
public Vector3 CheckHeight (Vector3 position) {
RaycastHit hit;
bool walkable;
return CheckHeight(position, out hit, out walkable);
}
/** Returns the position with the correct height.
* If #heightCheck is false, this will return \a position.\n
* \a walkable will be set to false if nothing was hit.
* The ray will check a tiny bit further than to the grids base to avoid floating point errors when the ground is exactly at the base of the grid */
public Vector3 CheckHeight (Vector3 position, out RaycastHit hit, out bool walkable) {
walkable = true;
if (!heightCheck || use2D) {
hit = new RaycastHit();
return position;
}
if (thickRaycast) {
var ray = new Ray(position+up*fromHeight, -up);
if (Physics.SphereCast(ray, finalRaycastRadius, out hit, fromHeight+0.005F, heightMask)) {
return VectorMath.ClosestPointOnLine(ray.origin, ray.origin+ray.direction, hit.point);
}
walkable &= !unwalkableWhenNoGround;
} else {
// Cast a ray from above downwards to try to find the ground
if (Physics.Raycast(position+up*fromHeight, -up, out hit, fromHeight+0.005F, heightMask)) {
return hit.point;
}
walkable &= !unwalkableWhenNoGround;
}
return position;
}
/** Same as #CheckHeight, except that the raycast will always start exactly at \a origin.
* \a walkable will be set to false if nothing was hit.
* The ray will check a tiny bit further than to the grids base to avoid floating point errors when the ground is exactly at the base of the grid */
public Vector3 Raycast (Vector3 origin, out RaycastHit hit, out bool walkable) {
walkable = true;
if (!heightCheck || use2D) {
hit = new RaycastHit();
return origin -up*fromHeight;
}
if (thickRaycast) {
var ray = new Ray(origin, -up);
if (Physics.SphereCast(ray, finalRaycastRadius, out hit, fromHeight+0.005F, heightMask)) {
return VectorMath.ClosestPointOnLine(ray.origin, ray.origin+ray.direction, hit.point);
}
walkable &= !unwalkableWhenNoGround;
} else {
if (Physics.Raycast(origin, -up, out hit, fromHeight+0.005F, heightMask)) {
return hit.point;
}
walkable &= !unwalkableWhenNoGround;
}
return origin -up*fromHeight;
}
/** Returns all hits when checking height for \a position.
* \warning Does not work well with thick raycast, will only return an object a single time
*/
public RaycastHit[] CheckHeightAll (Vector3 position) {
if (!heightCheck || use2D) {
var hit = new RaycastHit();
hit.point = position;
hit.distance = 0;
return new [] { hit };
}
if (thickRaycast) {
return new RaycastHit[0];
}
var hits = new List<RaycastHit>();
bool walkable;
Vector3 cpos = position + up*fromHeight;
Vector3 prevHit = Vector3.zero;
int numberSame = 0;
while (true) {
RaycastHit hit;
Raycast(cpos, out hit, out walkable);
if (hit.transform == null) { //Raycast did not hit anything
break;
}
//Make sure we didn't hit the same position
if (hit.point != prevHit || hits.Count == 0) {
cpos = hit.point - up*RaycastErrorMargin;
prevHit = hit.point;
numberSame = 0;
hits.Add(hit);
} else {
cpos -= up*0.001F;
numberSame++;
//Check if we are hitting the same position all the time, even though we are decrementing the cpos variable
if (numberSame > 10) {
Debug.LogError("Infinite Loop when raycasting. Please report this error (arongranberg.com)\n"+cpos+" : "+prevHit);
break;
}
}
}
return hits.ToArray();
}
public void DeserializeSettingsCompatibility (GraphSerializationContext ctx) {
type = (ColliderType)ctx.reader.ReadInt32();
diameter = ctx.reader.ReadSingle();
height = ctx.reader.ReadSingle();
collisionOffset = ctx.reader.ReadSingle();
rayDirection = (RayDirection)ctx.reader.ReadInt32();
mask = (LayerMask)ctx.reader.ReadInt32();
heightMask = (LayerMask)ctx.reader.ReadInt32();
fromHeight = ctx.reader.ReadSingle();
thickRaycast = ctx.reader.ReadBoolean();
thickRaycastDiameter = ctx.reader.ReadSingle();
unwalkableWhenNoGround = ctx.reader.ReadBoolean();
use2D = ctx.reader.ReadBoolean();
collisionCheck = ctx.reader.ReadBoolean();
heightCheck = ctx.reader.ReadBoolean();
}
}
/** Determines collision check shape */
public enum ColliderType {
Sphere, /**< Uses a Sphere, Physics.CheckSphere */
Capsule, /**< Uses a Capsule, Physics.CheckCapsule */
Ray /**< Uses a Ray, Physics.Linecast */
}
/** Determines collision check ray direction */
public enum RayDirection {
Up, /**< Casts the ray from the bottom upwards */
Down, /**< Casts the ray from the top downwards */
Both /**< Casts two rays in both directions */
}
}
| |
/*
* Copyright (c) 2007, Second Life Reverse Engineering Team
* 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.
* - Neither the name of the Second Life Reverse Engineering Team 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;
using System.Net;
using System.Threading;
using libsecondlife.StructuredData;
namespace libsecondlife.Capabilities
{
public class EventQueueClient
{
/// <summary>
///
/// </summary>
public delegate void ConnectedCallback();
/// <summary>
///
/// </summary>
/// <param name="eventName"></param>
/// <param name="body"></param>
public delegate void EventCallback(string eventName, LLSDMap body);
/// <summary></summary>
public ConnectedCallback OnConnected;
/// <summary></summary>
public EventCallback OnEvent;
public IWebProxy Proxy;
public bool Running { get { return _Running && _Client.IsBusy; } }
protected CapsBase _Client;
protected bool _Dead;
protected bool _Running;
public EventQueueClient(Uri eventQueueLocation)
{
_Client = new CapsBase(eventQueueLocation);
_Client.OpenWriteCompleted += new CapsBase.OpenWriteCompletedEventHandler(Client_OpenWriteCompleted);
_Client.UploadDataCompleted += new CapsBase.UploadDataCompletedEventHandler(Client_UploadDataCompleted);
}
public void Start()
{
_Dead = false;
_Client.OpenWriteAsync(_Client.Location);
}
public void Stop(bool immediate)
{
_Dead = true;
if (immediate)
_Running = false;
if (_Client.IsBusy)
{
Logger.DebugLog("Stopping a running event queue");
_Client.CancelAsync();
}
else
{
Logger.DebugLog("Stopping an already dead event queue");
}
}
#region Callback Handlers
private void Client_OpenWriteCompleted(object sender, CapsBase.OpenWriteCompletedEventArgs e)
{
bool raiseEvent = false;
if (!_Dead)
{
if (!_Running) raiseEvent = true;
// We are connected to the event queue
_Running = true;
}
// Create an EventQueueGet request
LLSDMap request = new LLSDMap();
request["ack"] = new LLSD();
request["done"] = LLSD.FromBoolean(false);
byte[] postData = LLSDParser.SerializeXmlBytes(request);
_Client.UploadDataAsync(_Client.Location, postData);
if (raiseEvent)
{
Logger.DebugLog("Capabilities event queue connected");
// The event queue is starting up for the first time
if (OnConnected != null)
{
try { OnConnected(); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
}
private void Client_UploadDataCompleted(object sender, CapsBase.UploadDataCompletedEventArgs e)
{
LLSDArray events = null;
int ack = 0;
if (e.Error != null)
{
// Error occurred
string message = e.Error.Message.ToLower();
// Check what kind of exception happened
if (Helpers.StringContains(message, "404") || Helpers.StringContains(message, "410"))
{
Logger.Log("Closing event queue at " + _Client.Location + " due to missing caps URI",
Helpers.LogLevel.Info);
_Running = false;
_Dead = true;
}
else if (!e.Cancelled)
{
HttpWebResponse errResponse = null;
if (e.Error is WebException)
{
WebException err = (WebException)e.Error;
errResponse = (HttpWebResponse)err.Response;
}
// Figure out what type of error was thrown so we can print a meaningful
// error message
if (errResponse != null)
{
switch (errResponse.StatusCode)
{
case HttpStatusCode.BadGateway:
// This is not good (server) protocol design, but it's normal.
// The EventQueue server is a proxy that connects to a Squid
// cache which will time out periodically. The EventQueue server
// interprets this as a generic error and returns a 502 to us
// that we ignore
break;
default:
Logger.Log(String.Format(
"Unrecognized caps connection problem from {0}: {1} (Server returned: {2})",
_Client.Location, errResponse.StatusCode, errResponse.StatusDescription),
Helpers.LogLevel.Warning);
break;
}
}
else if (e.Error.InnerException != null)
{
Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}",
_Client.Location, e.Error.InnerException.Message), Helpers.LogLevel.Warning);
}
else
{
Logger.Log(String.Format("Unrecognized caps exception from {0}: {1}",
_Client.Location, e.Error.Message), Helpers.LogLevel.Warning);
}
}
}
else if (!e.Cancelled && e.Result != null)
{
// Got a response
LLSD result = LLSDParser.DeserializeXml(e.Result);
if (result != null && result.Type == LLSDType.Map)
{
// Parse any events returned by the event queue
LLSDMap map = (LLSDMap)result;
events = (LLSDArray)map["events"];
ack = map["id"].AsInteger();
}
}
else if (e.Cancelled)
{
// Connection was cancelled
Logger.DebugLog("Cancelled connection to event queue at " + _Client.Location);
}
if (_Running)
{
LLSDMap request = new LLSDMap();
if (ack != 0) request["ack"] = LLSD.FromInteger(ack);
else request["ack"] = new LLSD();
request["done"] = LLSD.FromBoolean(_Dead);
byte[] postData = LLSDParser.SerializeXmlBytes(request);
_Client.UploadDataAsync(_Client.Location, postData);
// If the event queue is dead at this point, turn it off since
// that was the last thing we want to do
if (_Dead)
{
_Running = false;
Logger.DebugLog("Sent event queue shutdown message");
}
}
if (OnEvent != null && events != null && events.Count > 0)
{
// Fire callbacks for each event received
foreach (LLSDMap evt in events)
{
string msg = evt["message"].AsString();
LLSDMap body = (LLSDMap)evt["body"];
try { OnEvent(msg, body); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, ex); }
}
}
}
#endregion Callback Handlers
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;
namespace XenAPI
{
/// <summary>
/// Describes the storage that is available to a PVS site for caching purposes
/// </summary>
public partial class PVS_cache_storage : XenObject<PVS_cache_storage>
{
public PVS_cache_storage()
{
}
public PVS_cache_storage(string uuid,
XenRef<Host> host,
XenRef<SR> SR,
XenRef<PVS_site> site,
long size,
XenRef<VDI> VDI)
{
this.uuid = uuid;
this.host = host;
this.SR = SR;
this.site = site;
this.size = size;
this.VDI = VDI;
}
/// <summary>
/// Creates a new PVS_cache_storage from a Proxy_PVS_cache_storage.
/// </summary>
/// <param name="proxy"></param>
public PVS_cache_storage(Proxy_PVS_cache_storage proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(PVS_cache_storage update)
{
uuid = update.uuid;
host = update.host;
SR = update.SR;
site = update.site;
size = update.size;
VDI = update.VDI;
}
internal void UpdateFromProxy(Proxy_PVS_cache_storage proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
SR = proxy.SR == null ? null : XenRef<SR>.Create(proxy.SR);
site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site);
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI);
}
public Proxy_PVS_cache_storage ToProxy()
{
Proxy_PVS_cache_storage result_ = new Proxy_PVS_cache_storage();
result_.uuid = (uuid != null) ? uuid : "";
result_.host = (host != null) ? host : "";
result_.SR = (SR != null) ? SR : "";
result_.site = (site != null) ? site : "";
result_.size = size.ToString();
result_.VDI = (VDI != null) ? VDI : "";
return result_;
}
/// <summary>
/// Creates a new PVS_cache_storage from a Hashtable.
/// </summary>
/// <param name="table"></param>
public PVS_cache_storage(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
host = Marshalling.ParseRef<Host>(table, "host");
SR = Marshalling.ParseRef<SR>(table, "SR");
site = Marshalling.ParseRef<PVS_site>(table, "site");
size = Marshalling.ParseLong(table, "size");
VDI = Marshalling.ParseRef<VDI>(table, "VDI");
}
public bool DeepEquals(PVS_cache_storage other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._SR, other._SR) &&
Helper.AreEqual2(this._site, other._site) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._VDI, other._VDI);
}
public override string SaveChanges(Session session, string opaqueRef, PVS_cache_storage server)
{
if (opaqueRef == null)
{
Proxy_PVS_cache_storage p = this.ToProxy();
return session.proxy.pvs_cache_storage_create(session.uuid, p).parse();
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given PVS_cache_storage.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static PVS_cache_storage get_record(Session session, string _pvs_cache_storage)
{
return new PVS_cache_storage((Proxy_PVS_cache_storage)session.proxy.pvs_cache_storage_get_record(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse());
}
/// <summary>
/// Get a reference to the PVS_cache_storage instance with the specified UUID.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<PVS_cache_storage> get_by_uuid(Session session, string _uuid)
{
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<PVS_cache_storage> create(Session session, PVS_cache_storage _record)
{
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new PVS_cache_storage instance, and return its handle.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, PVS_cache_storage _record)
{
return XenRef<Task>.Create(session.proxy.async_pvs_cache_storage_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static void destroy(Session session, string _pvs_cache_storage)
{
session.proxy.pvs_cache_storage_destroy(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse();
}
/// <summary>
/// Destroy the specified PVS_cache_storage instance.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Task> async_destroy(Session session, string _pvs_cache_storage)
{
return XenRef<Task>.Create(session.proxy.async_pvs_cache_storage_destroy(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse());
}
/// <summary>
/// Get the uuid field of the given PVS_cache_storage.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static string get_uuid(Session session, string _pvs_cache_storage)
{
return (string)session.proxy.pvs_cache_storage_get_uuid(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse();
}
/// <summary>
/// Get the host field of the given PVS_cache_storage.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<Host> get_host(Session session, string _pvs_cache_storage)
{
return XenRef<Host>.Create(session.proxy.pvs_cache_storage_get_host(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse());
}
/// <summary>
/// Get the SR field of the given PVS_cache_storage.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<SR> get_SR(Session session, string _pvs_cache_storage)
{
return XenRef<SR>.Create(session.proxy.pvs_cache_storage_get_sr(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse());
}
/// <summary>
/// Get the site field of the given PVS_cache_storage.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<PVS_site> get_site(Session session, string _pvs_cache_storage)
{
return XenRef<PVS_site>.Create(session.proxy.pvs_cache_storage_get_site(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse());
}
/// <summary>
/// Get the size field of the given PVS_cache_storage.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static long get_size(Session session, string _pvs_cache_storage)
{
return long.Parse((string)session.proxy.pvs_cache_storage_get_size(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse());
}
/// <summary>
/// Get the VDI field of the given PVS_cache_storage.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pvs_cache_storage">The opaque_ref of the given pvs_cache_storage</param>
public static XenRef<VDI> get_VDI(Session session, string _pvs_cache_storage)
{
return XenRef<VDI>.Create(session.proxy.pvs_cache_storage_get_vdi(session.uuid, (_pvs_cache_storage != null) ? _pvs_cache_storage : "").parse());
}
/// <summary>
/// Return a list of all the PVS_cache_storages known to the system.
/// Experimental. First published in .
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<PVS_cache_storage>> get_all(Session session)
{
return XenRef<PVS_cache_storage>.Create(session.proxy.pvs_cache_storage_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the PVS_cache_storage Records at once, in a single XML RPC call
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<PVS_cache_storage>, PVS_cache_storage> get_all_records(Session session)
{
return XenRef<PVS_cache_storage>.Create<Proxy_PVS_cache_storage>(session.proxy.pvs_cache_storage_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// Experimental. First published in .
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// The host on which this object defines PVS cache storage
/// Experimental. First published in .
/// </summary>
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host;
/// <summary>
/// SR providing storage for the PVS cache
/// Experimental. First published in .
/// </summary>
public virtual XenRef<SR> SR
{
get { return _SR; }
set
{
if (!Helper.AreEqual(value, _SR))
{
_SR = value;
Changed = true;
NotifyPropertyChanged("SR");
}
}
}
private XenRef<SR> _SR;
/// <summary>
/// The PVS_site for which this object defines the storage
/// Experimental. First published in .
/// </summary>
public virtual XenRef<PVS_site> site
{
get { return _site; }
set
{
if (!Helper.AreEqual(value, _site))
{
_site = value;
Changed = true;
NotifyPropertyChanged("site");
}
}
}
private XenRef<PVS_site> _site;
/// <summary>
/// The size of the cache VDI (in bytes)
/// Experimental. First published in .
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// The VDI used for caching
/// Experimental. First published in .
/// </summary>
public virtual XenRef<VDI> VDI
{
get { return _VDI; }
set
{
if (!Helper.AreEqual(value, _VDI))
{
_VDI = value;
Changed = true;
NotifyPropertyChanged("VDI");
}
}
}
private XenRef<VDI> _VDI;
}
}
| |
using System.Collections.Generic;
using System.Collections;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System;
namespace Fabric.Internal.Editor.ThirdParty.xcodeapi.PBX
{
internal class PBXObjectData
{
public string guid;
protected PBXElementDict m_Properties = new PBXElementDict();
internal void SetPropertiesWhenSerializing(PBXElementDict props)
{
m_Properties = props;
}
internal PBXElementDict GetPropertiesWhenSerializing()
{
return m_Properties;
}
// returns null if it does not exist
protected string GetPropertyString(string name)
{
var prop = m_Properties[name];
if (prop == null)
return null;
return prop.AsString();
}
protected void SetPropertyString(string name, string value)
{
if (value == null)
m_Properties.Remove(name);
else
m_Properties.SetString(name, value);
}
protected List<string> GetPropertyList(string name)
{
var prop = m_Properties[name];
if (prop == null)
return null;
var list = new List<string>();
foreach (var el in prop.AsArray().values)
list.Add(el.AsString());
return list;
}
protected void SetPropertyList(string name, List<string> value)
{
if (value == null)
m_Properties.Remove(name);
else
{
var array = m_Properties.CreateArray(name);
foreach (string val in value)
array.AddString(val);
}
}
private static PropertyCommentChecker checkerData = new PropertyCommentChecker();
internal virtual PropertyCommentChecker checker { get { return checkerData; } }
internal virtual bool shouldCompact { get { return false; } }
public virtual void UpdateProps() {} // Updates the props from cached variables
public virtual void UpdateVars() {} // Updates the cached variables from underlying props
}
internal class PBXBuildFileData : PBXObjectData
{
public string fileRef;
public string compileFlags;
public bool weak;
public List<string> assetTags;
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"fileRef/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
internal override bool shouldCompact { get { return true; } }
public static PBXBuildFileData CreateFromFile(string fileRefGUID, bool weak,
string compileFlags)
{
PBXBuildFileData buildFile = new PBXBuildFileData();
buildFile.guid = PBXGUID.Generate();
buildFile.SetPropertyString("isa", "PBXBuildFile");
buildFile.fileRef = fileRefGUID;
buildFile.compileFlags = compileFlags;
buildFile.weak = weak;
buildFile.assetTags = new List<string>();
return buildFile;
}
public override void UpdateProps()
{
SetPropertyString("fileRef", fileRef);
PBXElementDict settings = null;
if (m_Properties.Contains("settings"))
settings = m_Properties["settings"].AsDict();
if (compileFlags != null && compileFlags != "")
{
if (settings == null)
settings = m_Properties.CreateDict("settings");
settings.SetString("COMPILER_FLAGS", compileFlags);
}
else
{
if (settings != null)
settings.Remove("COMPILER_FLAGS");
}
if (weak)
{
if (settings == null)
settings = m_Properties.CreateDict("settings");
PBXElementArray attrs = null;
if (settings.Contains("ATTRIBUTES"))
attrs = settings["ATTRIBUTES"].AsArray();
else
attrs = settings.CreateArray("ATTRIBUTES");
bool exists = false;
foreach (var value in attrs.values)
{
if (value is PBXElementString && value.AsString() == "Weak")
exists = true;
}
if (!exists)
attrs.AddString("Weak");
}
else
{
if (settings != null && settings.Contains("ATTRIBUTES"))
{
var attrs = settings["ATTRIBUTES"].AsArray();
attrs.values.RemoveAll(el => (el is PBXElementString && el.AsString() == "Weak"));
if (attrs.values.Count == 0)
settings.Remove("ATTRIBUTES");
}
}
if (assetTags.Count > 0)
{
if (settings == null)
settings = m_Properties.CreateDict("settings");
var tagsArray = settings.CreateArray("ASSET_TAGS");
foreach (string tag in assetTags)
tagsArray.AddString(tag);
}
else
{
if (settings != null)
settings.Remove("ASSET_TAGS");
}
if (settings != null && settings.values.Count == 0)
m_Properties.Remove("settings");
}
public override void UpdateVars()
{
fileRef = GetPropertyString("fileRef");
compileFlags = null;
weak = false;
assetTags = new List<string>();
if (m_Properties.Contains("settings"))
{
var dict = m_Properties["settings"].AsDict();
if (dict.Contains("COMPILER_FLAGS"))
compileFlags = dict["COMPILER_FLAGS"].AsString();
if (dict.Contains("ATTRIBUTES"))
{
var attrs = dict["ATTRIBUTES"].AsArray();
foreach (var value in attrs.values)
{
if (value is PBXElementString && value.AsString() == "Weak")
weak = true;
}
}
if (dict.Contains("ASSET_TAGS"))
{
var tags = dict["ASSET_TAGS"].AsArray();
foreach (var value in tags.values)
assetTags.Add(value.AsString());
}
}
}
}
internal class PBXFileReferenceData : PBXObjectData
{
string m_Path = null;
string m_ExplicitFileType = null;
string m_LastKnownFileType = null;
public string path
{
get { return m_Path; }
set { m_ExplicitFileType = null; m_LastKnownFileType = null; m_Path = value; }
}
public string name;
public PBXSourceTree tree;
public bool isFolderReference
{
get { return m_LastKnownFileType != null && m_LastKnownFileType == "folder"; }
}
internal override bool shouldCompact { get { return true; } }
public static PBXFileReferenceData CreateFromFile(string path, string projectFileName,
PBXSourceTree tree)
{
string guid = PBXGUID.Generate();
PBXFileReferenceData fileRef = new PBXFileReferenceData();
fileRef.SetPropertyString("isa", "PBXFileReference");
fileRef.guid = guid;
fileRef.path = path;
fileRef.name = projectFileName;
fileRef.tree = tree;
return fileRef;
}
public static PBXFileReferenceData CreateFromFolderReference(string path, string projectFileName,
PBXSourceTree tree)
{
var fileRef = CreateFromFile(path, projectFileName, tree);
fileRef.m_LastKnownFileType = "folder";
return fileRef;
}
public override void UpdateProps()
{
string ext = null;
if (m_ExplicitFileType != null)
SetPropertyString("explicitFileType", m_ExplicitFileType);
else if (m_LastKnownFileType != null)
SetPropertyString("lastKnownFileType", m_LastKnownFileType);
else
{
if (name != null)
ext = Path.GetExtension(name);
else if (m_Path != null)
ext = Path.GetExtension(m_Path);
if (ext != null)
{
if (FileTypeUtils.IsFileTypeExplicit(ext))
SetPropertyString("explicitFileType", FileTypeUtils.GetTypeName(ext));
else
SetPropertyString("lastKnownFileType", FileTypeUtils.GetTypeName(ext));
}
}
if (m_Path == name)
SetPropertyString("name", null);
else
SetPropertyString("name", name);
if (m_Path == null)
SetPropertyString("path", "");
else
SetPropertyString("path", m_Path);
SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree));
}
public override void UpdateVars()
{
name = GetPropertyString("name");
m_Path = GetPropertyString("path");
if (name == null)
name = m_Path;
if (m_Path == null)
m_Path = "";
tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree"));
m_ExplicitFileType = GetPropertyString("explicitFileType");
m_LastKnownFileType = GetPropertyString("lastKnownFileType");
}
}
class GUIDList : IEnumerable<string>
{
private List<string> m_List = new List<string>();
public GUIDList() {}
public GUIDList(List<string> data)
{
m_List = data;
}
public static implicit operator List<string>(GUIDList list) { return list.m_List; }
public static implicit operator GUIDList(List<string> data) { return new GUIDList(data); }
public void AddGUID(string guid) { m_List.Add(guid); }
public void RemoveGUID(string guid) { m_List.RemoveAll(x => x == guid); }
public bool Contains(string guid) { return m_List.Contains(guid); }
public int Count { get { return m_List.Count; } }
public void Clear() { m_List.Clear(); }
IEnumerator<string> IEnumerable<string>.GetEnumerator() { return m_List.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return m_List.GetEnumerator(); }
}
internal class XCConfigurationListData : PBXObjectData
{
public GUIDList buildConfigs;
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"buildConfigurations/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public static XCConfigurationListData Create()
{
var res = new XCConfigurationListData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "XCConfigurationList");
res.buildConfigs = new GUIDList();
res.SetPropertyString("defaultConfigurationIsVisible", "0");
return res;
}
public override void UpdateProps()
{
SetPropertyList("buildConfigurations", buildConfigs);
}
public override void UpdateVars()
{
buildConfigs = GetPropertyList("buildConfigurations");
}
}
internal class PBXGroupData : PBXObjectData
{
public GUIDList children;
public PBXSourceTree tree;
public string name, path;
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"children/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
// name must not contain '/'
public static PBXGroupData Create(string name, string path, PBXSourceTree tree)
{
if (name.Contains("/"))
throw new Exception("Group name must not contain '/'");
PBXGroupData gr = new PBXGroupData();
gr.guid = PBXGUID.Generate();
gr.SetPropertyString("isa", "PBXGroup");
gr.name = name;
gr.path = path;
gr.tree = PBXSourceTree.Group;
gr.children = new GUIDList();
return gr;
}
public static PBXGroupData CreateRelative(string name)
{
return Create(name, name, PBXSourceTree.Group);
}
public override void UpdateProps()
{
// The name property is set only if it is different from the path property
SetPropertyList("children", children);
if (name == path)
SetPropertyString("name", null);
else
SetPropertyString("name", name);
if (path == "")
SetPropertyString("path", null);
else
SetPropertyString("path", path);
SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree));
}
public override void UpdateVars()
{
children = GetPropertyList("children");
path = GetPropertyString("path");
name = GetPropertyString("name");
if (name == null)
name = path;
if (path == null)
path = "";
tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree"));
}
}
internal class PBXVariantGroupData : PBXGroupData
{
}
internal class PBXNativeTargetData : PBXObjectData
{
public GUIDList phases;
public string buildConfigList; // guid
public string name;
public GUIDList dependencies;
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"buildPhases/*",
"buildRules/*",
"dependencies/*",
"productReference/*",
"buildConfigurationList/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public static PBXNativeTargetData Create(string name, string productRef,
string productType, string buildConfigList)
{
var res = new PBXNativeTargetData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXNativeTarget");
res.buildConfigList = buildConfigList;
res.phases = new GUIDList();
res.SetPropertyList("buildRules", new List<string>());
res.dependencies = new GUIDList();
res.name = name;
res.SetPropertyString("productName", name);
res.SetPropertyString("productReference", productRef);
res.SetPropertyString("productType", productType);
return res;
}
public override void UpdateProps()
{
SetPropertyString("buildConfigurationList", buildConfigList);
SetPropertyString("name", name);
SetPropertyList("buildPhases", phases);
SetPropertyList("dependencies", dependencies);
}
public override void UpdateVars()
{
buildConfigList = GetPropertyString("buildConfigurationList");
name = GetPropertyString("name");
phases = GetPropertyList("buildPhases");
dependencies = GetPropertyList("dependencies");
}
}
internal class FileGUIDListBase : PBXObjectData
{
public GUIDList files;
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"files/*",
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public override void UpdateProps()
{
SetPropertyList("files", files);
}
public override void UpdateVars()
{
files = GetPropertyList("files");
}
}
internal class PBXSourcesBuildPhaseData : FileGUIDListBase
{
public static PBXSourcesBuildPhaseData Create()
{
var res = new PBXSourcesBuildPhaseData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXSourcesBuildPhase");
res.SetPropertyString("buildActionMask", "2147483647");
res.files = new List<string>();
res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0");
return res;
}
}
internal class PBXFrameworksBuildPhaseData : FileGUIDListBase
{
public static PBXFrameworksBuildPhaseData Create()
{
var res = new PBXFrameworksBuildPhaseData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXFrameworksBuildPhase");
res.SetPropertyString("buildActionMask", "2147483647");
res.files = new List<string>();
res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0");
return res;
}
}
internal class PBXResourcesBuildPhaseData : FileGUIDListBase
{
public static PBXResourcesBuildPhaseData Create()
{
var res = new PBXResourcesBuildPhaseData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXResourcesBuildPhase");
res.SetPropertyString("buildActionMask", "2147483647");
res.files = new List<string>();
res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0");
return res;
}
}
internal class PBXCopyFilesBuildPhaseData : FileGUIDListBase
{
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"files/*",
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public string name;
// name may be null
public static PBXCopyFilesBuildPhaseData Create(string name, string subfolderSpec)
{
var res = new PBXCopyFilesBuildPhaseData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXCopyFilesBuildPhase");
res.SetPropertyString("buildActionMask", "2147483647");
res.SetPropertyString("dstPath", "");
res.SetPropertyString("dstSubfolderSpec", subfolderSpec);
res.files = new List<string>();
res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0");
res.name = name;
return res;
}
public override void UpdateProps()
{
SetPropertyList("files", files);
SetPropertyString("name", name);
}
public override void UpdateVars()
{
files = GetPropertyList("files");
name = GetPropertyString("name");
}
}
internal class PBXShellScriptBuildPhaseData : PBXObjectData
{
public GUIDList files;
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"files/*",
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public override void UpdateProps()
{
SetPropertyList("files", files);
}
public override void UpdateVars()
{
files = GetPropertyList("files");
}
}
internal class BuildConfigEntryData
{
public string name;
public List<string> val = new List<string>();
public static string ExtractValue(string src)
{
return PBXStream.UnquoteString(src.Trim().TrimEnd(','));
}
public void AddValue(string value)
{
if (!val.Contains(value))
val.Add(value);
}
public void RemoveValue(string value)
{
val.RemoveAll(v => v == value);
}
public static BuildConfigEntryData FromNameValue(string name, string value)
{
BuildConfigEntryData ret = new BuildConfigEntryData();
ret.name = name;
ret.AddValue(value);
return ret;
}
}
internal class XCBuildConfigurationData : PBXObjectData
{
protected SortedDictionary<string, BuildConfigEntryData> entries = new SortedDictionary<string, BuildConfigEntryData>();
public string name { get { return GetPropertyString("name"); } }
// Note that QuoteStringIfNeeded does its own escaping. Double-escaping with quotes is
// required to please Xcode that does not handle paths with spaces if they are not
// enclosed in quotes.
static string EscapeWithQuotesIfNeeded(string name, string value)
{
if (name != "LIBRARY_SEARCH_PATHS")
return value;
if (!value.Contains(" "))
return value;
if (value.First() == '\"' && value.Last() == '\"')
return value;
return "\"" + value + "\"";
}
public void SetProperty(string name, string value)
{
entries[name] = BuildConfigEntryData.FromNameValue(name, EscapeWithQuotesIfNeeded(name, value));
}
public void AddProperty(string name, string value)
{
if (entries.ContainsKey(name))
entries[name].AddValue(EscapeWithQuotesIfNeeded(name, value));
else
SetProperty(name, value);
}
public void RemoveProperty(string name)
{
if (entries.ContainsKey(name))
entries.Remove(name);
}
public void RemovePropertyValue(string name, string value)
{
if (entries.ContainsKey(name))
entries[name].RemoveValue(EscapeWithQuotesIfNeeded(name, value));
}
// name should be either release or debug
public static XCBuildConfigurationData Create(string name)
{
var res = new XCBuildConfigurationData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "XCBuildConfiguration");
res.SetPropertyString("name", name);
return res;
}
public override void UpdateProps()
{
var dict = m_Properties.CreateDict("buildSettings");
foreach (var kv in entries)
{
if (kv.Value.val.Count == 0)
continue;
else if (kv.Value.val.Count == 1)
dict.SetString(kv.Key, kv.Value.val[0]);
else // kv.Value.val.Count > 1
{
var array = dict.CreateArray(kv.Key);
foreach (var value in kv.Value.val)
array.AddString(value);
}
}
}
public override void UpdateVars()
{
entries = new SortedDictionary<string, BuildConfigEntryData>();
if (m_Properties.Contains("buildSettings"))
{
var dict = m_Properties["buildSettings"].AsDict();
foreach (var key in dict.values.Keys)
{
var value = dict[key];
if (value is PBXElementString)
{
if (entries.ContainsKey(key))
entries[key].val.Add(value.AsString());
else
entries.Add(key, BuildConfigEntryData.FromNameValue(key, value.AsString()));
}
else if (value is PBXElementArray)
{
foreach (var pvalue in value.AsArray().values)
{
if (pvalue is PBXElementString)
{
if (entries.ContainsKey(key))
entries[key].val.Add(pvalue.AsString());
else
entries.Add(key, BuildConfigEntryData.FromNameValue(key, pvalue.AsString()));
}
}
}
}
}
}
}
internal class PBXContainerItemProxyData : PBXObjectData
{
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"containerPortal/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public static PBXContainerItemProxyData Create(string containerRef, string proxyType,
string remoteGlobalGUID, string remoteInfo)
{
var res = new PBXContainerItemProxyData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXContainerItemProxy");
res.SetPropertyString("containerPortal", containerRef); // guid
res.SetPropertyString("proxyType", proxyType);
res.SetPropertyString("remoteGlobalIDString", remoteGlobalGUID); // guid
res.SetPropertyString("remoteInfo", remoteInfo);
return res;
}
}
internal class PBXReferenceProxyData : PBXObjectData
{
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"remoteRef/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public string path { get { return GetPropertyString("path"); } }
public static PBXReferenceProxyData Create(string path, string fileType,
string remoteRef, string sourceTree)
{
var res = new PBXReferenceProxyData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXReferenceProxy");
res.SetPropertyString("path", path);
res.SetPropertyString("fileType", fileType);
res.SetPropertyString("remoteRef", remoteRef);
res.SetPropertyString("sourceTree", sourceTree);
return res;
}
}
internal class PBXTargetDependencyData : PBXObjectData
{
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"target/*",
"targetProxy/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public static PBXTargetDependencyData Create(string target, string targetProxy)
{
var res = new PBXTargetDependencyData();
res.guid = PBXGUID.Generate();
res.SetPropertyString("isa", "PBXTargetDependency");
res.SetPropertyString("target", target);
res.SetPropertyString("targetProxy", targetProxy);
return res;
}
}
internal class ProjectReference
{
public string group; // guid
public string projectRef; // guid
public static ProjectReference Create(string group, string projectRef)
{
var res = new ProjectReference();
res.group = group;
res.projectRef = projectRef;
return res;
}
}
internal class PBXProjectObjectData : PBXObjectData
{
private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{
"buildConfigurationList/*",
"mainGroup/*",
"projectReferences/*/ProductGroup/*",
"projectReferences/*/ProjectRef/*",
"targets/*"
});
internal override PropertyCommentChecker checker { get { return checkerData; } }
public List<ProjectReference> projectReferences = new List<ProjectReference>();
public string mainGroup { get { return GetPropertyString("mainGroup"); } }
public List<string> targets = new List<string>();
public List<string> knownAssetTags = new List<string>();
public string buildConfigList;
public void AddReference(string productGroup, string projectRef)
{
projectReferences.Add(ProjectReference.Create(productGroup, projectRef));
}
public override void UpdateProps()
{
m_Properties.values.Remove("projectReferences");
if (projectReferences.Count > 0)
{
var array = m_Properties.CreateArray("projectReferences");
foreach (var value in projectReferences)
{
var dict = array.AddDict();
dict.SetString("ProductGroup", value.group);
dict.SetString("ProjectRef", value.projectRef);
}
};
SetPropertyList("targets", targets);
SetPropertyString("buildConfigurationList", buildConfigList);
if (knownAssetTags.Count > 0)
{
PBXElementDict attrs;
if (m_Properties.Contains("attributes"))
attrs = m_Properties["attributes"].AsDict();
else
attrs = m_Properties.CreateDict("attributes");
var tags = attrs.CreateArray("knownAssetTags");
foreach (var tag in knownAssetTags)
tags.AddString(tag);
}
}
public override void UpdateVars()
{
projectReferences = new List<ProjectReference>();
if (m_Properties.Contains("projectReferences"))
{
var el = m_Properties["projectReferences"].AsArray();
foreach (var value in el.values)
{
PBXElementDict dict = value.AsDict();
if (dict.Contains("ProductGroup") && dict.Contains("ProjectRef"))
{
string group = dict["ProductGroup"].AsString();
string projectRef = dict["ProjectRef"].AsString();
projectReferences.Add(ProjectReference.Create(group, projectRef));
}
}
}
targets = GetPropertyList("targets");
buildConfigList = GetPropertyString("buildConfigurationList");
// update knownAssetTags
knownAssetTags = new List<string>();
if (m_Properties.Contains("attributes"))
{
var el = m_Properties["attributes"].AsDict();
if (el.Contains("knownAssetTags"))
{
var tags = el["knownAssetTags"].AsArray();
foreach (var tag in tags.values)
knownAssetTags.Add(tag.AsString());
}
}
}
}
} // namespace UnityEditor.iOS.Xcode
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareScalarUnorderedNotEqualBoolean()
{
var test = new BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean testClass)
{
var result = Sse.CompareScalarUnorderedNotEqual(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarUnorderedNotEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.CompareScalarUnorderedNotEqual(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.CompareScalarUnorderedNotEqual(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.CompareScalarUnorderedNotEqual(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedNotEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedNotEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedNotEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.CompareScalarUnorderedNotEqual(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.CompareScalarUnorderedNotEqual(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareScalarUnorderedNotEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarUnorderedNotEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarUnorderedNotEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean();
var result = Sse.CompareScalarUnorderedNotEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedNotEqualBoolean();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.CompareScalarUnorderedNotEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.CompareScalarUnorderedNotEqual(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarUnorderedNotEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.CompareScalarUnorderedNotEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse.CompareScalarUnorderedNotEqual(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((left[0] != right[0]) != result)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarUnorderedNotEqual)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if CLUSTERING_DYNAMODB
namespace Orleans.Clustering.DynamoDB
#elif PERSISTENCE_DYNAMODB
namespace Orleans.Persistence.DynamoDB
#elif REMINDERS_DYNAMODB
namespace Orleans.Reminders.DynamoDB
#elif AWSUTILS_TESTS
namespace Orleans.AWSUtils.Tests
#elif TRANSACTIONS_DYNAMODB
namespace Orleans.Transactions.DynamoDB
#else
// No default namespace intentionally to cause compile errors if something is not defined
#endif
{
/// <summary>
/// Wrapper around AWS DynamoDB SDK.
/// </summary>
internal class DynamoDBStorage
{
private string accessKey;
private string token;
/// <summary> Secret key for this dynamoDB table </summary>
protected string secretKey;
private string service;
public const int DefaultReadCapacityUnits = 10;
public const int DefaultWriteCapacityUnits = 5;
private int readCapacityUnits = DefaultReadCapacityUnits;
private int writeCapacityUnits = DefaultWriteCapacityUnits;
private readonly bool useProvisionedThroughput;
private AmazonDynamoDBClient ddbClient;
private ILogger Logger;
/// <summary>
/// Create a DynamoDBStorage instance
/// </summary>
/// <param name="logger"></param>
/// <param name="accessKey"></param>
/// <param name="secretKey"></param>
/// <param name="token"></param>
/// <param name="service"></param>
/// <param name="readCapacityUnits"></param>
/// <param name="writeCapacityUnits"></param>
/// <param name="useProvisionedThroughput"></param>
public DynamoDBStorage(
ILogger logger,
string service,
string accessKey = "",
string secretKey = "",
string token = "",
int readCapacityUnits = DefaultReadCapacityUnits,
int writeCapacityUnits = DefaultWriteCapacityUnits,
bool useProvisionedThroughput = true)
{
if (service == null) throw new ArgumentNullException(nameof(service));
this.accessKey = accessKey;
this.secretKey = secretKey;
this.token = token;
this.service = service;
this.readCapacityUnits = readCapacityUnits;
this.writeCapacityUnits = writeCapacityUnits;
this.useProvisionedThroughput = useProvisionedThroughput;
Logger = logger;
CreateClient();
}
/// <summary>
/// Create a DynamoDB table if it doesn't exist
/// </summary>
/// <param name="tableName">The name of the table</param>
/// <param name="keys">The keys definitions</param>
/// <param name="attributes">The attributes used on the key definition</param>
/// <param name="secondaryIndexes">(optional) The secondary index definitions</param>
/// <param name="ttlAttributeName">(optional) The name of the item attribute that indicates the item TTL (if null, ttl won't be enabled)</param>
/// <returns></returns>
public async Task InitializeTable(string tableName, List<KeySchemaElement> keys, List<AttributeDefinition> attributes, List<GlobalSecondaryIndex> secondaryIndexes = null, string ttlAttributeName = null)
{
try
{
if (await GetTableDescription(tableName) == null)
await CreateTable(tableName, keys, attributes, secondaryIndexes, ttlAttributeName);
}
catch (Exception exc)
{
Logger.Error(ErrorCode.StorageProviderBase, $"Could not initialize connection to storage table {tableName}", exc);
throw;
}
}
private void CreateClient()
{
if (this.service.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
this.service.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
// Local DynamoDB instance (for testing)
var credentials = new BasicAWSCredentials("dummy", "dummyKey");
this.ddbClient = new AmazonDynamoDBClient(credentials, new AmazonDynamoDBConfig { ServiceURL = this.service });
}
else if (!string.IsNullOrEmpty(this.accessKey) && !string.IsNullOrEmpty(this.secretKey) && !string.IsNullOrEmpty(this.token))
{
// AWS DynamoDB instance (auth via explicit credentials and token)
var credentials = new SessionAWSCredentials(this.accessKey, this.secretKey, this.token);
this.ddbClient = new AmazonDynamoDBClient(credentials, new AmazonDynamoDBConfig {RegionEndpoint = AWSUtils.GetRegionEndpoint(this.service)});
}
else if (!string.IsNullOrEmpty(this.accessKey) && !string.IsNullOrEmpty(this.secretKey))
{
// AWS DynamoDB instance (auth via explicit credentials)
var credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
this.ddbClient = new AmazonDynamoDBClient(credentials, new AmazonDynamoDBConfig {RegionEndpoint = AWSUtils.GetRegionEndpoint(this.service)});
}
else
{
// AWS DynamoDB instance (implicit auth - EC2 IAM Roles etc)
this.ddbClient = new AmazonDynamoDBClient(new AmazonDynamoDBConfig {RegionEndpoint = AWSUtils.GetRegionEndpoint(this.service)});
}
}
private async Task<TableDescription> GetTableDescription(string tableName)
{
try
{
var description = await ddbClient.DescribeTableAsync(tableName);
if (description.Table != null)
return description.Table;
}
catch (ResourceNotFoundException)
{
return null;
}
return null;
}
private async Task CreateTable(string tableName, List<KeySchemaElement> keys, List<AttributeDefinition> attributes, List<GlobalSecondaryIndex> secondaryIndexes = null, string ttlAttributeName = null)
{
var request = new CreateTableRequest
{
TableName = tableName,
AttributeDefinitions = attributes,
KeySchema = keys,
BillingMode = this.useProvisionedThroughput ? BillingMode.PROVISIONED : BillingMode.PAY_PER_REQUEST,
ProvisionedThroughput = this.useProvisionedThroughput ? new ProvisionedThroughput
{
ReadCapacityUnits = readCapacityUnits,
WriteCapacityUnits = writeCapacityUnits
} : null
};
if (secondaryIndexes != null && secondaryIndexes.Count > 0)
{
if (this.useProvisionedThroughput)
{
var indexThroughput = new ProvisionedThroughput {ReadCapacityUnits = readCapacityUnits, WriteCapacityUnits = writeCapacityUnits};
secondaryIndexes.ForEach(i =>
{
i.ProvisionedThroughput = indexThroughput;
});
}
request.GlobalSecondaryIndexes = secondaryIndexes;
}
try
{
var response = await ddbClient.CreateTableAsync(request);
TableDescription description = null;
do
{
description = await GetTableDescription(tableName);
await Task.Delay(2000);
} while (description.TableStatus == TableStatus.CREATING);
if (!string.IsNullOrEmpty(ttlAttributeName))
{
await ddbClient.UpdateTimeToLiveAsync(new UpdateTimeToLiveRequest
{
TableName = tableName,
TimeToLiveSpecification = new TimeToLiveSpecification { AttributeName = ttlAttributeName, Enabled = true }
});
}
if (description.TableStatus != TableStatus.ACTIVE)
throw new InvalidOperationException($"Failure creating table {tableName}");
}
catch (Exception exc)
{
Logger.Error(ErrorCode.StorageProviderBase, $"Could not create table {tableName}", exc);
throw;
}
}
/// <summary>
/// Delete a table from DynamoDB
/// </summary>
/// <param name="tableName">The name of the table to delete</param>
/// <returns></returns>
public Task DeleTableAsync(string tableName)
{
try
{
return ddbClient.DeleteTableAsync(new DeleteTableRequest { TableName = tableName });
}
catch (Exception exc)
{
Logger.Error(ErrorCode.StorageProviderBase, $"Could not delete table {tableName}", exc);
throw;
}
}
/// <summary>
/// Create or Replace an entry in a DynamoDB Table
/// </summary>
/// <param name="tableName">The name of the table to put an entry</param>
/// <param name="fields">The fields/attributes to add or replace in the table</param>
/// <param name="conditionExpression">Optional conditional expression</param>
/// <param name="conditionValues">Optional field/attribute values used in the conditional expression</param>
/// <returns></returns>
public Task PutEntryAsync(string tableName, Dictionary<string, AttributeValue> fields, string conditionExpression = "", Dictionary<string, AttributeValue> conditionValues = null)
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Creating {0} table entry: {1}", tableName, Utils.DictionaryToString(fields));
try
{
var request = new PutItemRequest(tableName, fields, ReturnValue.NONE);
if (!string.IsNullOrWhiteSpace(conditionExpression))
request.ConditionExpression = conditionExpression;
if (conditionValues != null && conditionValues.Keys.Count > 0)
request.ExpressionAttributeValues = conditionValues;
return ddbClient.PutItemAsync(request);
}
catch (Exception exc)
{
Logger.Error(ErrorCode.StorageProviderBase, $"Unable to create item to table '{tableName}'", exc);
throw;
}
}
/// <summary>
/// Create or update an entry in a DynamoDB Table
/// </summary>
/// <param name="tableName">The name of the table to upsert an entry</param>
/// <param name="keys">The table entry keys for the entry</param>
/// <param name="fields">The fields/attributes to add or updated in the table</param>
/// <param name="conditionExpression">Optional conditional expression</param>
/// <param name="conditionValues">Optional field/attribute values used in the conditional expression</param>
/// <param name="extraExpression">Additional expression that will be added in the end of the upsert expression</param>
/// <param name="extraExpressionValues">Additional field/attribute that will be used in the extraExpression</param>
/// <remarks>The fields dictionary item values will be updated with the values returned from DynamoDB</remarks>
/// <returns></returns>
public async Task UpsertEntryAsync(string tableName, Dictionary<string, AttributeValue> keys, Dictionary<string, AttributeValue> fields,
string conditionExpression = "", Dictionary<string, AttributeValue> conditionValues = null, string extraExpression = "",
Dictionary<string, AttributeValue> extraExpressionValues = null)
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Upserting entry {0} with key(s) {1} into table {2}", Utils.DictionaryToString(fields), Utils.DictionaryToString(keys), tableName);
try
{
var request = new UpdateItemRequest
{
TableName = tableName,
Key = keys,
ReturnValues = ReturnValue.UPDATED_NEW
};
(request.UpdateExpression, request.ExpressionAttributeValues) = ConvertUpdate(fields, conditionValues,
extraExpression, extraExpressionValues);
if (!string.IsNullOrWhiteSpace(conditionExpression))
request.ConditionExpression = conditionExpression;
var result = await ddbClient.UpdateItemAsync(request);
foreach (var key in result.Attributes.Keys)
{
if (fields.ContainsKey(key))
{
fields[key] = result.Attributes[key];
}
else
{
fields.Add(key, result.Attributes[key]);
}
}
}
catch (Exception exc)
{
Logger.Warn(ErrorCode.StorageProviderBase,
$"Intermediate error upserting to the table {tableName}", exc);
throw;
}
}
public (string updateExpression, Dictionary<string, AttributeValue> expressionAttributeValues)
ConvertUpdate(Dictionary<string, AttributeValue> fields,
Dictionary<string, AttributeValue> conditionValues = null,
string extraExpression = "", Dictionary<string, AttributeValue> extraExpressionValues = null)
{
var expressionAttributeValues = new Dictionary<string, AttributeValue>();
var updateExpression = new StringBuilder();
foreach (var field in fields.Keys)
{
var valueKey = ":" + field;
expressionAttributeValues.Add(valueKey, fields[field]);
updateExpression.Append($" {field} = {valueKey},");
}
updateExpression.Insert(0, "SET");
if (string.IsNullOrWhiteSpace(extraExpression))
{
updateExpression.Remove(updateExpression.Length - 1, 1);
}
else
{
updateExpression.Append($" {extraExpression}");
if (extraExpressionValues != null && extraExpressionValues.Count > 0)
{
foreach (var key in extraExpressionValues.Keys)
{
expressionAttributeValues.Add(key, extraExpressionValues[key]);
}
}
}
if (conditionValues != null && conditionValues.Keys.Count > 0)
{
foreach (var item in conditionValues)
{
expressionAttributeValues.Add(item.Key, item.Value);
}
}
return (updateExpression.ToString(), expressionAttributeValues);
}
/// <summary>
/// Delete an entry from a DynamoDB table
/// </summary>
/// <param name="tableName">The name of the table to delete an entry</param>
/// <param name="keys">The table entry keys for the entry to be deleted</param>
/// <param name="conditionExpression">Optional conditional expression</param>
/// <param name="conditionValues">Optional field/attribute values used in the conditional expression</param>
/// <returns></returns>
public Task DeleteEntryAsync(string tableName, Dictionary<string, AttributeValue> keys, string conditionExpression = "", Dictionary<string, AttributeValue> conditionValues = null)
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Deleting table {0} entry with key(s) {1}", tableName, Utils.DictionaryToString(keys));
try
{
var request = new DeleteItemRequest
{
TableName = tableName,
Key = keys
};
if (!string.IsNullOrWhiteSpace(conditionExpression))
request.ConditionExpression = conditionExpression;
if (conditionValues != null && conditionValues.Keys.Count > 0)
request.ExpressionAttributeValues = conditionValues;
return ddbClient.DeleteItemAsync(request);
}
catch (Exception exc)
{
Logger.Warn(ErrorCode.StorageProviderBase,
$"Intermediate error deleting entry from the table {tableName}.", exc);
throw;
}
}
/// <summary>
/// Delete multiple entries from a DynamoDB table (Batch delete)
/// </summary>
/// <param name="tableName">The name of the table to delete entries</param>
/// <param name="toDelete">List of key values for each entry that must be deleted in the batch</param>
/// <returns></returns>
public Task DeleteEntriesAsync(string tableName, IReadOnlyCollection<Dictionary<string, AttributeValue>> toDelete)
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Deleting {0} table entries", tableName);
if (toDelete == null) throw new ArgumentNullException("collection");
if (toDelete.Count == 0)
return Task.CompletedTask;
try
{
var request = new BatchWriteItemRequest();
request.RequestItems = new Dictionary<string, List<WriteRequest>>();
var batch = new List<WriteRequest>();
foreach (var keys in toDelete)
{
var writeRequest = new WriteRequest();
writeRequest.DeleteRequest = new DeleteRequest();
writeRequest.DeleteRequest.Key = keys;
batch.Add(writeRequest);
}
request.RequestItems.Add(tableName, batch);
return ddbClient.BatchWriteItemAsync(request);
}
catch (Exception exc)
{
Logger.Warn(ErrorCode.StorageProviderBase,
$"Intermediate error deleting entries from the table {tableName}.", exc);
throw;
}
}
/// <summary>
/// Read an entry from a DynamoDB table
/// </summary>
/// <typeparam name="TResult">The result type</typeparam>
/// <param name="tableName">The name of the table to search for the entry</param>
/// <param name="keys">The table entry keys to search for</param>
/// <param name="resolver">Function that will be called to translate the returned fields into a concrete type. This Function is only called if the result is != null</param>
/// <returns>The object translated by the resolver function</returns>
public async Task<TResult> ReadSingleEntryAsync<TResult>(string tableName, Dictionary<string, AttributeValue> keys, Func<Dictionary<string, AttributeValue>, TResult> resolver) where TResult : class
{
try
{
var request = new GetItemRequest
{
TableName = tableName,
Key = keys,
ConsistentRead = true
};
var response = await ddbClient.GetItemAsync(request);
if (response.IsItemSet)
{
return resolver(response.Item);
}
else
{
return null;
}
}
catch (Exception)
{
if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Unable to find table entry for Keys = {0}", Utils.DictionaryToString(keys));
throw;
}
}
/// <summary>
/// Query for multiple entries in a DynamoDB table by filtering its keys
/// </summary>
/// <typeparam name="TResult">The result type</typeparam>
/// <param name="tableName">The name of the table to search for the entries</param>
/// <param name="keys">The table entry keys to search for</param>
/// <param name="keyConditionExpression">the expression that will filter the keys</param>
/// <param name="resolver">Function that will be called to translate the returned fields into a concrete type. This Function is only called if the result is != null and will be called for each entry that match the query and added to the results list</param>
/// <param name="indexName">In case a secondary index is used in the keyConditionExpression</param>
/// <param name="scanIndexForward">In case an index is used, show if the seek order is ascending (true) or descending (false)</param>
/// <param name="lastEvaluatedKey">The primary key of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedKey in the previous operation</param>
/// <returns>The collection containing a list of objects translated by the resolver function and the LastEvaluatedKey for paged results</returns>
public async Task<(List<TResult> results, Dictionary<string, AttributeValue> lastEvaluatedKey)> QueryAsync<TResult>(string tableName, Dictionary<string, AttributeValue> keys, string keyConditionExpression, Func<Dictionary<string, AttributeValue>, TResult> resolver, string indexName = "", bool scanIndexForward = true, Dictionary<string, AttributeValue> lastEvaluatedKey = null) where TResult : class
{
try
{
var request = new QueryRequest
{
TableName = tableName,
ExpressionAttributeValues = keys,
ConsistentRead = true,
KeyConditionExpression = keyConditionExpression,
Select = Select.ALL_ATTRIBUTES,
ExclusiveStartKey = lastEvaluatedKey
};
if (!string.IsNullOrWhiteSpace(indexName))
{
request.ScanIndexForward = scanIndexForward;
request.IndexName = indexName;
}
var response = await ddbClient.QueryAsync(request);
var resultList = new List<TResult>();
foreach (var item in response.Items)
{
resultList.Add(resolver(item));
}
return (resultList, response.LastEvaluatedKey);
}
catch (Exception)
{
if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Unable to find table entry for Keys = {0}", Utils.DictionaryToString(keys));
throw;
}
}
/// <summary>
/// Query for multiple entries in a DynamoDB table by filtering its keys
/// </summary>
/// <typeparam name="TResult">The result type</typeparam>
/// <param name="tableName">The name of the table to search for the entries</param>
/// <param name="keys">The table entry keys to search for</param>
/// <param name="keyConditionExpression">the expression that will filter the keys</param>
/// <param name="resolver">Function that will be called to translate the returned fields into a concrete type. This Function is only called if the result is != null and will be called for each entry that match the query and added to the results list</param>
/// <param name="indexName">In case a secondary index is used in the keyConditionExpression</param>
/// <param name="scanIndexForward">In case an index is used, show if the seek order is ascending (true) or descending (false)</param>
/// <returns>The collection containing a list of objects translated by the resolver function</returns>
public async Task<List<TResult>> QueryAllAsync<TResult>(string tableName, Dictionary<string, AttributeValue> keys,
string keyConditionExpression, Func<Dictionary<string, AttributeValue>, TResult> resolver,
string indexName = "", bool scanIndexForward = true) where TResult : class
{
List<TResult> resultList = null;
Dictionary<string, AttributeValue> lastEvaluatedKey = null;
do
{
List<TResult> results;
(results, lastEvaluatedKey) = await QueryAsync(tableName, keys, keyConditionExpression, resolver,
indexName, scanIndexForward, lastEvaluatedKey);
if (resultList == null)
{
resultList = results;
}
else
{
resultList.AddRange(results);
}
} while (lastEvaluatedKey.Count != 0);
return resultList;
}
/// <summary>
/// Scan a DynamoDB table by querying the entry fields.
/// </summary>
/// <typeparam name="TResult">The result type</typeparam>
/// <param name="tableName">The name of the table to search for the entries</param>
/// <param name="attributes">The attributes used on the expression</param>
/// <param name="expression">The filter expression</param>
/// <param name="resolver">Function that will be called to translate the returned fields into a concrete type. This Function is only called if the result is != null and will be called for each entry that match the query and added to the results list</param>
/// <returns>The collection containing a list of objects translated by the resolver function</returns>
public async Task<List<TResult>> ScanAsync<TResult>(string tableName, Dictionary<string, AttributeValue> attributes, string expression, Func<Dictionary<string, AttributeValue>, TResult> resolver) where TResult : class
{
// From the Amazon documentation:
// "A single Scan operation will read up to the maximum number of items set
// (if using the Limit parameter) or a maximum of 1 MB of data and then apply
// any filtering to the results using FilterExpression."
// https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/DynamoDBv2/MDynamoDBScanAsyncStringDictionary!String,%20Condition!CancellationToken.html
try
{
var resultList = new List<TResult>();
var exclusiveStartKey = new Dictionary<string, AttributeValue>();
while (true)
{
var request = new ScanRequest
{
TableName = tableName,
ConsistentRead = true,
FilterExpression = expression,
ExpressionAttributeValues = attributes,
Select = Select.ALL_ATTRIBUTES,
ExclusiveStartKey = exclusiveStartKey
};
var response = await ddbClient.ScanAsync(request);
foreach (var item in response.Items)
{
resultList.Add(resolver(item));
}
if (response.LastEvaluatedKey.Count == 0)
{
break;
}
else
{
exclusiveStartKey = response.LastEvaluatedKey;
}
}
return resultList;
}
catch (Exception exc)
{
var errorMsg = $"Failed to read table {tableName}: {exc.Message}";
Logger.Warn(ErrorCode.StorageProviderBase, errorMsg, exc);
throw new OrleansException(errorMsg, exc);
}
}
/// <summary>
/// Crete or replace multiple entries in a DynamoDB table (Batch put)
/// </summary>
/// <param name="tableName">The name of the table to search for the entry</param>
/// <param name="toCreate">List of key values for each entry that must be created or replaced in the batch</param>
/// <returns></returns>
public Task PutEntriesAsync(string tableName, IReadOnlyCollection<Dictionary<string, AttributeValue>> toCreate)
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Put entries {0} table", tableName);
if (toCreate == null) throw new ArgumentNullException("collection");
if (toCreate.Count == 0)
return Task.CompletedTask;
try
{
var request = new BatchWriteItemRequest();
request.RequestItems = new Dictionary<string, List<WriteRequest>>();
var batch = new List<WriteRequest>();
foreach (var item in toCreate)
{
var writeRequest = new WriteRequest();
writeRequest.PutRequest = new PutRequest();
writeRequest.PutRequest.Item = item;
batch.Add(writeRequest);
}
request.RequestItems.Add(tableName, batch);
return ddbClient.BatchWriteItemAsync(request);
}
catch (Exception exc)
{
Logger.Warn(ErrorCode.StorageProviderBase,
$"Intermediate error bulk inserting entries to table {tableName}.", exc);
throw;
}
}
/// <summary>
/// Transactionally reads entries from a DynamoDB table
/// </summary>
/// <typeparam name="TResult">The result type</typeparam>
/// <param name="tableName">The name of the table to search for the entry</param>
/// <param name="keys">The table entry keys to search for</param>
/// <param name="resolver">Function that will be called to translate the returned fields into a concrete type. This Function is only called if the result is != null</param>
/// <returns>The object translated by the resolver function</returns>
public async Task<IEnumerable<TResult>> GetEntriesTxAsync<TResult>(string tableName, IEnumerable<Dictionary<string, AttributeValue>> keys, Func<Dictionary<string, AttributeValue>, TResult> resolver) where TResult : class
{
try
{
var request = new TransactGetItemsRequest
{
TransactItems = keys.Select(key => new TransactGetItem
{
Get = new Get
{
TableName = tableName,
Key = key
}
}).ToList()
};
var response = await ddbClient.TransactGetItemsAsync(request);
return response.Responses.Where(r => r?.Item?.Count > 0).Select(r => resolver(r.Item));
}
catch (Exception)
{
if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Unable to find table entry for Keys = {0}", Utils.EnumerableToString(keys, d => Utils.DictionaryToString(d)));
throw;
}
}
/// <summary>
/// Transactionally performs write requests
/// </summary>
/// <param name="puts">Any puts to be performed</param>
/// <param name="updates">Any updated to be performed</param>
/// <param name="deletes">Any deletes to be performed</param>
/// <param name="conditionChecks">Any condition checks to be performed</param>
/// <returns></returns>
public Task WriteTxAsync(IEnumerable<Put> puts = null, IEnumerable<Update> updates = null, IEnumerable<Delete> deletes = null, IEnumerable<ConditionCheck> conditionChecks = null)
{
try
{
var transactItems = new List<TransactWriteItem>();
if (puts != null)
{
transactItems.AddRange(puts.Select(p => new TransactWriteItem{Put = p}));
}
if (updates != null)
{
transactItems.AddRange(updates.Select(u => new TransactWriteItem{Update = u}));
}
if (deletes != null)
{
transactItems.AddRange(deletes.Select(d => new TransactWriteItem{Delete = d}));
}
if (conditionChecks != null)
{
transactItems.AddRange(conditionChecks.Select(c => new TransactWriteItem{ConditionCheck = c}));
}
var request = new TransactWriteItemsRequest
{
TransactItems = transactItems
};
return ddbClient.TransactWriteItemsAsync(request);
}
catch (Exception)
{
if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Unable to write tx");
throw;
}
}
}
}
| |
/*
* ButtonBase.cs - Implementation of the
* "System.Windows.Forms.ButtonBase" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms.Themes;
public abstract class ButtonBase : Control
{
// Internal state.
private FlatStyle flatStyle;
private Image image;
private ContentAlignment imageAlign;
private int imageIndex;
private ImageList imageList;
private ContentAlignment textAlign;
private bool isDefault;
internal bool entered;
internal bool pressed;
internal bool hasFocus;
internal MouseButtons button;
private StringFormat format;
private ButtonState prevState;
// Contructor.
protected ButtonBase()
{
flatStyle = FlatStyle.Standard;
imageAlign = ContentAlignment.MiddleCenter;
imageIndex = -1;
textAlign = ContentAlignment.MiddleCenter;
prevState = (ButtonState)(-1);
format = new StringFormat();
format.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.Show;
SetStringFormat();
SetStyle(ControlStyles.ResizeRedraw, true);
}
// Get or set this control's properties.
#if CONFIG_COMPONENT_MODEL
[Localizable(true)]
#endif
#if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS
[DefaultValue(FlatStyle.Standard)]
#endif
public FlatStyle FlatStyle
{
get
{
return flatStyle;
}
set
{
if(flatStyle != value)
{
flatStyle = value;
Redraw();
}
}
}
#if CONFIG_COMPONENT_MODEL
[Localizable(true)]
#endif
public Image Image
{
get
{
return image;
}
set
{
if(image != value)
{
image = value;
Redraw();
}
}
}
#if CONFIG_COMPONENT_MODEL
[Localizable(true)]
#endif
#if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS
[DefaultValue(ContentAlignment.MiddleCenter)]
#endif
public ContentAlignment ImageAlign
{
get
{
return imageAlign;
}
set
{
if(imageAlign != value)
{
imageAlign = value;
Redraw();
}
}
}
#if CONFIG_COMPONENT_MODEL
[Localizable(true)]
#endif
#if (CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS) && CONFIG_COMPONENT_MODEL_DESIGN
[DefaultValue(-1)]
[Editor("System.Windows.Forms.Design.ImageIndexEditor, System.Design", typeof(UITypeEditor))]
#endif
#if !CONFIG_COMPACT_FORMS || CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS
[TypeConverter(typeof(ImageIndexConverter))]
#endif
public int ImageIndex
{
get
{
return imageIndex;
}
set
{
if(imageIndex != value)
{
imageIndex = value;
Redraw();
}
}
}
public ImageList ImageList
{
get
{
return imageList;
}
set
{
if(imageList != value)
{
imageList = value;
Redraw();
}
}
}
#if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS
[Browsable(false)]
#endif
public new ImeMode ImeMode
{
get
{
return base.ImeMode;
}
set
{
base.ImeMode = value;
}
}
#if CONFIG_COMPONENT_MODEL
[Localizable(true)]
#endif
#if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS
[DefaultValue(ContentAlignment.MiddleCenter)]
#endif
#if !CONFIG_COMPACT_FORMS
public
#else
internal
#endif
virtual ContentAlignment TextAlign
{
get
{
return textAlign;
}
set
{
if(textAlign != value)
{
textAlign = value;
SetStringFormat();
Redraw();
}
}
}
protected override CreateParams CreateParams
{
get
{
return base.CreateParams;
}
}
protected override ImeMode DefaultImeMode
{
get
{
return ImeMode.Disable;
}
}
protected override Size DefaultSize
{
get
{
return new Size(75, 23);
}
}
protected bool IsDefault
{
get
{
return isDefault;
}
set
{
if(isDefault != value)
{
isDefault = value;
Redraw();
}
}
}
#if !CONFIG_COMPACT_FORMS
// Create the accessibility object for this control.
protected override AccessibleObject CreateAccessibilityInstance()
{
return base.CreateAccessibilityInstance();
}
#endif
// Dispose of this instance.
protected override void Dispose(bool disposing)
{
// Nothing to do in this implementation.
base.Dispose(disposing);
}
// Get the correct string format, based on text alignment and RTL info.
internal StringFormat GetStringFormat()
{
return format;
}
// Set the correct string format, based on text alignment and RTL info.
private void SetStringFormat()
{
format.FormatFlags |= StringFormatFlags.NoClip | StringFormatFlags.NoWrap;
switch(RtlTranslateAlignment(TextAlign))
{
case ContentAlignment.TopLeft:
{
format.Alignment = StringAlignment.Near;
format.LineAlignment = StringAlignment.Near;
}
break;
case ContentAlignment.TopCenter:
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Near;
}
break;
case ContentAlignment.TopRight:
{
format.Alignment = StringAlignment.Far;
format.LineAlignment = StringAlignment.Near;
}
break;
case ContentAlignment.MiddleLeft:
{
format.Alignment = StringAlignment.Near;
format.LineAlignment = StringAlignment.Center;
}
break;
case ContentAlignment.MiddleCenter:
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
}
break;
case ContentAlignment.MiddleRight:
{
format.Alignment = StringAlignment.Far;
format.LineAlignment = StringAlignment.Center;
}
break;
case ContentAlignment.BottomLeft:
{
format.Alignment = StringAlignment.Near;
format.LineAlignment = StringAlignment.Far;
}
break;
case ContentAlignment.BottomCenter:
{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Far;
}
break;
case ContentAlignment.BottomRight:
{
format.Alignment = StringAlignment.Far;
format.LineAlignment = StringAlignment.Far;
}
break;
}
}
// Calculate the current state of the button for its visual appearance.
internal virtual ButtonState CalculateState()
{
ButtonState state = ButtonState.Normal;
if(Enabled)
{
if(entered && pressed)
{
state |= ButtonState.Pushed;
if(flatStyle == FlatStyle.Flat)
{
state |= ButtonState.Flat;
}
}
else if(entered)
{
if(flatStyle == FlatStyle.Flat)
{
state |= ButtonState.Flat;
}
}
else
{
if(flatStyle == FlatStyle.Flat ||
flatStyle == FlatStyle.Popup)
{
state |= ButtonState.Flat;
}
}
if(hasFocus)
{
// Special flag that indicates a focus rectangle.
state |= (ButtonState)0x20000;
}
}
else
{
state |= ButtonState.Inactive;
if(flatStyle == FlatStyle.Flat ||
flatStyle == FlatStyle.Popup)
{
state |= ButtonState.Flat;
}
}
return state;
}
// Get the descent in pixels for a font.
internal static float GetDescent(Graphics graphics, Font font)
{
FontFamily family = font.FontFamily;
int ascent = family.GetCellAscent(font.Style);
int descent = family.GetCellDescent(font.Style);
return font.GetHeight(graphics) * descent / (ascent + descent);
}
// Draw the button in its current state on a Graphics surface.
internal virtual void Draw(Graphics graphics)
{
ButtonState state = CalculateState();
Size clientSize = ClientSize;
int x = 0;
int y = 0;
int width = clientSize.Width;
int height = clientSize.Height;
// Draw the border and background.
ThemeManager.MainPainter.DrawButton
(graphics, x, y, width, height, state,
ForeColor, BackColor, isDefault);
// Draw the focus rectangle.
if(hasFocus)
{
ControlPaint.DrawFocusRectangle
(graphics, new Rectangle(x + 4, y + 4,
width - 8, height - 8),
ForeColor, BackColor);
}
// Draw the button image.
Image image = this.image;
if(image == null && imageList != null && imageIndex != -1)
{
image = imageList.Images[imageIndex];
}
if(image != null)
{
int imageX = x;
int imageY = y;
int imageWidth = image.Width;
int imageHeight = image.Height;
switch(imageAlign)
{
case ContentAlignment.TopLeft: break;
case ContentAlignment.TopCenter:
{
imageX += (width - imageWidth) / 2;
}
break;
case ContentAlignment.TopRight:
{
imageX += width - imageWidth;
}
break;
case ContentAlignment.MiddleLeft:
{
imageY += (height - imageHeight) / 2;
}
break;
case ContentAlignment.MiddleCenter:
{
imageX += (width - imageWidth) / 2;
imageY += (height - imageHeight) / 2;
}
break;
case ContentAlignment.MiddleRight:
{
imageX += width - imageWidth;
imageY += (height - imageHeight) / 2;
}
break;
case ContentAlignment.BottomLeft:
{
imageY += height - imageHeight;
}
break;
case ContentAlignment.BottomCenter:
{
imageX += (width - imageWidth) / 2;
imageY += height - imageHeight;
}
break;
case ContentAlignment.BottomRight:
{
imageX += width - imageWidth;
imageY += height - imageHeight;
}
break;
}
if(pressed)
{
++imageX;
++imageY;
}
if(Enabled)
{
graphics.DrawImage(image, imageX, imageY);
}
else
{
ControlPaint.DrawImageDisabled
(graphics, image, imageX, imageY, BackColor);
}
}
// Get the text layout rectangle.
RectangleF layout = new RectangleF
(x + 2, y + 2, width - 4, height - 4);
if(entered && pressed)
{
layout.Offset(1.0f, 1.0f);
}
// If we are using "middle" alignment, then shift the
// text down to account for the descent. This makes
// the button "look better".
Font font = Font;
if((TextAlign & (ContentAlignment.MiddleLeft |
ContentAlignment.MiddleCenter |
ContentAlignment.MiddleRight)) != 0)
{
layout.Offset(0.0f, GetDescent(graphics, font) / 2.0f);
}
// Draw the text on the button.
String text = Text;
if(text != null && text != String.Empty)
{
if(Enabled)
{
Brush brush = new SolidBrush(ForeColor);
graphics.DrawString(text, font, brush, layout, format);
brush.Dispose();
}
else
{
ControlPaint.DrawStringDisabled
(graphics, text, font, BackColor, layout, format);
}
}
}
// Redraw the button after a state change.
internal void Redraw()
{
// Clear the previous state, for non-trivial draw detection.
prevState = (ButtonState)(-1);
// Redraw the button.
Invalidate();
}
// Redraw if a non-trivial state change has occurred.
internal void RedrawIfChanged()
{
ButtonState state = CalculateState();
if(state != prevState)
{
Redraw();
prevState = state;
}
}
// Override events from the "Control" class.
protected override void OnEnabledChanged(EventArgs e)
{
RedrawIfChanged();
base.OnEnabledChanged(e);
}
protected override void OnEnter(EventArgs e)
{
hasFocus = true;
RedrawIfChanged();
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
hasFocus = false;
RedrawIfChanged();
base.OnLeave (e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if(e.KeyData == Keys.Enter || e.KeyData == Keys.Space)
{
if(Enabled)
{
OnClick(EventArgs.Empty);
e.Handled = true;
}
}
base.OnKeyDown(e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if(button == MouseButtons.None && e.Button == MouseButtons.Left)
{
button = e.Button;
pressed = true;
RedrawIfChanged();
}
base.OnMouseDown(e);
}
protected override void OnMouseEnter(EventArgs e)
{
entered = true;
RedrawIfChanged();
base.OnMouseEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
entered = false;
RedrawIfChanged();
base.OnMouseLeave(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if(button == e.Button)
{
button = MouseButtons.None;
pressed = false;
RedrawIfChanged();
}
base.OnMouseUp(e);
}
protected override void OnPaint(PaintEventArgs e)
{
prevState = CalculateState();
Draw(e.Graphics);
base.OnPaint(e);
}
protected override void OnParentChanged(EventArgs e)
{
Redraw();
base.OnParentChanged(e);
}
protected override void OnTextChanged(EventArgs e)
{
Redraw();
base.OnTextChanged(e);
}
protected override void OnRightToLeftChanged(EventArgs e)
{
SetStringFormat();
Redraw();
base.OnRightToLeftChanged(e);
}
protected override void OnVisibleChanged(EventArgs e)
{
if(!Visible)
{
entered = false;
pressed = false;
hasFocus = false;
button = MouseButtons.None;
}
base.OnVisibleChanged(e);
}
#if !CONFIG_COMPACT_FORMS
// Process a message.
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
}
#endif // !CONFIG_COMPACT_FORMS
}; // class ButtonBase
}; // namespace System.Windows.Forms
| |
using System;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime.GrainDirectory;
namespace Orleans.Runtime.Messaging
{
internal class MessageCenter : IMessageCenter, IDisposable
{
public Gateway Gateway { get; set; }
private readonly ILogger log;
private Action<Message> rerouteHandler;
internal Func<Message, bool> ShouldDrop;
private HostedClient hostedClient;
private Action<Message> sniffIncomingMessageHandler;
internal OutboundMessageQueue OutboundQueue { get; set; }
private readonly MessageFactory messageFactory;
private readonly ILoggerFactory loggerFactory;
private readonly ConnectionManager senderManager;
private readonly MessagingTrace messagingTrace;
private SiloMessagingOptions messagingOptions;
private Dispatcher dispatcher;
internal bool IsBlockingApplicationMessages { get; private set; }
public void SetHostedClient(HostedClient client) => this.hostedClient = client;
public bool TryDeliverToProxy(Message msg)
{
if (!msg.TargetGrain.IsClient()) return false;
if (this.Gateway is Gateway gateway && gateway.TryDeliverToProxy(msg)) return true;
return this.hostedClient is HostedClient client && client.TryDispatchToClient(msg);
}
// This is determined by the IMA but needed by the OMS, and so is kept here in the message center itself.
public SiloAddress MyAddress { get; private set; }
public MessageCenter(
ILocalSiloDetails siloDetails,
IOptions<SiloMessagingOptions> messagingOptions,
MessageFactory messageFactory,
Factory<MessageCenter, Gateway> gatewayFactory,
ILoggerFactory loggerFactory,
ISiloStatusOracle siloStatusOracle,
ConnectionManager senderManager,
MessagingTrace messagingTrace)
{
this.messagingOptions = messagingOptions.Value;
this.loggerFactory = loggerFactory;
this.senderManager = senderManager;
this.messagingTrace = messagingTrace;
this.log = loggerFactory.CreateLogger<MessageCenter>();
this.messageFactory = messageFactory;
this.MyAddress = siloDetails.SiloAddress;
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Starting initialization.");
OutboundQueue = new OutboundMessageQueue(this, this.loggerFactory.CreateLogger<OutboundMessageQueue>(), this.senderManager, siloStatusOracle, this.messagingTrace);
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Completed initialization.");
if (siloDetails.GatewayAddress != null)
{
Gateway = gatewayFactory(this);
}
}
public void Start()
{
IsBlockingApplicationMessages = false;
OutboundQueue.Start();
}
public void StartGateway()
{
if (Gateway != null)
Gateway.Start();
}
private void WaitToRerouteAllQueuedMessages()
{
DateTime maxWaitTime = DateTime.UtcNow + this.messagingOptions.ShutdownRerouteTimeout;
while (DateTime.UtcNow < maxWaitTime)
{
var applicationMessageQueueLength = this.OutboundQueue.GetApplicationMessageCount();
if (applicationMessageQueueLength == 0)
break;
Thread.Sleep(100);
}
}
public void Stop()
{
IsBlockingApplicationMessages = true;
StopAcceptingClientMessages();
try
{
WaitToRerouteAllQueuedMessages();
OutboundQueue.Stop();
}
catch (Exception exc)
{
log.Error(ErrorCode.Runtime_Error_100110, "Stop failed.", exc);
}
}
public void StopAcceptingClientMessages()
{
if (log.IsEnabled(LogLevel.Debug)) log.Debug("StopClientMessages");
if (Gateway == null) return;
try
{
Gateway.Stop();
}
catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100109, "Stop failed.", exc); }
Gateway = null;
}
public Action<Message> RerouteHandler
{
set
{
if (rerouteHandler != null)
throw new InvalidOperationException("MessageCenter RerouteHandler already set");
rerouteHandler = value;
}
}
public void OnReceivedMessage(Message message)
{
var handler = this.dispatcher;
if (handler is null)
{
ThrowNullMessageHandler();
}
else
{
handler.ReceiveMessage(message);
}
static void ThrowNullMessageHandler() => throw new InvalidOperationException("MessageCenter does not have a message handler set");
}
public void RerouteMessage(Message message)
{
if (rerouteHandler != null)
rerouteHandler(message);
else
SendMessage(message);
}
public Action<Message> SniffIncomingMessage
{
set
{
if (this.sniffIncomingMessageHandler != null)
throw new InvalidOperationException("IncomingMessageAcceptor SniffIncomingMessage already set");
this.sniffIncomingMessageHandler = value;
}
get => this.sniffIncomingMessageHandler;
}
public void SendMessage(Message msg)
{
// Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here.
if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection)
&& !Constants.SystemMembershipTableType.Equals(msg.TargetGrain))
{
// Drop the message on the floor if it's an application message that isn't a rejection
this.messagingTrace.OnDropBlockedApplicationMessage(msg);
}
else
{
msg.SendingSilo ??= this.MyAddress;
OutboundQueue.SendMessage(msg);
}
}
public bool TrySendLocal(Message message)
{
if (!message.TargetSilo.Matches(MyAddress))
{
return false;
}
if (log.IsEnabled(LogLevel.Trace)) log.Trace("Message has been looped back to this silo: {0}", message);
MessagingStatisticsGroup.LocalMessagesSent.Increment();
this.OnReceivedMessage(message);
return true;
}
internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
if (msg.Direction == Message.Directions.Response && msg.Result == Message.ResponseTypes.Rejection)
{
// Do not send reject a rejection locally, it will create a stack overflow
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
if (this.log.IsEnabled(LogLevel.Debug)) log.Debug("Dropping rejection {msg}", msg);
}
else
{
if (string.IsNullOrEmpty(reason)) reason = $"Rejection from silo {this.MyAddress} - Unknown reason.";
var error = this.messageFactory.CreateRejectionResponse(msg, rejectionType, reason);
// rejection msgs are always originated in the local silo, they are never remote.
this.OnReceivedMessage(error);
}
}
public void SetDispatcher(Dispatcher dispatcher)
{
this.dispatcher = dispatcher;
}
public void Dispose()
{
OutboundQueue?.Dispose();
}
public int SendQueueLength { get { return OutboundQueue.GetCount(); } }
/// <summary>
/// Indicates that application messages should be blocked from being sent or received.
/// This method is used by the "fast stop" process.
/// <para>
/// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain.
/// Inbound application requests are rejected, and other inbound application messages are dropped.
/// </para>
/// </summary>
public void BlockApplicationMessages()
{
if(log.IsEnabled(LogLevel.Debug)) log.Debug("BlockApplicationMessages");
IsBlockingApplicationMessages = true;
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using MindTouch.Dream;
using MindTouch.IO;
using MindTouch.Threading;
namespace MindTouch.Tasking {
using Yield = IEnumerator<IYield>;
/// <summary>
/// Thrown when completion of all of a list of alternate synchronization handles fails.
/// </summary>
/// <remarks>Used by <see cref="AResultEx.Alt"/> and <see cref="AResultEx.Alt{T}"/>.</remarks>
/// <seealso cref="AResultEx.Alt"/>
/// <seealso cref="AResultEx.Alt{T}"/>
public class AsyncAllAlternatesFailed : Exception { }
/// <summary>
/// Static utility class containing extension and helper methods for handling asynchronous execution.
/// </summary>
public static class Async {
//--- Types ---
private delegate void AvailableThreadsDelegate(out int availableThreads, out int availablePorts);
//--- Class Fields ---
/// <summary>
/// The globally accessible <see cref="IDispatchQueue"/> for dispatching work without queue affinity.
/// </summary>
public static readonly IDispatchQueue GlobalDispatchQueue;
private static log4net.ILog _log = LogUtils.CreateLog();
private static readonly TimeSpan READ_TIMEOUT = TimeSpan.FromSeconds(30);
private static bool _inplaceActivation = true;
private static readonly int _minThreads;
private static readonly int _maxThreads;
private static readonly int _minPorts;
private static readonly int _maxPorts;
private static readonly AvailableThreadsDelegate _availableThreadsCallback;
[ThreadStatic]
private static IDispatchQueue _currentDispatchQueue;
//--- Constructors ---
static Async() {
if(!int.TryParse(System.Configuration.ConfigurationManager.AppSettings["threadpool-min"], out _minThreads)) {
_minThreads = 4;
}
if(!int.TryParse(System.Configuration.ConfigurationManager.AppSettings["threadpool-max"], out _maxThreads)) {
_maxThreads = 200;
}
// check which global dispatch queue implementation to use
int dummy;
switch(System.Configuration.ConfigurationManager.AppSettings["threadpool"]) {
default:
case "elastic":
ThreadPool.GetMinThreads(out dummy, out _minPorts);
ThreadPool.GetMaxThreads(out dummy, out _maxPorts);
_log.DebugFormat("Using ElasticThreadPool with {0}min / {1}max", _minThreads, _maxThreads);
var elasticThreadPool = new ElasticThreadPool(_minThreads, _maxThreads);
GlobalDispatchQueue = elasticThreadPool;
_inplaceActivation = false;
_availableThreadsCallback = delegate(out int threads, out int ports) {
int dummy2;
ThreadPool.GetAvailableThreads(out dummy2, out ports);
threads = elasticThreadPool.MaxParallelThreads - elasticThreadPool.ThreadCount;
};
break;
case "legacy":
ThreadPool.GetMinThreads(out dummy, out _minPorts);
ThreadPool.GetMaxThreads(out dummy, out _maxPorts);
ThreadPool.SetMinThreads(_minThreads, _minPorts);
ThreadPool.SetMaxThreads(_maxThreads, _maxPorts);
_log.Debug("Using LegacyThreadPool");
GlobalDispatchQueue = LegacyThreadPool.Instance;
_availableThreadsCallback = ThreadPool.GetAvailableThreads;
break;
}
}
//--- Class Properties ---
/// <summary>
/// The <see cref="IDispatchQueue"/> used by the current execution environment.
/// </summary>
public static IDispatchQueue CurrentDispatchQueue {
get {
return _currentDispatchQueue ?? (_inplaceActivation ? ImmediateDispatchQueue.Instance : GlobalDispatchQueue);
}
set {
_currentDispatchQueue = value;
}
}
//--- Class Methods ---
/// <summary>
/// Get the maximum number of resources allowed for this process' execution environment.
/// </summary>
/// <param name="threads">Number of threads allowed.</param>
/// <param name="ports">Number of completion ports allowed.</param>
/// <param name="dispatchers">Number of dispatchers allowed.</param>
public static void GetMaxThreads(out int threads, out int ports, out int dispatchers) {
threads = _maxThreads;
ports = _maxPorts;
dispatchers = DispatchThreadScheduler.MaxThreadCount;
}
/// <summary>
/// Get the minimum number of resources allocated forthis process' execution environment.
/// </summary>
/// <param name="threads">Minimum number of threads allocated.</param>
/// <param name="ports">Minimum number of completion ports allocated.</param>
/// <param name="dispatchers">Minimum number of dispatchers allocated.</param>
public static void GetAvailableThreads(out int threads, out int ports, out int dispatchers) {
_availableThreadsCallback(out threads, out ports);
dispatchers = DispatchThreadScheduler.AvailableThreadCount;
}
/// <summary>
/// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>.
/// </summary>
/// <param name="handler">Action to enqueue for execution.</param>
public static void Fork(Action handler) {
GlobalDispatchQueue.QueueWorkItemWithClonedEnv(handler, null);
}
/// <summary>
/// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>.
/// </summary>
/// <param name="handler">Action to enqueue for execution.</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle for the action's execution.</returns>
public static Result Fork(Action handler, Result result) {
return GlobalDispatchQueue.QueueWorkItemWithClonedEnv(handler, result);
}
/// <summary>
/// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>.
/// </summary>
/// <param name="handler">Action to enqueue for execution.</param>
/// <param name="env">Environment in which to execute the action.</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle for the action's execution.</returns>
public static Result Fork(Action handler, TaskEnv env, Result result) {
return GlobalDispatchQueue.QueueWorkItemWithEnv(handler, env, result);
}
/// <summary>
/// Dispatch an action to be executed via the <see cref="GlobalDispatchQueue"/>.
/// </summary>
/// <typeparam name="T">Type of result value produced by action.</typeparam>
/// <param name="handler">Action to enqueue for execution.</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle for the action's execution.</returns>
public static Result<T> Fork<T>(Func<T> handler, Result<T> result) {
return GlobalDispatchQueue.QueueWorkItemWithClonedEnv(handler, result);
}
/// <summary>
/// Dispatch an action to be executed with a new, dedicated backgrouns thread.
/// </summary>
/// <param name="handler">Action to enqueue for execution.</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle for the action's execution.</returns>
public static Result ForkThread(Action handler, Result result) {
ForkThread(TaskEnv.Clone().MakeAction(handler, result));
return result;
}
/// <summary>
/// Dispatch an action to be executed with a new, dedicated backgrouns thread.
/// </summary>
/// <typeparam name="T">Type of result value produced by action.</typeparam>
/// <param name="handler">Action to enqueue for execution.</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle for the action's execution.</returns>
public static Result<T> ForkThread<T>(Func<T> handler, Result<T> result) {
ForkThread(TaskEnv.Clone().MakeAction(handler, result));
return result;
}
/// <summary>
/// Dispatch an action to be executed with a new, dedicated backgrouns thread.
/// </summary>
/// <param name="handler">Action to enqueue for execution.</param>
private static void ForkThread(Action handler) {
var t = new Thread(() => handler()) { IsBackground = true };
t.Start();
}
/// <summary>
/// De-schedule the current execution environment to sleep for some period.
/// </summary>
/// <param name="duration">Time to sleep.</param>
/// <returns>Synchronization handle to continue execution after the sleep period.</returns>
public static Result Sleep(TimeSpan duration) {
Result result = new Result(TimeSpan.MaxValue);
TaskTimerFactory.Current.New(duration, _ => result.Return(), null, TaskEnv.New());
return result;
}
/// <summary>
/// Wrap a <see cref="WaitHandle"/> with <see cref="Result{WaitHandle}"/> to allow Result style synchronization with the handle.
/// </summary>
/// <param name="handle">The handle to wrap</param>
/// <param name="result">The <see cref="Result{WaitHandle}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle for the action's execution.</returns>
public static Result<WaitHandle> WaitHandle(this WaitHandle handle, Result<WaitHandle> result) {
ThreadPool.RegisterWaitForSingleObject(handle, delegate(object _unused, bool timedOut) {
if(timedOut) {
result.Throw(new TimeoutException());
} else {
result.Return(handle);
}
}, null, (int)result.Timeout.TotalMilliseconds, true);
return result;
}
/// <summary>
/// Execute a system process.
/// </summary>
/// <param name="application">Application to execute.</param>
/// <param name="cmdline">Command line parameters for he application.</param>
/// <param name="input">Input stream to pipe into the application.</param>
/// <param name="result">The Result instance to be returned by this method.</param>
/// <returns>Synchronization handle for the process execution, providing the application's exit code, output Stream and error Stream</returns>
public static Result<Tuplet<int, Stream, Stream>> ExecuteProcess(string application, string cmdline, Stream input, Result<Tuplet<int, Stream, Stream>> result) {
Stream output = new ChunkedMemoryStream();
Stream error = new ChunkedMemoryStream();
Result<int> innerResult = new Result<int>(result.Timeout);
Coroutine.Invoke(ExecuteProcess_Helper, application, cmdline, input, output, error, innerResult).WhenDone(delegate(Result<int> _unused) {
if(innerResult.HasException) {
result.Throw(innerResult.Exception);
} else {
// reset stream positions
output.Position = 0;
error.Position = 0;
// return outcome
result.Return(new Tuplet<int, Stream, Stream>(innerResult.Value, output, error));
}
});
return result;
}
/// <summary>
/// Execute a system process.
/// </summary>
/// <param name="application">Application to execute.</param>
/// <param name="cmdline">Command line parameters for he application.</param>
/// <param name="input">Input stream to pipe into the application.</param>
/// <param name="output"></param>
/// <param name="error"></param>
/// <param name="result">The <see cref="Result{Int32}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle for the process execution, providing the application's exit code</returns>
public static Result<int> ExecuteProcess(string application, string cmdline, Stream input, Stream output, Stream error, Result<int> result) {
return Coroutine.Invoke(ExecuteProcess_Helper, application, cmdline, input, output, error, result);
}
private static Yield ExecuteProcess_Helper(string application, string cmdline, Stream input, Stream output, Stream error, Result<int> result) {
// start process
var proc = new Process();
proc.StartInfo.FileName = application;
proc.StartInfo.Arguments = cmdline;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardInput = (input != null);
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
// inject input
if(input != null) {
input.CopyTo(proc.StandardInput.BaseStream, long.MaxValue, new Result<long>(TimeSpan.MaxValue)).WhenDone(_ => {
// trying closing the original input stream
try {
input.Close();
} catch { }
// try closing the process input pipe
try {
proc.StandardInput.Close();
} catch { }
});
}
// extract output stream
Result<long> outputDone = proc.StandardOutput.BaseStream.CopyTo(output, long.MaxValue, new Result<long>(TimeSpan.MaxValue));
// extract error stream
Result<long> errorDone = proc.StandardError.BaseStream.CopyTo(error, long.MaxValue, new Result<long>(TimeSpan.MaxValue));
TaskTimer timer = TaskTimerFactory.Current.New(result.Timeout, delegate(TaskTimer t) {
try {
// NOTE (steveb): we had to add the try..catch handler because mono throws an exception when killing a terminated process (why? who knows!)
proc.Kill();
} catch { }
}, null, TaskEnv.New());
// wait for output and error streams to be done
yield return new AResult[] { outputDone, errorDone }.Join();
int? exitCode = WaitForExit(proc, result.Timeout);
timer.Cancel();
proc.Close();
if(exitCode.HasValue) {
result.Return(exitCode.Value);
} else {
result.Throw(new InvalidOperationException("Unable to access process exit code"));
}
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <param name="begin">Lambda wrapping a no-arg async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle.</returns>
public static Result From(Func<AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, object state, Result result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
end(v);
} catch(Exception e) {
result.Throw(e);
return;
}
result.Return();
},
result.Throw
);
// begin asynchronous invocation
try {
begin(continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T1">Type of asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a single argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">Asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle.</returns>
public static Result From<T1>(Func<T1, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, object state, Result result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
end(v);
} catch(Exception e) {
result.Throw(e);
return;
}
result.Return();
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 2 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle.</returns>
public static Result From<T1, T2>(Func<T1, T2, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, object state, Result result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
end(v);
} catch(Exception e) {
result.Throw(e);
return;
}
result.Return();
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 3 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle.</returns>
public static Result From<T1, T2, T3>(Func<T1, T2, T3, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, object state, Result result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
end(v);
} catch(Exception e) {
result.Throw(e);
return;
}
result.Return();
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 4 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="item4">Fourth asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle.</returns>
public static Result From<T1, T2, T3, T4>(Func<T1, T2, T3, T4, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, T4 item4, object state, Result result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
end(v);
} catch(Exception e) {
result.Throw(e);
return;
}
result.Return();
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, item4, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam>
/// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 5 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="item4">Fourth asynchronous method argument.</param>
/// <param name="item5">Fifth asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle.</returns>
public static Result From<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, object state, Result result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
end(v);
} catch(Exception e) {
result.Throw(e);
return;
}
result.Return();
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, item4, item5, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam>
/// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam>
/// <typeparam name="T6">Type of sixth asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 6 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="item4">Fourth asynchronous method argument.</param>
/// <param name="item5">Fifth asynchronous method argument.</param>
/// <param name="item6">Sixth asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle.</returns>
public static Result From<T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6, AsyncCallback, object, IAsyncResult> begin, Action<IAsyncResult> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, object state, Result result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
end(v);
} catch(Exception e) {
result.Throw(e);
return;
}
result.Return();
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, item4, item5, item6, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T">Type of the asynchronous method return value.</typeparam>
/// <param name="begin">Lambda wrapping a no argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle providing result value T.</returns>
public static Result<T> From<T>(Func<AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, object state, Result<T> result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
result.Return(end(v));
} catch(Exception e) {
result.Throw(e);
}
},
result.Throw
);
// begin asynchronous invocation
try {
begin(continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T">Type of the asynchronous method return value.</typeparam>
/// <typeparam name="T1">Type of asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a single argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">Asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle providing result value T.</returns>
public static Result<T> From<T, T1>(Func<T1, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, object state, Result<T> result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
result.Return(end(v));
} catch(Exception e) {
result.Throw(e);
}
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T">Type of the asynchronous method return value.</typeparam>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 2 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle providing result value T.</returns>
public static Result<T> From<T, T1, T2>(Func<T1, T2, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, object state, Result<T> result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
result.Return(end(v));
} catch(Exception e) {
result.Throw(e);
}
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T">Type of the asynchronous method return value.</typeparam>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 3 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle providing result value T.</returns>
public static Result<T> From<T, T1, T2, T3>(Func<T1, T2, T3, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, object state, Result<T> result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
result.Return(end(v));
} catch(Exception e) {
result.Throw(e);
}
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T">Type of the asynchronous method return value.</typeparam>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 4 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="item4">Fourth asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle providing result value T.</returns>
public static Result<T> From<T, T1, T2, T3, T4>(Func<T1, T2, T3, T4, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, T4 item4, object state, Result<T> result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
result.Return(end(v));
} catch(Exception e) {
result.Throw(e);
}
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, item4, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T">Type of the asynchronous method return value.</typeparam>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam>
/// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 5 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="item4">Fourth asynchronous method argument.</param>
/// <param name="item5">Fifth asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle providing result value T.</returns>
public static Result<T> From<T, T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, object state, Result<T> result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
result.Return(end(v));
} catch(Exception e) {
result.Throw(e);
}
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, item4, item5, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Convert an asynchronous call using the <see cref="AsyncCallback"/> pattern into one using a <see cref="Result"/> synchronization handle.
/// </summary>
/// <typeparam name="T">Type of the asynchronous method return value.</typeparam>
/// <typeparam name="T1">Type of first asynchronous method argument.</typeparam>
/// <typeparam name="T2">Type of second asynchronous method argument.</typeparam>
/// <typeparam name="T3">Type of third asynchronous method argument.</typeparam>
/// <typeparam name="T4">Type of fourth asynchronous method argument.</typeparam>
/// <typeparam name="T5">Type of fifth asynchronous method argument.</typeparam>
/// <typeparam name="T6">Type of sixth asynchronous method argument.</typeparam>
/// <param name="begin">Lambda wrapping a 6 argument async call.</param>
/// <param name="end">Action to execute on async completion.</param>
/// <param name="item1">First asynchronous method argument.</param>
/// <param name="item2">Second asynchronous method argument.</param>
/// <param name="item3">Third asynchronous method argument.</param>
/// <param name="item4">Fourth asynchronous method argument.</param>
/// <param name="item5">Fifth asynchronous method argument.</param>
/// <param name="item6">Sixth asynchronous method argument.</param>
/// <param name="state">State object</param>
/// <param name="result">The <see cref="Result{T}"/>instance to be returned by this method.</param>
/// <returns>Synchronization handle providing result value T.</returns>
public static Result<T> From<T, T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6, AsyncCallback, object, IAsyncResult> begin, Func<IAsyncResult, T> end, T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, object state, Result<T> result) {
// define continuation for asynchronous invocation
var continuation = new Result<IAsyncResult>(TimeSpan.MaxValue).WhenDone(
v => {
try {
result.Return(end(v));
} catch(Exception e) {
result.Throw(e);
}
},
result.Throw
);
// begin asynchronous invocation
try {
begin(item1, item2, item3, item4, item5, item6, continuation.Return, state);
} catch(Exception e) {
result.Throw(e);
}
// return yield handle
return result;
}
/// <summary>
/// Waits for handle to be set.
/// </summary>
/// <param name="handle">Handle to wait on.</param>
/// <param name="timeout">Timeout period. Use <cref see="TimeSpan"/>.MaxValue for no timeout.</param>
/// <returns>Returns true if the handle was set before the timeout, false otherwise.</returns>
public static bool WaitFor(WaitHandle handle, TimeSpan timeout) {
DispatchThreadEvictWorkItems();
return handle.WaitOne((timeout == TimeSpan.MaxValue) ? Timeout.Infinite : (int)timeout.TotalMilliseconds);
}
/// <summary>
/// Waits for event to be signaled.
/// </summary>
/// <param name="monitor">Event to wait on.</param>
/// <param name="timeout">Timeout period. Use <cref see="TimeSpan"/>.MaxValue for no timeout.</param>
/// <returns>Returns true if the event was signaled before the timeout, false otherwise.</returns>
public static bool WaitFor(MonitorSemaphore monitor, TimeSpan timeout) {
DispatchThreadEvictWorkItems();
return monitor.Wait(timeout);
}
private static int? WaitForExit(Process process, TimeSpan retryTime) {
//NOTE (arnec): WaitForExit is unreliable on mono, so we have to loop on ExitCode to make sure
// the process really has exited
DateTime end = DateTime.UtcNow.Add(retryTime);
process.WaitForExit();
do {
try {
return process.ExitCode;
} catch(InvalidOperationException) {
Thread.Sleep(TimeSpan.FromMilliseconds(50));
}
} while(end > DateTime.UtcNow);
return null;
}
private static void DispatchThreadEvictWorkItems() {
var thread = DispatchThread.CurrentThread;
if(thread != null) {
thread.EvictWorkItems();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Mime;
using System.Runtime.ExceptionServices;
using System.Text;
namespace System.Net.Mail
{
public enum MailPriority
{
Normal = 0,
Low = 1,
High = 2
}
internal class Message
{
#region Fields
private MailAddress _from;
private MailAddress _sender;
private MailAddressCollection _replyToList;
private MailAddress _replyTo;
private MailAddressCollection _to;
private MailAddressCollection _cc;
private MailAddressCollection _bcc;
private MimeBasePart _content;
private HeaderCollection _headers;
private HeaderCollection _envelopeHeaders;
private string _subject;
private Encoding _subjectEncoding;
private Encoding _headersEncoding;
private MailPriority _priority = (MailPriority)(-1);
#endregion Fields
#region Constructors
internal Message()
{
}
internal Message(string from, string to) : this()
{
if (from == null)
throw new ArgumentNullException(nameof(from));
if (to == null)
throw new ArgumentNullException(nameof(to));
if (from == string.Empty)
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(from)), nameof(from));
if (to == string.Empty)
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(to)), nameof(to));
_from = new MailAddress(from);
MailAddressCollection collection = new MailAddressCollection();
collection.Add(to);
_to = collection;
}
internal Message(MailAddress from, MailAddress to) : this()
{
_from = from;
To.Add(to);
}
#endregion Constructors
#region Properties
public MailPriority Priority
{
get
{
return (((int)_priority == -1) ? MailPriority.Normal : _priority);
}
set
{
_priority = value;
}
}
internal MailAddress From
{
get
{
return _from;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_from = value;
}
}
internal MailAddress Sender
{
get
{
return _sender;
}
set
{
_sender = value;
}
}
internal MailAddress ReplyTo
{
get
{
return _replyTo;
}
set
{
_replyTo = value;
}
}
internal MailAddressCollection ReplyToList
{
get
{
if (_replyToList == null)
_replyToList = new MailAddressCollection();
return _replyToList;
}
}
internal MailAddressCollection To
{
get
{
if (_to == null)
_to = new MailAddressCollection();
return _to;
}
}
internal MailAddressCollection Bcc
{
get
{
if (_bcc == null)
_bcc = new MailAddressCollection();
return _bcc;
}
}
internal MailAddressCollection CC
{
get
{
if (_cc == null)
_cc = new MailAddressCollection();
return _cc;
}
}
internal string Subject
{
get
{
return _subject;
}
set
{
Encoding inputEncoding = null;
try
{
// extract the encoding from =?encoding?BorQ?blablalba?=
inputEncoding = MimeBasePart.DecodeEncoding(value);
}
catch (ArgumentException) { };
if (inputEncoding != null && value != null)
{
try
{
// Store the decoded value, we'll re-encode before sending
value = MimeBasePart.DecodeHeaderValue(value);
_subjectEncoding = _subjectEncoding ?? inputEncoding;
}
// Failed to decode, just pass it through as ascii (legacy)
catch (FormatException) { }
}
if (value != null && MailBnfHelper.HasCROrLF(value))
{
throw new ArgumentException(SR.MailSubjectInvalidFormat);
}
_subject = value;
if (_subject != null)
{
_subject = _subject.Normalize(NormalizationForm.FormC);
if (_subjectEncoding == null && !MimeBasePart.IsAscii(_subject, false))
{
_subjectEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
}
}
}
internal Encoding SubjectEncoding
{
get
{
return _subjectEncoding;
}
set
{
_subjectEncoding = value;
}
}
internal HeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = new HeaderCollection();
if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _headers);
}
return _headers;
}
}
internal Encoding HeadersEncoding
{
get
{
return _headersEncoding;
}
set
{
_headersEncoding = value;
}
}
internal HeaderCollection EnvelopeHeaders
{
get
{
if (_envelopeHeaders == null)
{
_envelopeHeaders = new HeaderCollection();
if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _envelopeHeaders);
}
return _envelopeHeaders;
}
}
internal virtual MimeBasePart Content
{
get
{
return _content;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_content = value;
}
}
#endregion Properties
#region Sending
internal void EmptySendCallback(IAsyncResult result)
{
Exception e = null;
if (result.CompletedSynchronously)
{
return;
}
EmptySendContext context = (EmptySendContext)result.AsyncState;
try
{
context._writer.EndGetContentStream(result).Close();
}
catch (Exception ex)
{
e = ex;
}
context._result.InvokeCallback(e);
}
internal class EmptySendContext
{
internal EmptySendContext(BaseWriter writer, LazyAsyncResult result)
{
_writer = writer;
_result = result;
}
internal LazyAsyncResult _result;
internal BaseWriter _writer;
}
internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
AsyncCallback callback, object state)
{
PrepareHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
if (Content != null)
{
return Content.BeginSend(writer, callback, allowUnicode, state);
}
else
{
LazyAsyncResult result = new LazyAsyncResult(this, state, callback);
IAsyncResult newResult = writer.BeginGetContentStream(EmptySendCallback, new EmptySendContext(writer, result));
if (newResult.CompletedSynchronously)
{
writer.EndGetContentStream(newResult).Close();
}
return result;
}
}
internal virtual void EndSend(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
if (Content != null)
{
Content.EndSend(asyncResult);
}
else
{
LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult);
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndSend)));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
if (castedAsyncResult.Result is Exception e)
{
ExceptionDispatchInfo.Throw(e);
}
}
}
internal virtual void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode)
{
if (sendEnvelope)
{
PrepareEnvelopeHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(EnvelopeHeaders, allowUnicode);
}
PrepareHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
if (Content != null)
{
Content.Send(writer, allowUnicode);
}
else
{
writer.GetContentStream().Close();
}
}
internal void PrepareEnvelopeHeaders(bool sendEnvelope, bool allowUnicode)
{
if (_headersEncoding == null)
{
_headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
EncodeHeaders(EnvelopeHeaders, allowUnicode);
// Only add X-Sender header if it wasn't already set by the user
string xSenderHeader = MailHeaderInfo.GetString(MailHeaderID.XSender);
if (!IsHeaderSet(xSenderHeader))
{
MailAddress sender = Sender ?? From;
EnvelopeHeaders.InternalSet(xSenderHeader, sender.Encode(xSenderHeader.Length, allowUnicode));
}
string headerName = MailHeaderInfo.GetString(MailHeaderID.XReceiver);
EnvelopeHeaders.Remove(headerName);
foreach (MailAddress address in To)
{
EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode));
}
foreach (MailAddress address in CC)
{
EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode));
}
foreach (MailAddress address in Bcc)
{
EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode));
}
}
internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode)
{
string headerName;
if (_headersEncoding == null)
{
_headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
//ContentType is written directly to the stream so remove potential user duplicate
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType));
Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0";
// add sender to headers first so that it is written first to allow the IIS smtp svc to
// send MAIL FROM with the sender if both sender and from are present
headerName = MailHeaderInfo.GetString(MailHeaderID.Sender);
if (Sender != null)
{
Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
headerName = MailHeaderInfo.GetString(MailHeaderID.From);
Headers.InternalAdd(headerName, From.Encode(headerName.Length, allowUnicode));
headerName = MailHeaderInfo.GetString(MailHeaderID.To);
if (To.Count > 0)
{
Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
headerName = MailHeaderInfo.GetString(MailHeaderID.Cc);
if (CC.Count > 0)
{
Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo);
if (ReplyTo != null)
{
Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode));
}
else if (ReplyToList.Count > 0)
{
Headers.InternalAdd(headerName, ReplyToList.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc));
if (_priority == MailPriority.High)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "1";
Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "urgent";
Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "high";
}
else if (_priority == MailPriority.Low)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "5";
Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "non-urgent";
Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "low";
}
//if the priority was never set, allow the app to set the headers directly.
else if (((int)_priority) != -1)
{
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority));
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority));
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance));
}
Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date),
MailBnfHelper.GetDateTimeString(DateTime.Now, null));
headerName = MailHeaderInfo.GetString(MailHeaderID.Subject);
if (!string.IsNullOrEmpty(_subject))
{
if (allowUnicode)
{
Headers.InternalAdd(headerName, _subject);
}
else
{
Headers.InternalAdd(headerName,
MimeBasePart.EncodeHeaderValue(_subject, _subjectEncoding,
MimeBasePart.ShouldUseBase64Encoding(_subjectEncoding),
headerName.Length));
}
}
else
{
Headers.Remove(headerName);
}
EncodeHeaders(_headers, allowUnicode);
}
internal void EncodeHeaders(HeaderCollection headers, bool allowUnicode)
{
if (_headersEncoding == null)
{
_headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
System.Diagnostics.Debug.Assert(_headersEncoding != null);
for (int i = 0; i < headers.Count; i++)
{
string headerName = headers.GetKey(i);
//certain well-known values are encoded by PrepareHeaders and PrepareEnvelopeHeaders
//so we can ignore them because either we encoded them already or there is no
//way for the user to have set them. If a header is well known and user settable then
//we should encode it here, otherwise we have already encoded it if necessary
if (!MailHeaderInfo.IsUserSettable(headerName))
{
continue;
}
string[] values = headers.GetValues(headerName);
string encodedValue = string.Empty;
for (int j = 0; j < values.Length; j++)
{
//encode if we need to
if (MimeBasePart.IsAscii(values[j], false)
|| (allowUnicode && MailHeaderInfo.AllowsUnicode(headerName) // EAI
&& !MailBnfHelper.HasCROrLF(values[j])))
{
encodedValue = values[j];
}
else
{
encodedValue = MimeBasePart.EncodeHeaderValue(values[j],
_headersEncoding,
MimeBasePart.ShouldUseBase64Encoding(_headersEncoding),
headerName.Length);
}
//potentially there are multiple values per key
if (j == 0)
{
//if it's the first or only value, set will overwrite all the values assigned to that key
//which is fine since we have them stored in values[]
headers.Set(headerName, encodedValue);
}
else
{
//this is a subsequent key, so we must Add it since the first key will have overwritten the
//other values
headers.Add(headerName, encodedValue);
}
}
}
}
private bool IsHeaderSet(string headerName)
{
for (int i = 0; i < Headers.Count; i++)
{
if (string.Equals(Headers.GetKey(i), headerName, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
#endregion Sending
}
}
| |
// 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.Serialization;
namespace System.Collections.Generic
{
public partial class SortedSet<T>
{
/// <summary>
/// This class represents a subset view into the tree. Any changes to this view
/// are reflected in the actual tree. It uses the comparer of the underlying tree.
/// </summary>
[Serializable]
internal sealed class TreeSubSet : SortedSet<T>, ISerializable, IDeserializationCallback
{
private SortedSet<T> _underlying;
private T _min, _max;
// these exist for unbounded collections
// for instance, you could allow this subset to be defined for i > 10. The set will throw if
// anything <= 10 is added, but there is no upper bound. These features Head(), Tail(), were punted
// in the spec, and are not available, but the framework is there to make them available at some point.
private bool _lBoundActive, _uBoundActive;
// used to see if the count is out of date
#if DEBUG
internal override bool versionUpToDate()
{
return (_version == _underlying._version);
}
#endif
public TreeSubSet(SortedSet<T> Underlying, T Min, T Max, bool lowerBoundActive, bool upperBoundActive)
: base(Underlying.Comparer)
{
_underlying = Underlying;
_min = Min;
_max = Max;
_lBoundActive = lowerBoundActive;
_uBoundActive = upperBoundActive;
_root = _underlying.FindRange(_min, _max, _lBoundActive, _uBoundActive); // root is first element within range
_count = 0;
_version = -1;
VersionCheckImpl();
}
private TreeSubSet(SerializationInfo info, StreamingContext context)
{
_siInfo = info;
OnDeserializationImpl(info);
}
internal override bool AddIfNotPresent(T item)
{
if (!IsWithinRange(item))
{
throw new ArgumentOutOfRangeException(nameof(item));
}
bool ret = _underlying.AddIfNotPresent(item);
VersionCheck();
#if DEBUG
Debug.Assert(this.versionUpToDate() && _root == _underlying.FindRange(_min, _max));
#endif
return ret;
}
public override bool Contains(T item)
{
VersionCheck();
#if DEBUG
Debug.Assert(versionUpToDate() && _root == _underlying.FindRange(_min, _max));
#endif
return base.Contains(item);
}
internal override bool DoRemove(T item)
{
if (!IsWithinRange(item))
{
return false;
}
bool ret = _underlying.Remove(item);
VersionCheck();
#if DEBUG
Debug.Assert(versionUpToDate() && _root == _underlying.FindRange(_min, _max));
#endif
return ret;
}
public override void Clear()
{
if (_count == 0)
{
return;
}
List<T> toRemove = new List<T>();
BreadthFirstTreeWalk(n => { toRemove.Add(n.Item); return true; });
while (toRemove.Count != 0)
{
_underlying.Remove(toRemove[toRemove.Count - 1]);
toRemove.RemoveAt(toRemove.Count - 1);
}
_root = null;
_count = 0;
_version = _underlying._version;
}
internal override bool IsWithinRange(T item)
{
int comp = _lBoundActive ? Comparer.Compare(_min, item) : -1;
if (comp > 0)
{
return false;
}
comp = _uBoundActive ? Comparer.Compare(_max, item) : 1;
return comp >= 0;
}
internal override T MinInternal
{
get
{
Node current = _root;
T result = default(T);
while (current != null)
{
int comp = _lBoundActive ? Comparer.Compare(_min, current.Item) : -1;
if (comp == 1)
{
current = current.Right;
}
else
{
result = current.Item;
if (comp == 0)
{
break;
}
current = current.Left;
}
}
return result;
}
}
internal override T MaxInternal
{
get
{
Node current = _root;
T result = default(T);
while (current != null)
{
int comp = _uBoundActive ? Comparer.Compare(_max, current.Item) : 1;
if (comp == -1)
{
current = current.Left;
}
else
{
result = current.Item;
if (comp == 0)
{
break;
}
current = current.Right;
}
}
return result;
}
}
internal override bool InOrderTreeWalk(TreeWalkPredicate<T> action)
{
VersionCheck();
if (_root == null)
{
return true;
}
// The maximum height of a red-black tree is 2*lg(n+1).
// See page 264 of "Introduction to algorithms" by Thomas H. Cormen
Stack<Node> stack = new Stack<Node>(2 * (int)SortedSet<T>.Log2(_count + 1)); // this is not exactly right if count is out of date, but the stack can grow
Node current = _root;
while (current != null)
{
if (IsWithinRange(current.Item))
{
stack.Push(current);
current = current.Left;
}
else if (_lBoundActive && Comparer.Compare(_min, current.Item) > 0)
{
current = current.Right;
}
else
{
current = current.Left;
}
}
while (stack.Count != 0)
{
current = stack.Pop();
if (!action(current))
{
return false;
}
Node node = current.Right;
while (node != null)
{
if (IsWithinRange(node.Item))
{
stack.Push(node);
node = node.Left;
}
else if (_lBoundActive && Comparer.Compare(_min, node.Item) > 0)
{
node = node.Right;
}
else
{
node = node.Left;
}
}
}
return true;
}
internal override bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action)
{
VersionCheck();
if (_root == null)
{
return true;
}
Queue<Node> processQueue = new Queue<Node>();
processQueue.Enqueue(_root);
Node current;
while (processQueue.Count != 0)
{
current = processQueue.Dequeue();
if (IsWithinRange(current.Item) && !action(current))
{
return false;
}
if (current.Left != null && (!_lBoundActive || Comparer.Compare(_min, current.Item) < 0))
{
processQueue.Enqueue(current.Left);
}
if (current.Right != null && (!_uBoundActive || Comparer.Compare(_max, current.Item) > 0))
{
processQueue.Enqueue(current.Right);
}
}
return true;
}
internal override SortedSet<T>.Node FindNode(T item)
{
if (!IsWithinRange(item))
{
return null;
}
VersionCheck();
#if DEBUG
Debug.Assert(this.versionUpToDate() && _root == _underlying.FindRange(_min, _max));
#endif
return base.FindNode(item);
}
// this does indexing in an inefficient way compared to the actual sortedset, but it saves a
// lot of space
internal override int InternalIndexOf(T item)
{
int count = -1;
foreach (T i in this)
{
count++;
if (Comparer.Compare(item, i) == 0)
return count;
}
#if DEBUG
Debug.Assert(this.versionUpToDate() && _root == _underlying.FindRange(_min, _max));
#endif
return -1;
}
/// <summary>
/// Checks whether this subset is out of date, and updates it if necessary.
/// </summary>
internal override void VersionCheck() => VersionCheckImpl();
private void VersionCheckImpl()
{
Debug.Assert(_underlying != null);
if (_version != _underlying._version)
{
_root = _underlying.FindRange(_min, _max, _lBoundActive, _uBoundActive);
_version = _underlying._version;
_count = 0;
InOrderTreeWalk(n => { _count++; return true; });
}
}
// This passes functionality down to the underlying tree, clipping edges if necessary
// There's nothing gained by having a nested subset. May as well draw it from the base
// Cannot increase the bounds of the subset, can only decrease it
public override SortedSet<T> GetViewBetween(T lowerValue, T upperValue)
{
if (_lBoundActive && Comparer.Compare(_min, lowerValue) > 0)
{
throw new ArgumentOutOfRangeException(nameof(lowerValue));
}
if (_uBoundActive && Comparer.Compare(_max, upperValue) < 0)
{
throw new ArgumentOutOfRangeException(nameof(upperValue));
}
return (TreeSubSet)_underlying.GetViewBetween(lowerValue, upperValue);
}
#if DEBUG
internal override void IntersectWithEnumerable(IEnumerable<T> other)
{
base.IntersectWithEnumerable(other);
Debug.Assert(versionUpToDate() && _root == _underlying.FindRange(_min, _max));
}
#endif
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) => GetObjectData(info, context);
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(MaxName, _max, typeof(T));
info.AddValue(MinName, _min, typeof(T));
info.AddValue(LowerBoundActiveName, _lBoundActive);
info.AddValue(UpperBoundActiveName, _uBoundActive);
base.GetObjectData(info, context);
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
// Don't do anything here as the work has already been done by the constructor
}
protected override void OnDeserialization(Object sender) => OnDeserializationImpl(sender);
private void OnDeserializationImpl(Object sender)
{
if (_siInfo == null)
{
throw new SerializationException(SR.Serialization_InvalidOnDeser);
}
_comparer = (IComparer<T>)_siInfo.GetValue(ComparerName, typeof(IComparer<T>));
int savedCount = _siInfo.GetInt32(CountName);
_max = (T)_siInfo.GetValue(MaxName, typeof(T));
_min = (T)_siInfo.GetValue(MinName, typeof(T));
_lBoundActive = _siInfo.GetBoolean(LowerBoundActiveName);
_uBoundActive = _siInfo.GetBoolean(UpperBoundActiveName);
_underlying = new SortedSet<T>();
if (savedCount != 0)
{
T[] items = (T[])_siInfo.GetValue(ItemsName, typeof(T[]));
if (items == null)
{
throw new SerializationException(SR.Serialization_MissingValues);
}
for (int i = 0; i < items.Length; i++)
{
_underlying.Add(items[i]);
}
}
_underlying._version = _siInfo.GetInt32(VersionName);
_count = _underlying._count;
_version = _underlying._version - 1;
VersionCheck(); // this should update the count to be right and update root to be right
if (_count != savedCount)
{
throw new SerializationException(SR.Serialization_MismatchedCount);
}
_siInfo = null;
}
}
}
}
| |
//
// LargeTrackInfoDisplay.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// 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 Gtk;
using Cairo;
using Hyena;
using Hyena.Gui;
using Banshee.Collection;
using Banshee.Collection.Gui;
namespace Banshee.Gui.Widgets
{
public class LargeTrackInfoDisplay : TrackInfoDisplay
{
private Gdk.Rectangle track_info_alloc;
private Dictionary<ImageSurface, Surface> surfaces = new Dictionary<ImageSurface, Surface> ();
private Pango.Layout first_line_layout;
private Pango.Layout second_line_layout;
private Pango.Layout third_line_layout;
public LargeTrackInfoDisplay ()
{
}
protected LargeTrackInfoDisplay (IntPtr native) : base (native)
{
}
protected override int MissingIconSizeRequest {
get { return 128; }
}
protected virtual int MaxArtworkSize {
get { return 300; }
}
protected virtual int Spacing {
get { return 30; }
}
protected override int ArtworkSizeRequest {
get { return Math.Min (Math.Min (Allocation.Height, Allocation.Width), MaxArtworkSize); }
}
protected virtual Gdk.Rectangle RenderAllocation {
get {
int width = ArtworkSizeRequest * 2 + Spacing;
int height = (int)Math.Ceiling (ArtworkSizeRequest * 1.2);
int x = Allocation.X + (Allocation.Width - width) / 2;
int y = Allocation.Y + (Allocation.Height - height) / 2;
return new Gdk.Rectangle (x, y, width, height);
}
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
QueueDraw ();
}
protected override void OnThemeChanged ()
{
if (first_line_layout != null) {
first_line_layout.FontDescription.Dispose ();
first_line_layout.Dispose ();
first_line_layout = null;
}
if (second_line_layout != null) {
second_line_layout.FontDescription.Dispose ();
second_line_layout.Dispose ();
second_line_layout = null;
}
if (third_line_layout != null) {
third_line_layout.FontDescription.Dispose ();
third_line_layout.Dispose ();
third_line_layout = null;
}
}
protected override void RenderCoverArt (Cairo.Context cr, ImageSurface image)
{
if (image == null) {
return;
}
Gdk.Rectangle alloc = RenderAllocation;
int asr = ArtworkSizeRequest;
int reflect = (int)(image.Height * 0.2);
int surface_w = image.Width;
int surface_h = image.Height + reflect;
int x = alloc.X + alloc.Width - asr;
int y = alloc.Y;
Surface scene = null;
if (!surfaces.TryGetValue (image, out scene)) {
scene = CreateScene (cr, image, reflect);
surfaces.Add (image, scene);
}
cr.Rectangle (x, y, asr, alloc.Height);
cr.Color = BackgroundColor;
cr.Fill ();
x += (asr - surface_w) / 2;
y += surface_h > asr ? 0 : (asr - surface_h) / 2;
cr.SetSource (scene, x, y);
cr.Paint ();
}
private Surface CreateScene (Cairo.Context window_cr, ImageSurface image, int reflect)
{
Surface surface = window_cr.Target.CreateSimilar (window_cr.Target.Content,
image.Width, image.Height + reflect);
Cairo.Context cr = new Context (surface);
cr.Save ();
cr.SetSource (image);
cr.Paint ();
cr.Rectangle (0, image.Height, image.Width, reflect);
cr.Clip ();
Matrix matrix = new Matrix ();
matrix.InitScale (1, -1);
matrix.Translate (0, -(2 * image.Height) + 1);
cr.Transform (matrix);
cr.SetSource (image);
cr.Paint ();
cr.Restore ();
Color bg_transparent = BackgroundColor;
bg_transparent.A = 0.65;
LinearGradient mask = new LinearGradient (0, image.Height, 0, image.Height + reflect);
mask.AddColorStop (0, bg_transparent);
mask.AddColorStop (1, BackgroundColor);
cr.Rectangle (0, image.Height, image.Width, reflect);
cr.Pattern = mask;
cr.Fill ();
((IDisposable)cr).Dispose ();
return surface;
}
protected override void RenderTrackInfo (Context cr, TrackInfo track, bool render_track, bool render_artist_album)
{
if (track == null) {
return;
}
Gdk.Rectangle alloc = RenderAllocation;
int width = ArtworkSizeRequest;
int fl_width, fl_height, sl_width, sl_height, tl_width, tl_height;
int pango_width = (int)(width * Pango.Scale.PangoScale);
string first_line = GetFirstLineText (track);
// FIXME: This is incredibly bad, but we don't want to break
// translations right now. It needs to be replaced for 1.4!!
string line = GetSecondLineText (track);
string second_line = line, third_line = String.Empty;
int split_pos = line.LastIndexOf ("<span");
if (split_pos >= 0
// Check that there are at least 3 spans in the string, else this
// will break for tracks with missing artist or album info.
&& StringUtil.SubstringCount (line, "<span") >= 3) {
second_line = line.Substring (0, Math.Max (0, split_pos - 1)) + "</span>";
third_line = String.Format ("<span color=\"{0}\">{1}",
CairoExtensions.ColorGetHex (TextColor, false),
line.Substring (split_pos, line.Length - split_pos));
}
if (first_line_layout == null) {
first_line_layout = CairoExtensions.CreateLayout (this, cr);
first_line_layout.Wrap = Pango.WrapMode.Word;
first_line_layout.Ellipsize = Pango.EllipsizeMode.None;
first_line_layout.Alignment = Pango.Alignment.Right;
int base_size = first_line_layout.FontDescription.Size;
first_line_layout.FontDescription.Size = (int)(base_size * Pango.Scale.XLarge);
}
if (second_line_layout == null) {
second_line_layout = CairoExtensions.CreateLayout (this, cr);
second_line_layout.Wrap = Pango.WrapMode.Word;
second_line_layout.Ellipsize = Pango.EllipsizeMode.None;
second_line_layout.Alignment = Pango.Alignment.Right;
}
if (third_line_layout == null) {
third_line_layout = CairoExtensions.CreateLayout (this, cr);
third_line_layout.Wrap = Pango.WrapMode.Word;
third_line_layout.Ellipsize = Pango.EllipsizeMode.None;
third_line_layout.Alignment = Pango.Alignment.Right;
}
// Set up the text layouts
first_line_layout.Width = pango_width;
second_line_layout.Width = pango_width;
third_line_layout.Width = pango_width;
// Compute the layout coordinates
first_line_layout.SetMarkup (first_line);
first_line_layout.GetPixelSize (out fl_width, out fl_height);
second_line_layout.SetMarkup (second_line);
second_line_layout.GetPixelSize (out sl_width, out sl_height);
third_line_layout.SetMarkup (third_line);
third_line_layout.GetPixelSize (out tl_width, out tl_height);
track_info_alloc.X = alloc.X;
track_info_alloc.Width = width;
track_info_alloc.Height = fl_height + sl_height + tl_height;
track_info_alloc.Y = alloc.Y + (ArtworkSizeRequest - track_info_alloc.Height) / 2;
// Render the layouts
cr.Antialias = Cairo.Antialias.Default;
if (render_track) {
cr.MoveTo (track_info_alloc.X, track_info_alloc.Y);
cr.Color = TextColor;
PangoCairoHelper.ShowLayout (cr, first_line_layout);
RenderTrackRating (cr, track);
}
if (render_artist_album) {
cr.MoveTo (track_info_alloc.X, track_info_alloc.Y + fl_height);
PangoCairoHelper.ShowLayout (cr, second_line_layout);
cr.MoveTo (track_info_alloc.X, track_info_alloc.Y + fl_height + sl_height);
PangoCairoHelper.ShowLayout (cr, third_line_layout);
}
}
private void RenderTrackRating (Cairo.Context cr, TrackInfo track)
{
RatingRenderer rating_renderer = new RatingRenderer ();
rating_renderer.Value = track.Rating;
int x = track_info_alloc.X + track_info_alloc.Width + 4 * rating_renderer.Xpad - rating_renderer.Width;
int y = track_info_alloc.Y + track_info_alloc.Height;
track_info_alloc.Height += rating_renderer.Height;
Gdk.Rectangle area = new Gdk.Rectangle (x, y, rating_renderer.Width, rating_renderer.Height);
rating_renderer.Render (cr, area, TextColor, false, false, rating_renderer.Value, 0.8, 0.8, 0.35);
}
protected override void Invalidate ()
{
if (CurrentImage == null || CurrentTrack == null || IncomingImage == null || IncomingTrack == null) {
QueueDraw ();
} else {
Gdk.Rectangle alloc = RenderAllocation;
QueueDrawArea (track_info_alloc.X, track_info_alloc.Y, track_info_alloc.Width, track_info_alloc.Height);
QueueDrawArea (alloc.X + track_info_alloc.Width + Spacing, alloc.Y,
alloc.Width - track_info_alloc.Width - Spacing, alloc.Height);
}
}
protected override void InvalidateCache ()
{
foreach (Surface surface in surfaces.Values) {
((IDisposable)surface).Dispose ();
}
surfaces.Clear ();
}
}
}
| |
using System;
using MonoBrickFirmware.Extensions;
namespace MonoBrickFirmware.Sensors
{
/// <summary>
/// Sensor mode when using a EV3 IR Sensor
/// </summary>
public enum IRMode {
/// <summary>
/// Use the IR sensor as a distance sensor
/// </summary>
Proximity = UARTMode.Mode0,
/// <summary>
/// Use the IR sensor to detect the location of the IR Remote
/// </summary>
Seek = UARTMode.Mode1,
/// <summary>
/// Use the IR sensor to detect wich Buttons where pressed on the IR Remote
/// </summary>
Remote = UARTMode.Mode2,
};
/// <summary>
/// IR channels
/// </summary>
public enum IRChannel{
#pragma warning disable
One = 0, Two = 1, Three = 2, Four = 3
#pragma warning restore
};
/// <summary>
/// Class for IR beacon location.
/// </summary>
public class BeaconLocation{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrickFirmware.Sensors.BeaconLocation"/> class.
/// </summary>
/// <param name="location">Location.</param>
/// <param name="distance">Distance.</param>
public BeaconLocation(sbyte location, sbyte distance){this.Location = location; this.Distance = distance;}
/// <summary>
/// Gets the location of the beacon ranging from minus to plus increasing clockwise when pointing towards the beacon
/// </summary>
/// <value>The location of the beacon.</value>
public sbyte Location{get;private set;}
/// <summary>
/// Gets the distance of the beacon in CM (0-100)
/// </summary>
/// <value>The distance to the beacon.</value>
public sbyte Distance{get; private set;}
}
/// <summary>
/// Class for the EV3 IR sensor
/// </summary>
public class EV3IRSensor : UartSensor{
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrickFirmware.Sensors.EV3IRSensor"/> class.
/// </summary>
/// <param name="port">Port.</param>
public EV3IRSensor (SensorPort port) : this(port, IRMode.Proximity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MonoBrickFirmware.Sensors.EV3IRSensor"/> class.
/// </summary>
/// <param name="port">Senosr port.</param>
/// <param name="mode">IR Mode.</param>
public EV3IRSensor (SensorPort port, IRMode mode) : base(port)
{
base.Initialise(base.uartMode);
Mode = mode;
Channel = IRChannel.One;
}
/// <summary>
/// Gets or sets the IR mode.
/// </summary>
/// <value>The mode.</value>
public IRMode Mode {
get{return (IRMode) base.uartMode;}
set{SetMode((UARTMode) value);}
}
/// <summary>
/// Reads the sensor value as a string.
/// </summary>
/// <returns>The value as a string</returns>
public override string ReadAsString ()
{
string s = "";
switch ((IRMode)base.uartMode)
{
case IRMode.Proximity:
s = ReadDistance() + " cm";
break;
case IRMode.Remote:
s = ReadRemoteCommand() + " on channel " + Channel;
break;
case IRMode.Seek:
BeaconLocation location = ReadBeaconLocation();
s = "Location: " + location.Location + " Distance: " + location.Distance + " cm";
break;
}
return s;
}
/// <summary>
/// Read the sensor value. The returned value depends on the mode. Distance in proximity mode.
/// Remote command number in remote mode. Beacon location in seek mode.
/// </summary>
public int Read(){
int value = 0;
switch ((IRMode)base.uartMode)
{
case IRMode.Proximity:
value = ReadDistance();
break;
case IRMode.Remote:
value = (int)ReadRemoteCommand();
break;
case IRMode.Seek:
value = (int)ReadBeaconLocation().Location;
break;
}
return value;
}
/// <summary>
/// Read the distance of the sensor in CM (0-100). This will change mode to proximity
/// </summary>
public int ReadDistance()
{
if (Mode != IRMode.Proximity) {
Mode = IRMode.Proximity;
}
return ReadByte();
}
/// <summary>
/// Reads commands from the IR-Remote. This will change mode to remote
/// </summary>
/// <returns>The remote command.</returns>
public byte ReadRemoteCommand ()
{
if (Mode != IRMode.Remote) {
Mode = IRMode.Remote;
}
return ReadBytes (4) [(int)Channel];
}
/// <summary>
/// Gets the beacon location. This will change the mode to seek
/// </summary>
/// <returns>The beacon location.</returns>
public BeaconLocation ReadBeaconLocation(){
if (Mode != IRMode.Seek) {
Mode = IRMode.Seek;
}
byte[] data = ReadBytes(4*2);
return new BeaconLocation((sbyte)data[(int)Channel*2], (sbyte)data[((int)Channel*2)+1]);
}
/// <summary>
/// Gets or sets the IR channel used for reading remote commands or beacon location
/// </summary>
/// <value>The channel.</value>
public IRChannel Channel{get;set;}
public override string GetSensorName ()
{
return "EV3 IR";
}
public override void SelectNextMode()
{
Mode = Mode.Next();
return;
}
public override void SelectPreviousMode ()
{
Mode = Mode.Previous();
return;
}
public override int NumberOfModes ()
{
return Enum.GetNames(typeof(IRMode)).Length;
}
public override string SelectedMode ()
{
return Mode.ToString();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_DWSS
{
using System;
using System.Net;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Provides test methods for validating the operation: RemoveDwsUser.
/// </summary>
[TestClass]
public class S05_ManageSiteUsers : TestClassBase
{
#region Variables
/// <summary>
/// Adapter Instance.
/// </summary>
private IMS_DWSSAdapter dwsAdapter;
#endregion Variables
#region Test Suite Initialization
/// <summary>
/// Use ClassInitialize to run code before running the first test in the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Use ClassCleanup to run code after all tests in a class have run.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion Test Suite Initialization
#region Test Cases
#region Test RemoveDwsUser Operation
/// <summary>
/// This test case is intended to validate that the RemoveDwsUser operation removes the specified user from the list of users for the current Document Workspace site successfully.
/// </summary>
[TestCategory("MSDWSS"), TestMethod()]
public void MSDWSS_S05_TC01_RemoveDwsUser_RemoveUserSuccessfully()
{
this.dwsAdapter.ServiceUrl = Common.GetConfigurationPropertyValue("TestDWSSWebSite", this.Site);
Error error;
UsersItem users = new UsersItem();
DocumentsItem documents = new DocumentsItem();
users.Name = Common.GetConfigurationPropertyValue("UserName", this.Site);
users.Email = Common.GetConfigurationPropertyValue("RegisteredUsersEmail", this.Site);
documents.ID = Guid.NewGuid().ToString();
documents.Name = Common.GetConfigurationPropertyValue("DocumentsName", this.Site) + "_" + Common.FormatCurrentDateTime();
CreateDwsResultResults createDwsRespResults = this.dwsAdapter.CreateDws(string.Empty, users, string.Empty, documents, out error);
// Redirect the web service to the newly created site.
this.dwsAdapter.ServiceUrl = createDwsRespResults.Url + Common.GetConfigurationPropertyValue("TestDWSSSuffix", this.Site);
// Get first member of the current site.
Results getDwsDataRespResults = this.dwsAdapter.GetDwsData(documents.Name, string.Empty, out error);
this.Site.Assert.IsNull(error, "The response is expected to be a GetDwsDataResult not an error");
this.Site.Assert.IsNotNull(getDwsDataRespResults.Members.Items, "The server should return a member element.");
this.Site.Assert.IsTrue(getDwsDataRespResults.Members.Items.Length > 0, "The site members should be more than one.");
Member firstMember = getDwsDataRespResults.Members.Items[0] as Member;
this.Site.Assert.IsNotNull(firstMember, "The user should exist on server.");
// Remove the first member.
this.dwsAdapter.RemoveDwsUser(int.Parse(firstMember.ID), out error);
this.Site.Assert.IsNull(error, "The response is expected to be a Result element not an error");
this.dwsAdapter.DeleteDws(out error);
this.Site.Assert.IsNull(error, "The response should not be an error!");
}
/// <summary>
/// This test case is intended to validate the related requirements when the server returns a ServerFailure Error element during processing RemoveDwsUser operation.
/// </summary>
[TestCategory("MSDWSS"), TestMethod()]
public void MSDWSS_S05_TC02_RemoveDwsUser_ServerFailure()
{
this.dwsAdapter.ServiceUrl = Common.GetConfigurationPropertyValue("TestDWSSWebSite", this.Site);
Error error;
UsersItem users = new UsersItem();
DocumentsItem documents = new DocumentsItem();
users.Name = Common.GetConfigurationPropertyValue("UserName", this.Site);
users.Email = Common.GetConfigurationPropertyValue("RegisteredUsersEmail", this.Site);
documents.ID = Guid.NewGuid().ToString();
documents.Name = Common.GetConfigurationPropertyValue("DocumentsName", this.Site) + "_" + Common.FormatCurrentDateTime();
CreateDwsResultResults createDwsRespResults = this.dwsAdapter.CreateDws(string.Empty, users, string.Empty, documents, out error);
// Redirect the web service to the newly created site.
this.dwsAdapter.ServiceUrl = createDwsRespResults.Url + Common.GetConfigurationPropertyValue("TestDWSSSuffix", this.Site);
int invalidUserId = -1;
this.dwsAdapter.RemoveDwsUser(invalidUserId, out error);
this.Site.Assert.IsNotNull(error, "The expected response is an error.");
// If the error is not null, it indicates that the server returned an Error element as is specified.
this.Site.CaptureRequirement(
289,
@"[In RemoveDwsUserResponse] Error: An Error element as specified in section 2.2.3.2.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-DWSS_R286");
// Verify MS-DWSS requirement: MS-DWSS_R286
this.Site.CaptureRequirementIfAreEqual<ErrorTypes>(
ErrorTypes.ServerFailure,
error.Value,
286,
@"[In RemoveDwsUser] If an error of any type occurs during the processing, the protocol server MUST return an Error element as specified in section 2.2.3.2 with an error code of ServerFailure.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-DWSS_R20");
// Verify MS-DWSS requirement: MS-DWSS_R20
this.Site.CaptureRequirementIfAreEqual<string>(
"1",
error.ID,
20,
@"[In Error] The value 1 [ID] matches the Error type ServerFailure.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-DWSS_R312");
// Verify MS-DWSS requirement: MS-DWSS_R312
this.Site.CaptureRequirementIfIsTrue(
string.IsNullOrEmpty(error.AccessUrl),
312,
@"[In Error] This attribute [AccessUrl] MUST NOT be present when the Error element contains ServerFailure error code.");
this.dwsAdapter.DeleteDws(out error);
this.Site.Assert.IsNull(error, "The response should not be an error!");
}
/// <summary>
/// This test case is intended to validate that an Error element with NoAccess code should be returned by RemoveDwsUser operation if the user does not have sufficient access permissions to remove the user.
/// </summary>
[TestCategory("MSDWSS"), TestMethod()]
public void MSDWSS_S05_TC03_RemoveDwsUser_NoAccess()
{
this.dwsAdapter.ServiceUrl = Common.GetConfigurationPropertyValue("TestDWSSWebSite", this.Site);
Error error;
UsersItem users = new UsersItem();
DocumentsItem documents = new DocumentsItem();
users.Name = Common.GetConfigurationPropertyValue("UserName", this.Site);
users.Email = Common.GetConfigurationPropertyValue("RegisteredUsersEmail", this.Site);
documents.ID = Guid.NewGuid().ToString();
documents.Name = Common.GetConfigurationPropertyValue("DocumentsName", this.Site) + "_" + Common.FormatCurrentDateTime();
CreateDwsResultResults createDwsRespResults = this.dwsAdapter.CreateDws(string.Empty, users, string.Empty, documents, out error);
// Redirect the web service to the newly created site.
this.dwsAdapter.ServiceUrl = createDwsRespResults.Url + Common.GetConfigurationPropertyValue("TestDWSSSuffix", this.Site);
Results getDwsDataRespResults = this.dwsAdapter.GetDwsData(documents.Name, string.Empty, out error);
this.Site.Assert.IsNull(error, "The response is expected to be a GetDwsDataResult not an error");
this.Site.Assert.IsNotNull(getDwsDataRespResults.Members.Items, "The members not expected to be null");
// Get first member
Member firstMember = getDwsDataRespResults.Members.Items[0] as Member;
this.Site.Assert.IsNotNull(firstMember, "The user should exist on server.");
// Set Dws service credential to Reader credential.
string userName = Common.GetConfigurationPropertyValue("ReaderRoleUser", this.Site);
string password = Common.GetConfigurationPropertyValue("ReaderRoleUserPassword", this.Site);
string domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
this.dwsAdapter.Credentials = new NetworkCredential(userName, password, domain);
this.dwsAdapter.RemoveDwsUser(int.Parse(firstMember.ID), out error);
this.Site.Assert.IsNotNull(error, "The response is expected to be a NoAccess error.");
// Add the debug information
this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-DWSS_R22");
// Verify MS-DWSS requirement: MS-DWSS_R22
bool isVerifiedR22 = string.Equals("3", error.ID, StringComparison.CurrentCultureIgnoreCase) &&
error.Value == ErrorTypes.NoAccess;
this.Site.CaptureRequirementIfIsTrue(
isVerifiedR22,
22,
@"[In Error] The value 3 [ID] matches the Error type NoAccess.");
// Set default Dws service credential to admin credential.
userName = Common.GetConfigurationPropertyValue("UserName", this.Site);
password = Common.GetConfigurationPropertyValue("Password", this.Site);
domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
this.dwsAdapter.Credentials = new NetworkCredential(userName, password, domain);
this.dwsAdapter.DeleteDws(out error);
this.Site.Assert.IsNull(error, "The response should not be an error!");
}
#endregion
#endregion Test Cases
#region Test Case Initialization
/// <summary>
/// Initialize Test case and test environment
/// </summary>
[TestInitialize]
public void TestCaseInitialize()
{
this.dwsAdapter = Site.GetAdapter<IMS_DWSSAdapter>();
Common.CheckCommonProperties(this.Site, true);
// Set default Dws service credential to admin credential.
string userName = Common.GetConfigurationPropertyValue("UserName", this.Site);
string password = Common.GetConfigurationPropertyValue("Password", this.Site);
string domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
this.dwsAdapter.Credentials = new NetworkCredential(userName, password, domain);
}
/// <summary>
/// Clean up test environment.
/// </summary>
[TestCleanup]
public void TestCaseCleanup()
{
this.dwsAdapter.Reset();
}
#endregion Test Case Initialization
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Impl.Auth.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Impl.Auth
{
/// <summary>
/// <para>Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/RFC2617Scheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/RFC2617Scheme", AccessFlags = 1057)]
public abstract partial class RFC2617Scheme : global::Org.Apache.Http.Impl.Auth.AuthSchemeBase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for RFC2617 compliant authetication schemes. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RFC2617Scheme() /* MethodBuilder.Create */
{
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 4)]
protected internal override void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns authentication parameters map. Keys in the map are lower-cased.</para><para></para>
/// </summary>
/// <returns>
/// <para>the map of authentication parameters </para>
/// </returns>
/// <java-name>
/// getParameters
/// </java-name>
[Dot42.DexImport("getParameters", "()Ljava/util/Map;", AccessFlags = 4, Signature = "()Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;")]
protected internal virtual global::Java.Util.IMap<string, string> GetParameters() /* MethodBuilder.Create */
{
return default(global::Java.Util.IMap<string, string>);
}
/// <summary>
/// <para>Returns authentication parameter with the given name, if available.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameter with the given name </para>
/// </returns>
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)]
public override string GetParameter(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication realm. The realm may not be null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetRealm() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication parameters map. Keys in the map are lower-cased.</para><para></para>
/// </summary>
/// <returns>
/// <para>the map of authentication parameters </para>
/// </returns>
/// <java-name>
/// getParameters
/// </java-name>
protected internal global::Java.Util.IMap<string, string> Parameters
{
[Dot42.DexImport("getParameters", "()Ljava/util/Map;", AccessFlags = 4, Signature = "()Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;")]
get{ return GetParameters(); }
}
/// <summary>
/// <para>Returns authentication realm. The realm may not be null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
public string Realm
{
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetRealm(); }
}
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/DigestSchemeFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/DigestSchemeFactory", AccessFlags = 33)]
public partial class DigestSchemeFactory : global::Org.Apache.Http.Auth.IAuthSchemeFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DigestSchemeFactory() /* MethodBuilder.Create */
{
}
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Auth.IAuthScheme NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Auth.IAuthScheme);
}
}
/// <java-name>
/// org/apache/http/impl/auth/NTLMScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMScheme", AccessFlags = 33)]
public partial class NTLMScheme : global::Org.Apache.Http.Impl.Auth.AuthSchemeBase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/impl/auth/NTLMEngine;)V", AccessFlags = 1)]
public NTLMScheme(global::Org.Apache.Http.Impl.Auth.INTLMEngine engine) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns textual designation of the given authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the given authentication scheme </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)]
public override string GetParameter(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication realm. If the concept of an authentication realm is not applicable to the given authentication scheme, returns <code>null</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetRealm() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Tests if the authentication scheme is provides authorization on a per connection basis instead of usual per request basis</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the scheme is connection based, <code>false</code> if the scheme is request based. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 4)]
protected internal override void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Authentication process may involve a series of challenge-response exchanges. This method tests if the authorization process has been completed, either successfully or unsuccessfully, that is, all the required authorization challenges have been processed in their entirety.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the authentication process has been completed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal NTLMScheme() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns textual designation of the given authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the given authentication scheme </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
/// <summary>
/// <para>Returns authentication realm. If the concept of an authentication realm is not applicable to the given authentication scheme, returns <code>null</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
public string Realm
{
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetRealm(); }
}
}
/// <summary>
/// <para>Basic authentication scheme as defined in RFC 2617. </para><para><para> </para><simplesectsep></simplesectsep><para>Rodney Waldhoff </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para>Ortwin Glueck </para><simplesectsep></simplesectsep><para>Sean C. Sullivan </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/BasicScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/BasicScheme", AccessFlags = 33)]
public partial class BasicScheme : global::Org.Apache.Http.Impl.Auth.RFC2617Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for the basic authetication scheme. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicScheme() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns textual designation of the basic authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>basic</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Processes the Basic challenge.</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public override void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the Basic authentication process has been completed.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if Basic authorization has been processed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns <code>false</code>. Basic authentication scheme is request based.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code>. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Produces basic authorization header for the given set of Credentials.</para><para></para>
/// </summary>
/// <returns>
/// <para>a basic authorization string </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Returns a basic <code>Authorization</code> header value for the given Credentials and charset.</para><para></para>
/// </summary>
/// <returns>
/// <para>a basic authorization header </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Ljava/lang/String;Z)Lorg/apache/http/Header;", AccessFlags = 9)]
public static global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, string charset, bool proxy) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Returns textual designation of the basic authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>basic</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
}
/// <summary>
/// <para>Authentication credentials required to respond to a authentication challenge are invalid</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/UnsupportedDigestAlgorithmException
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/UnsupportedDigestAlgorithmException", AccessFlags = 33)]
public partial class UnsupportedDigestAlgorithmException : global::System.SystemException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Digest authentication scheme as defined in RFC 2617. Both MD5 (default) and MD5-sess are supported. Currently only qop=auth or no qop is supported. qop=auth-int is unsupported. If auth and auth-int are provided, auth is used. </para><para>Credential charset is configured via the credential charset parameter. Since the digest username is included as clear text in the generated Authentication header, the charset of the username must be compatible with the http element charset. </para><para><para> </para><simplesectsep></simplesectsep><para>Rodney Waldhoff </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para>Ortwin Glueck </para><simplesectsep></simplesectsep><para>Sean C. Sullivan </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/DigestScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/DigestScheme", AccessFlags = 33)]
public partial class DigestScheme : global::Org.Apache.Http.Impl.Auth.RFC2617Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for the digest authetication scheme. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DigestScheme() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Processes the Digest challenge.</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public override void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the Digest authentication process has been completed.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if Digest authorization has been processed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns textual designation of the digest authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>digest</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns <code>false</code>. Digest authentication scheme is request based.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code>. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// overrideParamter
/// </java-name>
[Dot42.DexImport("overrideParamter", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void OverrideParamter(string name, string value) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Produces a digest authorization string for the given set of Credentials, method name and URI.</para><para></para>
/// </summary>
/// <returns>
/// <para>a digest authorization string </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Creates a random cnonce value based on the current time.</para><para></para>
/// </summary>
/// <returns>
/// <para>The cnonce value as String. </para>
/// </returns>
/// <java-name>
/// createCnonce
/// </java-name>
[Dot42.DexImport("createCnonce", "()Ljava/lang/String;", AccessFlags = 9)]
public static string CreateCnonce() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns textual designation of the digest authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>digest</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
}
/// <summary>
/// <para>Signals NTLM protocol failure.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/NTLMEngineException
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMEngineException", AccessFlags = 33)]
public partial class NTLMEngineException : global::Org.Apache.Http.Auth.AuthenticationException
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public NTLMEngineException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NTLMEngineException with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public NTLMEngineException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NTLMEngineException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public NTLMEngineException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract NTLM authentication engine. The engine can be used to generate Type1 messages and Type3 messages in response to a Type2 challenge. </para><para>For details see </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/NTLMEngine
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMEngine", AccessFlags = 1537)]
public partial interface INTLMEngine
/* scope: __dot42__ */
{
/// <summary>
/// <para>Generates a Type1 message given the domain and workstation.</para><para></para>
/// </summary>
/// <returns>
/// <para>Type1 message </para>
/// </returns>
/// <java-name>
/// generateType1Msg
/// </java-name>
[Dot42.DexImport("generateType1Msg", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GenerateType1Msg(string domain, string workstation) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Generates a Type3 message given the user credentials and the authentication challenge.</para><para></para>
/// </summary>
/// <returns>
/// <para>Type3 response. </para>
/// </returns>
/// <java-name>
/// generateType3Msg
/// </java-name>
[Dot42.DexImport("generateType3Msg", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/la" +
"ng/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GenerateType3Msg(string username, string password, string domain, string workstation, string challenge) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/BasicSchemeFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/BasicSchemeFactory", AccessFlags = 33)]
public partial class BasicSchemeFactory : global::Org.Apache.Http.Auth.IAuthSchemeFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicSchemeFactory() /* MethodBuilder.Create */
{
}
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Auth.IAuthScheme NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Auth.IAuthScheme);
}
}
/// <summary>
/// <para>Abstract authentication scheme class that serves as a basis for all authentication schemes supported by HttpClient. This class defines the generic way of parsing an authentication challenge. It does not make any assumptions regarding the format of the challenge nor does it impose any specific way of responding to that challenge.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/AuthSchemeBase
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/AuthSchemeBase", AccessFlags = 1057)]
public abstract partial class AuthSchemeBase : global::Org.Apache.Http.Auth.IAuthScheme
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AuthSchemeBase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Processes the given challenge token. Some authentication schemes may involve multiple challenge-response exchanges. Such schemes must be able to maintain the state information when dealing with sequential challenges</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public virtual void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1028)]
protected internal abstract void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <code>true</code> if authenticating against a proxy, <code>false</code> otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if authenticating against a proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isProxy
/// </java-name>
[Dot42.DexImport("isProxy", "()Z", AccessFlags = 1)]
public virtual bool IsProxy() /* MethodBuilder.Create */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getSchemeName", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetSchemeName() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getRealm", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetRealm() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "isConnectionBased", "()Z", AccessFlags = 1025)]
public virtual bool IsConnectionBased() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "isComplete", "()Z", AccessFlags = 1025)]
public virtual bool IsComplete() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1025)]
public virtual global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
public string SchemeName
{
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getSchemeName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSchemeName(); }
}
public string Realm
{
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getRealm", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetRealm(); }
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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.Diagnostics;
using System.Reflection;
using System.Security.Permissions;
using Gallio.Common.Platform;
namespace Gallio.Common.Diagnostics
{
/// <summary>
/// Provides helper functions for manipulating <see cref="Exception" />s.
/// </summary>
public static class ExceptionUtils
{
/// <summary>
/// Safely converts an exception to a string.
/// </summary>
/// <remarks>
/// <para>
/// This method protects the caller from unexpected failures that may occur while
/// reporting an exception of untrusted origin. If an error occurs while converting the
/// exception to a string, this method returns a generic description of the exception
/// that can be used instead of the real thing.
/// </para>
/// <para>
/// It can happen that converting an exception to a string produces a secondary exception
/// because the <see cref="Exception.ToString" /> method has been overridden or because the
/// stack frames associated with the exception are malformed. For example, we observed
/// one case of a <see cref="TypeLoadException" /> being thrown while printing an exception
/// because one of the stack frames referred to a dynamic method with incorrect metadata.
/// </para>
/// </remarks>
/// <param name="ex">The exception.</param>
/// <returns>The string contents.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="ex"/> is null.</exception>
/// <seealso cref="Exception.ToString"/>
public static string SafeToString(Exception ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
try
{
return ex.ToString();
}
catch (Exception ex2)
{
return String.Format("An exception of type '{0}' occurred. Details are not available because a second exception of type '{1}' occurred in Exception.ToString().",
ex.GetType().FullName, ex2.GetType().FullName);
}
}
/// <summary>
/// Safely obtains the <see cref="Exception.Message"/> component of an exception.
/// </summary>
/// <returns>The message.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="ex"/> is null.</exception>
/// <seealso cref="SafeToString"/>
public static string SafeGetMessage(Exception ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
try
{
return ex.Message ?? "";
}
catch (Exception ex2)
{
return String.Format("An exception of type '{0}' occurred. Details are not available because a second exception of type '{1}' occurred in Exception.ToString().",
ex.GetType().FullName, ex2.GetType().FullName);
}
}
/// <summary>
/// Safely obtains the <see cref="Exception.StackTrace"/> component of an exception.
/// </summary>
/// <returns>The stack trace.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="ex"/> is null.</exception>
/// <seealso cref="SafeToString"/>
public static string SafeGetStackTrace(Exception ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
try
{
return ex.StackTrace ?? "";
}
catch
{
return "";
}
}
/// <summary>
/// Rethrows an exception without discarding its stack trace.
/// This enables the inner exception of <see cref="TargetInvocationException" />
/// to be unwrapped.
/// </summary>
/// <remarks>
/// <remarks>
/// This implementation is based on code by <a href="http://bradwilson.typepad.com/">Brad Wilson</a>.
/// </remarks>
/// </remarks>
/// <param name="ex">The exception to rethrow.</param>
[DebuggerStepThrough, DebuggerHidden]
[ReflectionPermission(SecurityAction.Assert, MemberAccess=true)]
public static void RethrowWithNoStackTraceLoss(Exception ex)
{
if (ex == null)
throw new ArgumentNullException("ex");
// Hack the stack trace so it appears to have been preserved.
// If we can't hack the stack trace, then there's not much we can do as anything we
// choose will alter the semantics of test execution.
if (DotNetRuntimeSupport.IsUsingMono)
{
MethodInfo method = typeof(Exception).GetMethod("FixRemotingException", BindingFlags.Instance | BindingFlags.NonPublic);
ex = (Exception) method.Invoke(ex, null);
}
else
{
MethodInfo method = typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(ex, null);
}
throw ex;
}
/// <summary>
/// Invokes a method without producing a <see cref="TargetInvocationException" />
/// </summary>
/// <param name="method">The method to invoke.</param>
/// <param name="obj">The instance on which to invoke the method, or null if none.</param>
/// <param name="args">The method arguments, or null if none.</param>
/// <returns>The method return value, or null if none.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="method"/> is null.</exception>
[DebuggerStepThrough, DebuggerHidden]
public static object InvokeMethodWithoutTargetInvocationException(MethodBase method, object obj, object[] args)
{
if (method == null)
throw new ArgumentNullException("method");
try
{
return method.Invoke(obj, args);
}
catch (TargetInvocationException ex)
{
RethrowWithNoStackTraceLoss(ex.InnerException);
throw;
}
}
/// <summary>
/// Invokes a constructor without producing a <see cref="TargetInvocationException" />
/// </summary>
/// <param name="constructor">The constructor to invoke.</param>
/// <param name="args">The constructor arguments, or null if none.</param>
/// <returns>The new instance, or null if none.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="constructor"/> is null.</exception>
[DebuggerStepThrough, DebuggerHidden]
public static object InvokeConstructorWithoutTargetInvocationException(ConstructorInfo constructor, object[] args)
{
if (constructor == null)
throw new ArgumentNullException("constructor");
try
{
return constructor.Invoke(args);
}
catch (TargetInvocationException ex)
{
RethrowWithNoStackTraceLoss(ex.InnerException);
throw;
}
}
/// <summary>
/// Creates an object using <see cref="Activator.CreateInstance(Type)"/> without producing a <see cref="TargetInvocationException" />
/// </summary>
/// <param name="type">The type of object to create.</param>
/// <param name="args">The constructor arguments, or null if none.</param>
/// <returns>The new instance, or null if none.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="type"/> is null.</exception>
[DebuggerStepThrough, DebuggerHidden]
public static object CreateInstanceWithoutTargetInvocationException(Type type, object[] args)
{
if (type == null)
throw new ArgumentNullException("type");
try
{
return args != null
? Activator.CreateInstance(type, args)
: Activator.CreateInstance(type);
}
catch (TargetInvocationException ex)
{
RethrowWithNoStackTraceLoss(ex.InnerException);
throw;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace System.IO.Tests
{
public partial class StringWriterTests : RemoteExecutorTestBase
{
static int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue };
static int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
static int[] iArrValidValues = new int[] { 10000, 100000, int.MaxValue / 2000, int.MaxValue / 5000, short.MaxValue };
private static StringBuilder getSb()
{
var chArr = TestDataProvider.CharData;
var sb = new StringBuilder(40);
for (int i = 0; i < chArr.Length; i++)
sb.Append(chArr[i]);
return sb;
}
[Fact]
public static void Ctor()
{
StringWriter sw = new StringWriter();
Assert.NotNull(sw);
}
[Fact]
public static void CtorWithStringBuilder()
{
var sb = getSb();
StringWriter sw = new StringWriter(getSb());
Assert.NotNull(sw);
Assert.Equal(sb.Length, sw.GetStringBuilder().Length);
}
[Fact]
public static void CtorWithCultureInfo()
{
StringWriter sw = new StringWriter(new CultureInfo("en-gb"));
Assert.NotNull(sw);
Assert.Equal(new CultureInfo("en-gb"), sw.FormatProvider);
}
[Fact]
public static void SimpleWriter()
{
var sw = new StringWriter();
sw.Write(4);
var sb = sw.GetStringBuilder();
Assert.Equal("4", sb.ToString());
}
[Fact]
public static void WriteArray()
{
var chArr = TestDataProvider.CharData;
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
var sr = new StringReader(sw.GetStringBuilder().ToString());
for (int i = 0; i < chArr.Length; i++)
{
int tmp = sr.Read();
Assert.Equal((int)chArr[i], tmp);
}
}
[Fact]
public static void CantWriteNullArray()
{
var sw = new StringWriter();
Assert.Throws<ArgumentNullException>(() => sw.Write(null, 0, 0));
}
[Fact]
public static void CantWriteNegativeOffset()
{
var sw = new StringWriter();
Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], -1, 0));
}
[Fact]
public static void CantWriteNegativeCount()
{
var sw = new StringWriter();
Assert.Throws<ArgumentOutOfRangeException>(() => sw.Write(new char[0], 0, -1));
}
[Fact]
public static void CantWriteIndexLargeValues()
{
var chArr = TestDataProvider.CharData;
for (int i = 0; i < iArrLargeValues.Length; i++)
{
StringWriter sw = new StringWriter();
AssertExtensions.Throws<ArgumentException>(null, () => sw.Write(chArr, iArrLargeValues[i], chArr.Length));
}
}
[Fact]
public static void CantWriteCountLargeValues()
{
var chArr = TestDataProvider.CharData;
for (int i = 0; i < iArrLargeValues.Length; i++)
{
StringWriter sw = new StringWriter();
AssertExtensions.Throws<ArgumentException>(null, () => sw.Write(chArr, 0, iArrLargeValues[i]));
}
}
[Fact]
public static void WriteWithOffset()
{
StringWriter sw = new StringWriter();
StringReader sr;
var chArr = TestDataProvider.CharData;
sw.Write(chArr, 2, 5);
sr = new StringReader(sw.ToString());
for (int i = 2; i < 7; i++)
{
int tmp = sr.Read();
Assert.Equal((int)chArr[i], tmp);
}
}
[Fact]
public static void WriteWithLargeIndex()
{
for (int i = 0; i < iArrValidValues.Length; i++)
{
StringBuilder sb = new StringBuilder(int.MaxValue / 2000);
StringWriter sw = new StringWriter(sb);
var chArr = new char[int.MaxValue / 2000];
for (int j = 0; j < chArr.Length; j++)
chArr[j] = (char)(j % 256);
sw.Write(chArr, iArrValidValues[i] - 1, 1);
string strTemp = sw.GetStringBuilder().ToString();
Assert.Equal(1, strTemp.Length);
}
}
[Fact]
public static void WriteWithLargeCount()
{
for (int i = 0; i < iArrValidValues.Length; i++)
{
StringBuilder sb = new StringBuilder(int.MaxValue / 2000);
StringWriter sw = new StringWriter(sb);
var chArr = new char[int.MaxValue / 2000];
for (int j = 0; j < chArr.Length; j++)
chArr[j] = (char)(j % 256);
sw.Write(chArr, 0, iArrValidValues[i]);
string strTemp = sw.GetStringBuilder().ToString();
Assert.Equal(iArrValidValues[i], strTemp.Length);
}
}
[Fact]
public static void NewStringWriterIsEmpty()
{
var sw = new StringWriter();
Assert.Equal(string.Empty, sw.ToString());
}
[Fact]
public static void NewStringWriterHasEmptyStringBuilder()
{
var sw = new StringWriter();
Assert.Equal(string.Empty, sw.GetStringBuilder().ToString());
}
[Fact]
public static void ToStringReturnsWrittenData()
{
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
sw.Write(sb.ToString());
Assert.Equal(sb.ToString(), sw.ToString());
}
[Fact]
public static void StringBuilderHasCorrectData()
{
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
sw.Write(sb.ToString());
Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString());
}
[Fact]
public static void Closed_DisposedExceptions()
{
StringWriter sw = new StringWriter();
sw.Close();
ValidateDisposedExceptions(sw);
}
[Fact]
public static void Disposed_DisposedExceptions()
{
StringWriter sw = new StringWriter();
sw.Dispose();
ValidateDisposedExceptions(sw);
}
private static void ValidateDisposedExceptions(StringWriter sw)
{
Assert.Throws<ObjectDisposedException>(() => { sw.Write('a'); });
Assert.Throws<ObjectDisposedException>(() => { sw.Write(new char[10], 0, 1); });
Assert.Throws<ObjectDisposedException>(() => { sw.Write("abc"); });
}
[Fact]
public static async Task FlushAsyncWorks()
{
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
sw.Write(sb.ToString());
await sw.FlushAsync(); // I think this is a noop in this case
Assert.Equal(sb.ToString(), sw.GetStringBuilder().ToString());
}
[Fact]
public static void MiscWrites()
{
var sw = new StringWriter();
sw.Write('H');
sw.Write("ello World!");
Assert.Equal("Hello World!", sw.ToString());
}
[Fact]
public static async Task MiscWritesAsync()
{
var sw = new StringWriter();
await sw.WriteAsync('H');
await sw.WriteAsync(new char[] { 'e', 'l', 'l', 'o', ' ' });
await sw.WriteAsync("World!");
Assert.Equal("Hello World!", sw.ToString());
}
[Fact]
public static async Task MiscWriteLineAsync()
{
var sw = new StringWriter();
await sw.WriteLineAsync('H');
await sw.WriteLineAsync(new char[] { 'e', 'l', 'l', 'o' });
await sw.WriteLineAsync("World!");
Assert.Equal(
string.Format("H{0}ello{0}World!{0}", Environment.NewLine),
sw.ToString());
}
[Fact]
public static void GetEncoding()
{
var sw = new StringWriter();
Assert.Equal(Encoding.Unicode.WebName, sw.Encoding.WebName);
}
[Fact]
public static void TestWriteMisc()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture
var sw = new StringWriter();
sw.Write(true);
sw.Write((char)'a');
sw.Write(new decimal(1234.01));
sw.Write((double)3452342.01);
sw.Write((int)23456);
sw.Write((long)long.MinValue);
sw.Write((float)1234.50f);
sw.Write((uint)uint.MaxValue);
sw.Write((ulong)ulong.MaxValue);
Assert.Equal("Truea1234.013452342.0123456-92233720368547758081234.5429496729518446744073709551615", sw.ToString());
});
}
[Fact]
public static void TestWriteObject()
{
var sw = new StringWriter();
sw.Write(new Object());
Assert.Equal("System.Object", sw.ToString());
}
[Fact]
public static void TestWriteLineMisc()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture
var sw = new StringWriter();
sw.WriteLine((bool)false);
sw.WriteLine((char)'B');
sw.WriteLine((int)987);
sw.WriteLine((long)875634);
sw.WriteLine((float)1.23457f);
sw.WriteLine((uint)45634563);
sw.WriteLine((ulong.MaxValue));
Assert.Equal(
string.Format("False{0}B{0}987{0}875634{0}1.23457{0}45634563{0}18446744073709551615{0}", Environment.NewLine),
sw.ToString());
});
}
[Fact]
public static void TestWriteLineObject()
{
var sw = new StringWriter();
sw.WriteLine(new Object());
Assert.Equal("System.Object" + Environment.NewLine, sw.ToString());
}
[Fact]
public static void TestWriteLineAsyncCharArray()
{
StringWriter sw = new StringWriter();
sw.WriteLineAsync(new char[] { 'H', 'e', 'l', 'l', 'o' });
Assert.Equal("Hello" + Environment.NewLine, sw.ToString());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework throws NullReferenceException")]
public async Task NullNewLineAsync()
{
using (MemoryStream ms = new MemoryStream())
{
string newLine;
using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8, 16, true))
{
newLine = sw.NewLine;
await sw.WriteLineAsync(default(string));
await sw.WriteLineAsync(default(string));
}
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
Assert.Equal(newLine + newLine, await sr.ReadToEndAsync());
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void Permute2x128Int642()
{
var test = new ImmBinaryOpTest__Permute2x128Int642();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__Permute2x128Int642
{
private struct TestStruct
{
public Vector256<Int64> _fld1;
public Vector256<Int64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__Permute2x128Int642 testClass)
{
var result = Avx.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int64[] _data2 = new Int64[Op2ElementCount];
private static Vector256<Int64> _clsVar1;
private static Vector256<Int64> _clsVar2;
private Vector256<Int64> _fld1;
private Vector256<Int64> _fld2;
private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable;
static ImmBinaryOpTest__Permute2x128Int642()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
}
public ImmBinaryOpTest__Permute2x128Int642()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Permute2x128(
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Permute2x128(
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Permute2x128(
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Permute2x128(
_clsVar1,
_clsVar2,
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr);
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr));
var result = Avx.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__Permute2x128Int642();
var result = Avx.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] inArray2 = new Int64[Op2ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (i < 2 ? right[i] : left[i-2]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute2x128)}<Int64>(Vector256<Int64>.2, Vector256<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
[ExecuteInEditMode]
[RequireComponent (typeof(Camera))]
public class PostEffectsBase : MonoBehaviour
{
protected bool supportHDRTextures = true;
protected bool supportDX11 = false;
protected bool isSupported = true;
protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create)
{
if (!s)
{
Debug.Log("Missing shader in " + ToString ());
enabled = false;
return null;
}
if (s.isSupported && m2Create && m2Create.shader == s)
return m2Create;
if (!s.isSupported)
{
NotSupported ();
Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!");
return null;
}
else
{
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
protected Material CreateMaterial (Shader s, Material m2Create)
{
if (!s)
{
Debug.Log ("Missing shader in " + ToString ());
return null;
}
if (m2Create && (m2Create.shader == s) && (s.isSupported))
return m2Create;
if (!s.isSupported)
{
return null;
}
else
{
m2Create = new Material (s);
m2Create.hideFlags = HideFlags.DontSave;
if (m2Create)
return m2Create;
else return null;
}
}
void OnEnable ()
{
isSupported = true;
}
protected bool CheckSupport ()
{
return CheckSupport (false);
}
public virtual bool CheckResources ()
{
Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten.");
return isSupported;
}
protected void Start ()
{
CheckResources ();
}
protected bool CheckSupport (bool needDepth)
{
isSupported = true;
supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf);
supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders;
#if UNITY_5_5_1
if (!SystemInfo.supportsImageEffects || !SystemInfo.supportsRenderTextures)
{
NotSupported ();
return false;
}
#elif UNITY_2019
#endif
if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth))
{
NotSupported ();
return false;
}
if (needDepth)
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
return true;
}
protected bool CheckSupport (bool needDepth, bool needHdr)
{
if (!CheckSupport(needDepth))
return false;
if (needHdr && !supportHDRTextures)
{
NotSupported ();
return false;
}
return true;
}
public bool Dx11Support ()
{
return supportDX11;
}
protected void ReportAutoDisable ()
{
Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform.");
}
// deprecated but needed for old effects to survive upgrading
bool CheckShader (Shader s)
{
Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package.");
if (!s.isSupported)
{
NotSupported ();
return false;
}
else
{
return false;
}
}
protected void NotSupported ()
{
enabled = false;
isSupported = false;
return;
}
protected void DrawBorder (RenderTexture dest, Material material)
{
float x1;
float x2;
float y1;
float y2;
RenderTexture.active = dest;
bool invertY = true; // source.texelSize.y < 0.0ff;
// Set up the simple Matrix
GL.PushMatrix();
GL.LoadOrtho();
for (int i = 0; i < material.passCount; i++)
{
material.SetPass(i);
float y1_; float y2_;
if (invertY)
{
y1_ = 1.0f; y2_ = 0.0f;
}
else
{
y1_ = 0.0f; y2_ = 1.0f;
}
// left
x1 = 0.0f;
x2 = 0.0f + 1.0f/(dest.width*1.0f);
y1 = 0.0f;
y2 = 1.0f;
GL.Begin(GL.QUADS);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// right
x1 = 1.0f - 1.0f/(dest.width*1.0f);
x2 = 1.0f;
y1 = 0.0f;
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// top
x1 = 0.0f;
x2 = 1.0f;
y1 = 0.0f;
y2 = 0.0f + 1.0f/(dest.height*1.0f);
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
// bottom
x1 = 0.0f;
x2 = 1.0f;
y1 = 1.0f - 1.0f/(dest.height*1.0f);
y2 = 1.0f;
GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f);
GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f);
GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f);
GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f);
GL.End();
}
GL.PopMatrix();
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax
// .NET Compact Framework 1.0 has no support for Win32 Console API's
#if !NETCF
// .Mono 1.0 has no support for Win32 Console API's
#if !MONO
// SSCLI 1.0 has no support for Win32 Console API's
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using log4net.Layout;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to the console.
/// </summary>
/// <remarks>
/// <para>
/// ColoredConsoleAppender appends log events to the standard output stream
/// or the error output stream using a layout specified by the
/// user. It also allows the color of a specific type of message to be set.
/// </para>
/// <para>
/// By default, all output is written to the console's standard output stream.
/// The <see cref="Target"/> property can be set to direct the output to the
/// error stream.
/// </para>
/// <para>
/// NOTE: This appender writes directly to the application's attached console
/// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>.
/// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be
/// programmatically redirected (for example NUnit does this to capture program output).
/// This appender will ignore these redirections because it needs to use Win32
/// API calls to colorize the output. To respect these redirections the <see cref="ConsoleAppender"/>
/// must be used.
/// </para>
/// <para>
/// When configuring the colored console appender, mapping should be
/// specified to map a logging level to a color. For example:
/// </para>
/// <code lang="XML" escaped="true">
/// <mapping>
/// <level value="ERROR" />
/// <foreColor value="White" />
/// <backColor value="Red, HighIntensity" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <backColor value="Green" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard log4net logging level and ForeColor and BackColor can be any
/// combination of the following values:
/// <list type="bullet">
/// <item><term>Blue</term><description></description></item>
/// <item><term>Green</term><description></description></item>
/// <item><term>Red</term><description></description></item>
/// <item><term>White</term><description></description></item>
/// <item><term>Yellow</term><description></description></item>
/// <item><term>Purple</term><description></description></item>
/// <item><term>Cyan</term><description></description></item>
/// <item><term>HighIntensity</term><description></description></item>
/// </list>
/// </para>
/// </remarks>
/// <author>Rick Hobbs</author>
/// <author>Nicko Cadell</author>
public class ColoredConsoleAppender : AppenderSkeleton
{
#region Colors Enum
/// <summary>
/// The enum of possible color values for use with the color mapping method
/// </summary>
/// <remarks>
/// <para>
/// The following flags can be combined together to
/// form the colors.
/// </para>
/// </remarks>
/// <seealso cref="ColoredConsoleAppender" />
[Flags]
public enum Colors : int
{
/// <summary>
/// color is blue
/// </summary>
Blue = 0x0001,
/// <summary>
/// color is green
/// </summary>
Green = 0x0002,
/// <summary>
/// color is red
/// </summary>
Red = 0x0004,
/// <summary>
/// color is white
/// </summary>
White = Blue | Green | Red,
/// <summary>
/// color is yellow
/// </summary>
Yellow = Red | Green,
/// <summary>
/// color is purple
/// </summary>
Purple = Red | Blue,
/// <summary>
/// color is cyan
/// </summary>
Cyan = Green | Blue,
/// <summary>
/// color is intensified
/// </summary>
HighIntensity = 0x0008,
}
#endregion // Colors Enum
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class.
/// </summary>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
public ColoredConsoleAppender()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <remarks>
/// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout property")]
public ColoredConsoleAppender(ILayout layout) : this(layout, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class
/// with the specified layout.
/// </summary>
/// <param name="layout">the layout to use for this appender</param>
/// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param>
/// <remarks>
/// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to
/// the standard error output stream. Otherwise, output is written to the standard
/// output stream.
/// </remarks>
[Obsolete("Instead use the default constructor and set the Layout & Target properties")]
public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream)
{
Layout = layout;
m_writeToErrorStream = writeToErrorStream;
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </summary>
/// <value>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </value>
/// <remarks>
/// <para>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </para>
/// </remarks>
virtual public string Target
{
get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; }
set
{
string v = value.Trim();
if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0)
{
m_writeToErrorStream = true;
}
else
{
m_writeToErrorStream = false;
}
}
}
/// <summary>
/// Add a mapping of level to color - done by the config file
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="LevelColors"/> mapping to this appender.
/// Each mapping defines the foreground and background colors
/// for a level.
/// </para>
/// </remarks>
public void AddMapping(LevelColors mapping)
{
m_levelMapping.Add(mapping);
}
#endregion // Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to the console.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
override protected void Append(log4net.Core.LoggingEvent loggingEvent)
{
if (m_consoleOutputWriter != null)
{
IntPtr consoleHandle = IntPtr.Zero;
if (m_writeToErrorStream)
{
// Write to the error stream
consoleHandle = GetStdHandle(STD_ERROR_HANDLE);
}
else
{
// Write to the output stream
consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
}
// Default to white on black
ushort colorInfo = (ushort)Colors.White;
// see if there is a specified lookup
LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
if (levelColors != null)
{
colorInfo = levelColors.CombinedColor;
}
// Render the event to a string
string strLoggingMessage = RenderLoggingEvent(loggingEvent);
// get the current console color - to restore later
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
GetConsoleScreenBufferInfo(consoleHandle, out bufferInfo);
// set the console colors
SetConsoleTextAttribute(consoleHandle, colorInfo);
// Using WriteConsoleW seems to be unreliable.
// If a large buffer is written, say 15,000 chars
// Followed by a larger buffer, say 20,000 chars
// then WriteConsoleW will fail, last error 8
// 'Not enough storage is available to process this command.'
//
// Although the documentation states that the buffer must
// be less that 64KB (i.e. 32,000 WCHARs) the longest string
// that I can write out a the first call to WriteConsoleW
// is only 30,704 chars.
//
// Unlike the WriteFile API the WriteConsoleW method does not
// seem to be able to partially write out from the input buffer.
// It does have a lpNumberOfCharsWritten parameter, but this is
// either the length of the input buffer if any output was written,
// or 0 when an error occurs.
//
// All results above were observed on Windows XP SP1 running
// .NET runtime 1.1 SP1.
//
// Old call to WriteConsoleW:
//
// WriteConsoleW(
// consoleHandle,
// strLoggingMessage,
// (UInt32)strLoggingMessage.Length,
// out (UInt32)ignoreWrittenCount,
// IntPtr.Zero);
//
// Instead of calling WriteConsoleW we use WriteFile which
// handles large buffers correctly. Because WriteFile does not
// handle the codepage conversion as WriteConsoleW does we
// need to use a System.IO.StreamWriter with the appropriate
// Encoding. The WriteFile calls are wrapped up in the
// System.IO.__ConsoleStream internal class obtained through
// the System.Console.OpenStandardOutput method.
//
// See the ActivateOptions method below for the code that
// retrieves and wraps the stream.
// The windows console uses ScrollConsoleScreenBuffer internally to
// scroll the console buffer when the display buffer of the console
// has been used up. ScrollConsoleScreenBuffer fills the area uncovered
// by moving the current content with the background color
// currently specified on the console. This means that it fills the
// whole line in front of the cursor position with the current
// background color.
// This causes an issue when writing out text with a non default
// background color. For example; We write a message with a Blue
// background color and the scrollable area of the console is full.
// When we write the newline at the end of the message the console
// needs to scroll the buffer to make space available for the new line.
// The ScrollConsoleScreenBuffer internals will fill the newly created
// space with the current background color: Blue.
// We then change the console color back to default (White text on a
// Black background). We write some text to the console, the text is
// written correctly in White with a Black background, however the
// remainder of the line still has a Blue background.
//
// This causes a disjointed appearance to the output where the background
// colors change.
//
// This can be remedied by restoring the console colors before causing
// the buffer to scroll, i.e. before writing the last newline. This does
// assume that the rendered message will end with a newline.
//
// Therefore we identify a trailing newline in the message and don't
// write this to the output, then we restore the console color and write
// a newline. Note that we must AutoFlush before we restore the console
// color otherwise we will have no effect.
//
// There will still be a slight artefact for the last line of the message
// will have the background extended to the end of the line, however this
// is unlikely to cause any user issues.
//
// Note that none of the above is visible while the console buffer is scrollable
// within the console window viewport, the effects only arise when the actual
// buffer is full and needs to be scrolled.
char[] messageCharArray = strLoggingMessage.ToCharArray();
int arrayLength = messageCharArray.Length;
bool appendNewline = false;
// Trim off last newline, if it exists
if (arrayLength > 1 && messageCharArray[arrayLength-2] == '\r' && messageCharArray[arrayLength-1] == '\n')
{
arrayLength -= 2;
appendNewline = true;
}
// Write to the output stream
m_consoleOutputWriter.Write(messageCharArray, 0, arrayLength);
// Restore the console back to its previous color scheme
SetConsoleTextAttribute(consoleHandle, bufferInfo.wAttributes);
if (appendNewline)
{
// Write the newline, after changing the color scheme
m_consoleOutputWriter.Write(s_windowsNewline, 0, 2);
}
}
}
private static readonly char[] s_windowsNewline = {'\r', '\n'};
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Initialize the options for this appender
/// </summary>
/// <remarks>
/// <para>
/// Initialize the level to color mappings set on this appender.
/// </para>
/// </remarks>
#if NET_4_0
[System.Security.SecuritySafeCritical]
#endif
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode=true)]
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
System.IO.Stream consoleOutputStream = null;
// Use the Console methods to open a Stream over the console std handle
if (m_writeToErrorStream)
{
// Write to the error stream
consoleOutputStream = Console.OpenStandardError();
}
else
{
// Write to the output stream
consoleOutputStream = Console.OpenStandardOutput();
}
// Lookup the codepage encoding for the console
System.Text.Encoding consoleEncoding = System.Text.Encoding.GetEncoding(GetConsoleOutputCP());
// Create a writer around the console stream
m_consoleOutputWriter = new System.IO.StreamWriter(consoleOutputStream, consoleEncoding, 0x100);
m_consoleOutputWriter.AutoFlush = true;
// SuppressFinalize on m_consoleOutputWriter because all it will do is flush
// and close the file handle. Because we have set AutoFlush the additional flush
// is not required. The console file handle should not be closed, so we don't call
// Dispose, Close or the finalizer.
GC.SuppressFinalize(m_consoleOutputWriter);
}
#endregion // Override implementation of AppenderSkeleton
#region Public Static Fields
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </para>
/// </remarks>
public const string ConsoleOut = "Console.Out";
/// <summary>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </para>
/// </remarks>
public const string ConsoleError = "Console.Error";
#endregion // Public Static Fields
#region Private Instances Fields
/// <summary>
/// Flag to write output to the error stream rather than the standard output stream
/// </summary>
private bool m_writeToErrorStream = false;
/// <summary>
/// Mapping from level object to color value
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// The console output stream writer to write to
/// </summary>
/// <remarks>
/// <para>
/// This writer is not thread safe.
/// </para>
/// </remarks>
private System.IO.StreamWriter m_consoleOutputWriter = null;
#endregion // Private Instances Fields
#region Win32 Methods
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern int GetConsoleOutputCP();
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool SetConsoleTextAttribute(
IntPtr consoleHandle,
ushort attributes);
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool GetConsoleScreenBufferInfo(
IntPtr consoleHandle,
out CONSOLE_SCREEN_BUFFER_INFO bufferInfo);
// [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
// private static extern bool WriteConsoleW(
// IntPtr hConsoleHandle,
// [MarshalAs(UnmanagedType.LPWStr)] string strBuffer,
// UInt32 bufferLen,
// out UInt32 written,
// IntPtr reserved);
//private const UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10));
private const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
private const UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12));
[DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern IntPtr GetStdHandle(
UInt32 type);
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public UInt16 x;
public UInt16 y;
}
[StructLayout(LayoutKind.Sequential)]
private struct SMALL_RECT
{
public UInt16 Left;
public UInt16 Top;
public UInt16 Right;
public UInt16 Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct CONSOLE_SCREEN_BUFFER_INFO
{
public COORD dwSize;
public COORD dwCursorPosition;
public ushort wAttributes;
public SMALL_RECT srWindow;
public COORD dwMaximumWindowSize;
}
#endregion // Win32 Methods
#region LevelColors LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and the color it should be displayed in.
/// </para>
/// </remarks>
public class LevelColors : LevelMappingEntry
{
private Colors m_foreColor;
private Colors m_backColor;
private ushort m_combinedColor = 0;
/// <summary>
/// The mapped foreground color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped foreground color for the specified level.
/// </para>
/// </remarks>
public Colors ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
/// <summary>
/// The mapped background color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped background color for the specified level.
/// </para>
/// </remarks>
public Colors BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
/// <summary>
/// Initialize the options for the object
/// </summary>
/// <remarks>
/// <para>
/// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
m_combinedColor = (ushort)( (int)m_foreColor + (((int)m_backColor) << 4) );
}
/// <summary>
/// The combined <see cref="ForeColor"/> and <see cref="BackColor"/> suitable for
/// setting the console color.
/// </summary>
internal ushort CombinedColor
{
get { return m_combinedColor; }
}
}
#endregion // LevelColors LevelMapping Entry
}
}
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
{
public static class SLUtil
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region SL / file extension / content-type conversions
public static string SLAssetTypeToContentType(int assetType)
{
switch ((AssetType)assetType)
{
case AssetType.Texture:
return "image/x-j2c";
case AssetType.Sound:
return "audio/ogg";
case AssetType.CallingCard:
return "application/vnd.ll.callingcard";
case AssetType.Landmark:
return "application/vnd.ll.landmark";
case AssetType.Clothing:
return "application/vnd.ll.clothing";
case AssetType.Object:
return "application/vnd.ll.primitive";
case AssetType.Notecard:
return "application/vnd.ll.notecard";
case AssetType.Folder:
return "application/vnd.ll.folder";
case AssetType.RootFolder:
return "application/vnd.ll.rootfolder";
case AssetType.LSLText:
return "application/vnd.ll.lsltext";
case AssetType.LSLBytecode:
return "application/vnd.ll.lslbyte";
case AssetType.TextureTGA:
case AssetType.ImageTGA:
return "image/tga";
case AssetType.Bodypart:
return "application/vnd.ll.bodypart";
case AssetType.TrashFolder:
return "application/vnd.ll.trashfolder";
case AssetType.SnapshotFolder:
return "application/vnd.ll.snapshotfolder";
case AssetType.LostAndFoundFolder:
return "application/vnd.ll.lostandfoundfolder";
case AssetType.SoundWAV:
return "audio/x-wav";
case AssetType.ImageJPEG:
return "image/jpeg";
case AssetType.Animation:
return "application/vnd.ll.animation";
case AssetType.Gesture:
return "application/vnd.ll.gesture";
case AssetType.Simstate:
return "application/x-metaverse-simstate";
case AssetType.FavoriteFolder:
return "application/vnd.ll.favoritefolder";
case AssetType.Link:
return "application/vnd.ll.link";
case AssetType.LinkFolder:
return "application/vnd.ll.linkfolder";
case AssetType.CurrentOutfitFolder:
return "application/vnd.ll.currentoutfitfolder";
case AssetType.OutfitFolder:
return "application/vnd.ll.outfitfolder";
case AssetType.MyOutfitsFolder:
return "application/vnd.ll.myoutfitsfolder";
case AssetType.Unknown:
default:
return "application/octet-stream";
}
}
public static string SLInvTypeToContentType(int invType)
{
switch ((InventoryType)invType)
{
case InventoryType.Animation:
return "application/vnd.ll.animation";
case InventoryType.CallingCard:
return "application/vnd.ll.callingcard";
case InventoryType.Folder:
return "application/vnd.ll.folder";
case InventoryType.Gesture:
return "application/vnd.ll.gesture";
case InventoryType.Landmark:
return "application/vnd.ll.landmark";
case InventoryType.LSL:
return "application/vnd.ll.lsltext";
case InventoryType.Notecard:
return "application/vnd.ll.notecard";
case InventoryType.Attachment:
case InventoryType.Object:
return "application/vnd.ll.primitive";
case InventoryType.Sound:
return "audio/ogg";
case InventoryType.Snapshot:
case InventoryType.Texture:
return "image/x-j2c";
case InventoryType.Wearable:
return "application/vnd.ll.clothing";
default:
return "application/octet-stream";
}
}
public static sbyte ContentTypeToSLAssetType(string contentType)
{
switch (contentType)
{
case "image/x-j2c":
case "image/jp2":
return (sbyte)AssetType.Texture;
case "application/ogg":
case "audio/ogg":
return (sbyte)AssetType.Sound;
case "application/vnd.ll.callingcard":
case "application/x-metaverse-callingcard":
return (sbyte)AssetType.CallingCard;
case "application/vnd.ll.landmark":
case "application/x-metaverse-landmark":
return (sbyte)AssetType.Landmark;
case "application/vnd.ll.clothing":
case "application/x-metaverse-clothing":
return (sbyte)AssetType.Clothing;
case "application/vnd.ll.primitive":
case "application/x-metaverse-primitive":
return (sbyte)AssetType.Object;
case "application/vnd.ll.notecard":
case "application/x-metaverse-notecard":
return (sbyte)AssetType.Notecard;
case "application/vnd.ll.folder":
return (sbyte)AssetType.Folder;
case "application/vnd.ll.rootfolder":
return (sbyte)AssetType.RootFolder;
case "application/vnd.ll.lsltext":
case "application/x-metaverse-lsl":
return (sbyte)AssetType.LSLText;
case "application/vnd.ll.lslbyte":
case "application/x-metaverse-lso":
return (sbyte)AssetType.LSLBytecode;
case "image/tga":
// Note that AssetType.TextureTGA will be converted to AssetType.ImageTGA
return (sbyte)AssetType.ImageTGA;
case "application/vnd.ll.bodypart":
case "application/x-metaverse-bodypart":
return (sbyte)AssetType.Bodypart;
case "application/vnd.ll.trashfolder":
return (sbyte)AssetType.TrashFolder;
case "application/vnd.ll.snapshotfolder":
return (sbyte)AssetType.SnapshotFolder;
case "application/vnd.ll.lostandfoundfolder":
return (sbyte)AssetType.LostAndFoundFolder;
case "audio/x-wav":
return (sbyte)AssetType.SoundWAV;
case "image/jpeg":
return (sbyte)AssetType.ImageJPEG;
case "application/vnd.ll.animation":
case "application/x-metaverse-animation":
return (sbyte)AssetType.Animation;
case "application/vnd.ll.gesture":
case "application/x-metaverse-gesture":
return (sbyte)AssetType.Gesture;
case "application/x-metaverse-simstate":
return (sbyte)AssetType.Simstate;
case "application/vnd.ll.favoritefolder":
return (sbyte)AssetType.FavoriteFolder;
case "application/vnd.ll.link":
return (sbyte)AssetType.Link;
case "application/vnd.ll.linkfolder":
return (sbyte)AssetType.LinkFolder;
case "application/vnd.ll.currentoutfitfolder":
return (sbyte)AssetType.CurrentOutfitFolder;
case "application/vnd.ll.outfitfolder":
return (sbyte)AssetType.OutfitFolder;
case "application/vnd.ll.myoutfitsfolder":
return (sbyte)AssetType.MyOutfitsFolder;
case "application/octet-stream":
default:
return (sbyte)AssetType.Unknown;
}
}
public static sbyte ContentTypeToSLInvType(string contentType)
{
switch (contentType)
{
case "image/x-j2c":
case "image/jp2":
case "image/tga":
case "image/jpeg":
return (sbyte)InventoryType.Texture;
case "application/ogg":
case "audio/ogg":
case "audio/x-wav":
return (sbyte)InventoryType.Sound;
case "application/vnd.ll.callingcard":
case "application/x-metaverse-callingcard":
return (sbyte)InventoryType.CallingCard;
case "application/vnd.ll.landmark":
case "application/x-metaverse-landmark":
return (sbyte)InventoryType.Landmark;
case "application/vnd.ll.clothing":
case "application/x-metaverse-clothing":
case "application/vnd.ll.bodypart":
case "application/x-metaverse-bodypart":
return (sbyte)InventoryType.Wearable;
case "application/vnd.ll.primitive":
case "application/x-metaverse-primitive":
return (sbyte)InventoryType.Object;
case "application/vnd.ll.notecard":
case "application/x-metaverse-notecard":
return (sbyte)InventoryType.Notecard;
case "application/vnd.ll.folder":
return (sbyte)InventoryType.Folder;
case "application/vnd.ll.rootfolder":
return (sbyte)InventoryType.RootCategory;
case "application/vnd.ll.lsltext":
case "application/x-metaverse-lsl":
case "application/vnd.ll.lslbyte":
case "application/x-metaverse-lso":
return (sbyte)InventoryType.LSL;
case "application/vnd.ll.trashfolder":
case "application/vnd.ll.snapshotfolder":
case "application/vnd.ll.lostandfoundfolder":
return (sbyte)InventoryType.Folder;
case "application/vnd.ll.animation":
case "application/x-metaverse-animation":
return (sbyte)InventoryType.Animation;
case "application/vnd.ll.gesture":
case "application/x-metaverse-gesture":
return (sbyte)InventoryType.Gesture;
case "application/x-metaverse-simstate":
return (sbyte)InventoryType.Snapshot;
case "application/octet-stream":
default:
return (sbyte)InventoryType.Unknown;
}
}
#endregion SL / file extension / content-type conversions
/// <summary>
/// Parse a notecard in Linden format to a string of ordinary text.
/// </summary>
/// <param name="rawInput"></param>
/// <returns></returns>
public static string ParseNotecardToString(string rawInput)
{
string[] output = ParseNotecardToList(rawInput).ToArray();
// foreach (string line in output)
// m_log.DebugFormat("[PARSE NOTECARD]: ParseNotecardToString got line {0}", line);
return string.Join("\n", output);
}
/// <summary>
/// Parse a notecard in Linden format to a list of ordinary lines.
/// </summary>
/// <param name="rawInput"></param>
/// <returns></returns>
public static List<string> ParseNotecardToList(string rawInput)
{
string[] input = rawInput.Replace("\r", "").Split('\n');
int idx = 0;
int level = 0;
List<string> output = new List<string>();
string[] words;
while (idx < input.Length)
{
if (input[idx] == "{")
{
level++;
idx++;
continue;
}
if (input[idx]== "}")
{
level--;
idx++;
continue;
}
switch (level)
{
case 0:
words = input[idx].Split(' '); // Linden text ver
// Notecards are created *really* empty. Treat that as "no text" (just like after saving an empty notecard)
if (words.Length < 3)
return output;
int version = int.Parse(words[3]);
if (version != 2)
return output;
break;
case 1:
words = input[idx].Split(' ');
if (words[0] == "LLEmbeddedItems")
break;
if (words[0] == "Text")
{
int len = int.Parse(words[2]);
idx++;
int count = -1;
while (count < len)
{
// int l = input[idx].Length;
string ln = input[idx];
int need = len-count-1;
if (ln.Length > need)
ln = ln.Substring(0, need);
// m_log.DebugFormat("[PARSE NOTECARD]: Adding line {0}", ln);
output.Add(ln);
count += ln.Length + 1;
idx++;
}
return output;
}
break;
case 2:
words = input[idx].Split(' '); // count
if (words[0] == "count")
{
int c = int.Parse(words[1]);
if (c > 0)
return output;
break;
}
break;
}
idx++;
}
return output;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// AudioManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
#endregion
namespace Yacht
{
/// <summary>
/// Component that manages audio playback for all sounds.
/// </summary>
public class AudioManager : GameComponent
{
#region Fields
/// <summary>
/// The singleton for this type.
/// </summary>
static AudioManager audioManager = null;
public static AudioManager Instance
{
get
{
return audioManager;
}
}
static readonly string soundAssetLocation = "Sounds/";
// Audio Data
Dictionary<string, SoundEffectInstance> soundBank;
Dictionary<string, Song> musicBank;
Random random;
#endregion
#region Initialization
private AudioManager(Game game)
: base(game) { }
/// <summary>
/// Initialize the static AudioManager functionality.
/// </summary>
/// <param name="game">The game that this component will be attached to.</param>
public static void Initialize(Game game)
{
audioManager = new AudioManager(game);
audioManager.soundBank = new Dictionary<string, SoundEffectInstance>();
audioManager.musicBank = new Dictionary<string, Song>();
audioManager.random = new Random();
game.Components.Add(audioManager);
}
#endregion
#region Loading Methods
/// <summary>
/// Loads a single sound into the sound manager, giving it a specified alias.
/// </summary>
/// <param name="contentName">The content name of the sound file. Assumes all sounds are located under
/// the "Sounds" folder in the content project.</param>
/// <param name="alias">Alias to give the sound. This will be used to identify the sound uniquely.</param>
/// <remarks>Loading a sound with an alias that is already used will have no effect.</remarks>
public static void LoadSound(string contentName, string alias)
{
SoundEffect soundEffect = audioManager.Game.Content.Load<SoundEffect>(soundAssetLocation + contentName);
SoundEffectInstance soundEffectInstance = soundEffect.CreateInstance();
if (!audioManager.soundBank.ContainsKey(alias))
{
audioManager.soundBank.Add(alias, soundEffectInstance);
}
}
/// <summary>
/// Loads a single song into the sound manager, giving it a specified alias.
/// </summary>
/// <param name="contentName">The content name of the sound file containing the song. Assumes all sounds are
/// located under the "Sounds" folder in the content project.</param>
/// <param name="alias">Alias to give the song. This will be used to identify the song uniquely.</param>
/// /// <remarks>Loading a song with an alias that is already used will have no effect.</remarks>
public static void LoadSong(string contentName, string alias)
{
Song song = audioManager.Game.Content.Load<Song>(soundAssetLocation + contentName);
if (!audioManager.musicBank.ContainsKey(alias))
{
audioManager.musicBank.Add(alias, song);
}
}
/// <summary>
/// Loads and organizes the sounds used by the game.
/// </summary>
public static void LoadSounds()
{
LoadSound("DiceRoll 1", "Roll1");
LoadSound("DiceRoll 2", "Roll2");
LoadSound("DiceRoll 3", "Roll3");
LoadSound("DiceRoll 4", "Roll4");
LoadSound("Pencil 1", "Pencil1");
LoadSound("Pencil 2", "Pencil2");
LoadSound("Pencil 3", "Pencil3");
LoadSound("DiceSelection 1", "DieSelect1");
LoadSound("DiceSelection 2", "DieSelect2");
LoadSound("Score Select", "ScoreSelect");
LoadSound("Turn Change 1", "TurnChange1");
LoadSound("Turn Change 2", "TurnChange2");
LoadSound("Winner", "Winner");
LoadSound("Loss", "Loss");
}
/// <summary>
/// Loads and organizes the music used by the game.
/// </summary>
public static void LoadMusic()
{
// No music for this game
}
#endregion
#region Sound Methods
/// <summary>
/// Indexer. Return a sound instance by name.
/// </summary>
public SoundEffectInstance this[string soundName]
{
get
{
if (audioManager.soundBank.ContainsKey(soundName))
{
return audioManager.soundBank[soundName];
}
else
{
return null;
}
}
}
/// <summary>
/// Plays a sound by name.
/// </summary>
/// <param name="soundName">The name of the sound to play.</param>
public static void PlaySound(string soundName)
{
// If the sound exists, start it
if (audioManager.soundBank.ContainsKey(soundName))
{
audioManager.soundBank[soundName].Play();
}
}
/// <summary>
/// Plays a random sound by appending a number to the supplied sound name.
/// </summary>
/// <param name="soundName">The base sound name to which a number will be appended.</param>
/// <param name="maxNumber">The maximal number to append to <paramref name="soundName"/>.</param>
/// <example>Calling PlaySound("Fish", 4) will play one of the following sounds: Fish1, Fish2, Fish3
/// or Fish4.</example>
public static void PlaySoundRandom(string soundName, int maxNumber)
{
PlaySound(soundName + audioManager.random.Next(1, maxNumber + 1));
}
/// <summary>
/// Plays a sound by name.
/// </summary>
/// <param name="soundName">The name of the sound to play.</param>
/// <param name="isLooped">Indicates if the sound should loop.</param>
public static void PlaySound(string soundName, bool isLooped)
{
// If the sound exists, start it
if (audioManager.soundBank.ContainsKey(soundName))
{
if (audioManager.soundBank[soundName].IsLooped != isLooped)
{
audioManager.soundBank[soundName].IsLooped = isLooped;
}
audioManager.soundBank[soundName].Play();
}
}
/// <summary>
/// Plays a sound by name.
/// </summary>
/// <param name="soundName">The name of the sound to play.</param>
/// <param name="isLooped">Indicates if the sound should loop.</param>
/// <param name="volume">Indicates if the volume</param>
public static void PlaySound(string soundName, bool isLooped, float volume)
{
// If the sound exists, start it
if (audioManager.soundBank.ContainsKey(soundName))
{
if (audioManager.soundBank[soundName].IsLooped != isLooped)
{
audioManager.soundBank[soundName].IsLooped = isLooped;
}
audioManager.soundBank[soundName].Volume = volume;
audioManager.soundBank[soundName].Play();
}
}
/// <summary>
/// Stops a sound mid-play. If the sound is not playing, this
/// method does nothing.
/// </summary>
/// <param name="soundName">The name of the sound to stop.</param>
public static void StopSound(string soundName)
{
// If the sound exists, stop it
if (audioManager.soundBank.ContainsKey(soundName))
{
audioManager.soundBank[soundName].Stop();
}
}
/// <summary>
/// Stops all currently playing sounds.
/// </summary>
public static void StopSounds()
{
foreach (SoundEffectInstance sound in audioManager.soundBank.Values)
{
if (sound.State != SoundState.Stopped)
{
sound.Stop();
}
}
}
/// <summary>
/// Pause or resume all sounds.
/// </summary>
/// <param name="resumeSounds">True to resume all paused sounds or false
/// to pause all playing sounds.</param>
public static void PauseResumeSounds(bool resumeSounds)
{
SoundState state = resumeSounds ? SoundState.Paused : SoundState.Playing;
foreach (SoundEffectInstance sound in audioManager.soundBank.Values)
{
if (sound.State == state)
{
if (resumeSounds)
{
sound.Resume();
}
else
{
sound.Pause();
}
}
}
}
/// <summary>
/// Play music by name. This stops the currently playing music first. Music will loop until stopped.
/// </summary>
/// <param name="musicSoundName">The name of the music sound.</param>
/// <remarks>If the desired music is not in the music bank, nothing will happen.</remarks>
public static void PlayMusic(string musicSoundName)
{
// If the music sound exists
if (audioManager.musicBank.ContainsKey(musicSoundName))
{
// Stop the old music sound
if (MediaPlayer.State != MediaState.Stopped)
{
MediaPlayer.Stop();
}
MediaPlayer.IsRepeating = true;
MediaPlayer.Play(audioManager.musicBank[musicSoundName]);
}
}
/// <summary>
/// Stops the currently playing music.
/// </summary>
public static void StopMusic()
{
if (MediaPlayer.State != MediaState.Stopped)
{
MediaPlayer.Stop();
}
}
#endregion
#region Instance Disposal Methods
/// <summary>
/// Clean up the component when it is disposing.
/// </summary>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
foreach (var item in soundBank)
{
item.Value.Dispose();
}
soundBank.Clear();
soundBank = null;
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion
}
}
| |
using System;
using Eto.Forms;
using System.Linq;
using Eto.Drawing;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
using CoreImage;
#elif OSX
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
using MonoMac.CoreImage;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
#endif
#if IOS
using UIKit;
using CoreGraphics;
using Eto.iOS;
using NSView = UIKit.UIView;
using IMacView = Eto.iOS.Forms.IIosView;
using MacContainer = Eto.iOS.Forms.IosLayout<UIKit.UIView, Eto.Forms.TableLayout, Eto.Forms.TableLayout.ICallback>;
#elif OSX
using Eto.Mac.Forms.Controls;
#if XAMMAC2
using MacContainer = Eto.Mac.Forms.MacContainer<AppKit.NSView, Eto.Forms.TableLayout, Eto.Forms.TableLayout.ICallback>;
#else
using MacContainer = Eto.Mac.Forms.MacContainer<MonoMac.AppKit.NSView, Eto.Forms.TableLayout, Eto.Forms.TableLayout.ICallback>;
#endif
#endif
namespace Eto.Mac.Forms
{
public class TableLayoutHandler : MacContainer, TableLayout.IHandler
{
Control[,] views;
bool[] xscaling;
bool[] yscaling;
int lastxscale;
int lastyscale;
Size spacing;
Padding padding;
CGSize oldFrameSize;
public override NSView ContainerControl { get { return Control; } }
public Size Spacing
{
get { return spacing; }
set
{
spacing = value;
if (Widget.Loaded)
LayoutParent();
}
}
public Padding Padding
{
get { return padding; }
set
{
padding = value;
if (Widget.Loaded)
LayoutParent();
}
}
public TableLayoutHandler()
{
#if OSX
Control = new MacEventView { Handler = this };
#elif IOS
Control = new NSView();
#endif
}
protected override void Initialize()
{
base.Initialize();
Widget.SizeChanged += HandleSizeChanged;
}
bool isResizing;
void HandleSizeChanged(object sender, EventArgs e)
{
if (!isResizing)
{
isResizing = true;
LayoutChildren();
isResizing = false;
}
}
public override void OnLoad(EventArgs e)
{
base.OnLoad(e);
LayoutChildren();
}
protected override SizeF GetNaturalSize(SizeF availableSize)
{
if (views == null)
return SizeF.Empty;
var heights = new float[views.GetLength(0)];
var widths = new float[views.GetLength(1)];
float totalxpadding = Padding.Horizontal + Spacing.Width * (widths.Length - 1);
float totalypadding = Padding.Vertical + Spacing.Height * (heights.Length - 1);
var requiredx = totalxpadding;
var requiredy = totalypadding;
for (int y = 0; y < heights.Length; y++)
{
heights[y] = 0;
}
for (int x = 0; x < widths.Length; x++)
{
widths[x] = 0;
}
for (int y = 0; y < heights.Length; y++)
for (int x = 0; x < widths.Length; x++)
{
var view = views[y, x];
if (view != null && view.Visible)
{
var size = view.GetPreferredSize(Size.MaxValue);
if (size.Width > widths[x])
{
requiredx += size.Width - widths[x];
widths[x] = size.Width;
}
if (size.Height > heights[y])
{
requiredy += size.Height - heights[y];
heights[y] = size.Height;
}
}
}
return new SizeF(requiredx, requiredy);
}
public override void LayoutChildren()
{
if (!Widget.Loaded || views == null || NeedsQueue())
return;
var heights = new float[views.GetLength(0)];
var widths = new float[views.GetLength(1)];
var controlFrame = ContentControl.Frame;
float totalxpadding = Padding.Horizontal + Spacing.Width * (widths.Length - 1);
float totalypadding = Padding.Vertical + Spacing.Height * (heights.Length - 1);
var totalx = (float)controlFrame.Width - totalxpadding;
var totaly = (float)controlFrame.Height - totalypadding;
var requiredx = totalxpadding;
var requiredy = totalypadding;
var numx = 0;
var numy = 0;
for (int y = 0; y < heights.Length; y++)
{
heights[y] = 0;
if (yscaling[y] || lastyscale == y)
numy++;
}
for (int x = 0; x < widths.Length; x++)
{
widths[x] = 0;
if (xscaling[x] || lastxscale == x)
numx++;
}
var availableSize = Size.Max(Size.Empty, Control.Frame.Size.ToEtoSize() - new Size((int)requiredx, (int)requiredy));
for (int y = 0; y < heights.Length; y++)
for (int x = 0; x < widths.Length; x++)
{
var view = views[y, x];
if (view != null && view.Visible)
{
var size = view.GetPreferredSize(availableSize);
if (!xscaling[x] && lastxscale != x && widths[x] < size.Width)
{
requiredx += size.Width - widths[x];
widths[x] = size.Width;
}
if (!yscaling[y] && lastyscale != y && heights[y] < size.Height)
{
requiredy += size.Height - heights[y];
heights[y] = size.Height;
}
}
}
if (controlFrame.Width < requiredx)
{
totalx = requiredx - totalxpadding;
}
if (controlFrame.Height < requiredy)
{
totaly = requiredy - totalypadding;
}
for (int y = 0; y < heights.Length; y++)
if (!yscaling[y] && lastyscale != y)
totaly -= heights[y];
for (int x = 0; x < widths.Length; x++)
if (!xscaling[x] && lastxscale != x)
totalx -= widths[x];
var chunkx = (numx > 0) ? (float)Math.Truncate(Math.Max(totalx, 0) / numx) : totalx;
var chunky = (numy > 0) ? (float)Math.Truncate(Math.Max(totaly, 0) / numy) : totaly;
#if OSX
bool flipped = Control.IsFlipped;
#elif IOS
bool flipped = !Control.Layer.GeometryFlipped;
#endif
float starty = Padding.Top;
for (int x = 0; x < widths.Length; x++)
{
if (xscaling[x] || lastxscale == x)
{
widths[x] = Math.Min(chunkx, totalx);
totalx -= chunkx;
}
}
for (int y = 0; y < heights.Length; y++)
{
if (yscaling[y] || lastyscale == y)
{
heights[y] = Math.Min(chunky, totaly);
totaly -= chunky;
}
float startx = Padding.Left;
for (int x = 0; x < widths.Length; x++)
{
var view = views[y, x];
if (view != null && view.Visible)
{
var nsview = view.GetContainerView();
var frame = nsview.Frame;
var oldframe = frame;
frame.Width = widths[x];
frame.Height = heights[y];
frame.X = Math.Max(0, startx);
frame.Y = flipped ? starty : controlFrame.Height - starty - frame.Height;
if (frame != oldframe)
nsview.Frame = frame;
else if (oldframe.Right > oldFrameSize.Width || oldframe.Bottom > oldFrameSize.Height
|| frame.Right > oldFrameSize.Width || frame.Bottom > oldFrameSize.Height)
nsview.SetNeedsDisplay();
//Console.WriteLine("*** x:{2} y:{3} view: {0} size: {1} totalx:{4} totaly:{5}", view, view.Size, x, y, totalx, totaly);
}
startx += widths[x] + Spacing.Width;
}
starty += heights[y] + Spacing.Height;
}
oldFrameSize = controlFrame.Size;
}
public void Add(Control child, int x, int y)
{
var current = views[y, x];
if (current != null)
{
var currentView = current.GetContainerView();
if (currentView != null)
currentView.RemoveFromSuperview();
}
views[y, x] = child;
if (child != null)
{
var view = child.GetContainerView();
if (Widget.Loaded)
LayoutParent();
Control.AddSubview(view);
}
else if (Widget.Loaded)
LayoutParent();
}
public void Move(Control child, int x, int y)
{
var current = views[y, x];
if (current != null)
{
var currentView = current.GetContainerView();
if (currentView != null)
currentView.RemoveFromSuperview();
}
for (int yy = 0; yy < views.GetLength(0); yy++)
for (int xx = 0; xx < views.GetLength(1); xx++)
{
if (object.ReferenceEquals(views[yy, xx], child))
views[yy, xx] = null;
}
views[y, x] = child;
if (Widget.Loaded)
LayoutParent();
}
public void Remove(Control child)
{
for (int y = 0; y < views.GetLength(0); y++)
for (int x = 0; x < views.GetLength(1); x++)
{
if (object.ReferenceEquals(views[y, x], child))
{
var view = child.GetContainerView();
view.RemoveFromSuperview();
views[y, x] = null;
if (Widget.Loaded)
LayoutParent();
return;
}
}
}
public void CreateControl(int cols, int rows)
{
views = new Control[rows, cols];
xscaling = new bool[cols];
lastxscale = cols - 1;
yscaling = new bool[rows];
lastyscale = rows - 1;
}
public void SetColumnScale(int column, bool scale)
{
xscaling[column] = scale;
lastxscale = xscaling.Any(r => r) ? -1 : xscaling.Length - 1;
if (Widget.Loaded)
LayoutParent();
}
public bool GetColumnScale(int column)
{
return xscaling[column];
}
public void SetRowScale(int row, bool scale)
{
yscaling[row] = scale;
lastyscale = yscaling.Any(r => r) ? -1 : yscaling.Length - 1;
if (Widget.Loaded)
LayoutParent();
}
public bool GetRowScale(int row)
{
return yscaling[row];
}
}
}
| |
/* This class has been written by
* Corinna John (Hannover, Germany)
* cj@binary-universe.net
*
* You may do with this code whatever you like,
* except selling it or claiming any rights/ownership.
*
* Please send me a little feedback about what you're
* using this code for and what changes you'd like to
* see in later versions. (And please excuse my bad english.)
*
* WARNING: This is experimental code.
* Please do not expect "Release Quality".
* */
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace AnimatGuiCtrls.Video
{
public class VideoStream : AviStream
{
/// <summary>handle for AVIStreamGetFrame</summary>
private int getFrameObject;
/// <summary>size of an imge in bytes, stride*height</summary>
private int frameSize;
public int FrameSize {
get { return frameSize; }
}
protected double frameRate;
public double FrameRate {
get{ return frameRate; }
}
private int width;
public int Width{
get{ return width; }
}
private int height;
public int Height{
get{ return height; }
}
private Int16 countBitsPerPixel;
public Int16 CountBitsPerPixel {
get{ return countBitsPerPixel; }
}
/// <summary>count of frames in the stream</summary>
protected int countFrames = 0;
public int CountFrames{
get{ return countFrames; }
}
/// <summary>initial frame index</summary>
/// <remarks>Added by M. Covington</remarks>
protected int firstFrame = 0;
public int FirstFrame
{
get { return firstFrame; }
}
private Avi.AVICOMPRESSOPTIONS compressOptions;
public Avi.AVICOMPRESSOPTIONS CompressOptions {
get { return compressOptions; }
}
public Avi.AVISTREAMINFO StreamInfo {
get { return GetStreamInfo(aviStream); }
}
/// <summary>Initialize an empty VideoStream</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: Create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="frameSize">Size of one frame in bytes</param>
/// <param name="width">Width of each image</param>
/// <param name="height">Height of each image</param>
/// <param name="format">PixelFormat of the images</param>
public VideoStream(int aviFile, bool writeCompressed, double frameRate, int frameSize, int width, int height, PixelFormat format) {
this.aviFile = aviFile;
this.writeCompressed = writeCompressed;
this.frameRate = frameRate;
this.frameSize = frameSize;
this.width = width;
this.height = height;
this.countBitsPerPixel = ConvertPixelFormatToBitCount(format);
this.firstFrame = 0;
CreateStream();
}
/// <summary>Initialize a new VideoStream and add the first frame</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
public VideoStream(int aviFile, bool writeCompressed, double frameRate, Bitmap firstFrame) {
Initialize(aviFile, writeCompressed, frameRate, firstFrame);
CreateStream();
AddFrame(firstFrame);
}
/// <summary>Initialize a new VideoStream and add the first frame</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
public VideoStream(int aviFile, Avi.AVICOMPRESSOPTIONS compressOptions, double frameRate, Bitmap firstFrame) {
Initialize(aviFile, true, frameRate, firstFrame);
CreateStream(compressOptions);
AddFrame(firstFrame);
}
/// <summary>Initialize a VideoStream for an existing stream</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="aviStream">An IAVISTREAM from [aviFile]</param>
public VideoStream(int aviFile, IntPtr aviStream){
this.aviFile = aviFile;
this.aviStream = aviStream;
Avi.BITMAPINFOHEADER bih = new Avi.BITMAPINFOHEADER();
int size = Marshal.SizeOf(bih);
Avi.AVIStreamReadFormat(aviStream, 0, ref bih, ref size);
Avi.AVISTREAMINFO streamInfo = GetStreamInfo(aviStream);
this.frameRate = (float)streamInfo.dwRate / (float)streamInfo.dwScale;
this.width = (int)streamInfo.rcFrame.right;
this.height = (int)streamInfo.rcFrame.bottom;
this.frameSize = bih.biSizeImage;
this.countBitsPerPixel = bih.biBitCount;
this.firstFrame = Avi.AVIStreamStart(aviStream.ToInt32());
this.countFrames = Avi.AVIStreamLength(aviStream.ToInt32());
}
/// <summary>Copy all properties from one VideoStream to another one</summary>
/// <remarks>Used by EditableVideoStream</remarks>
/// <param name="frameSize"></param><param name="frameRate"></param>
/// <param name="width"></param><param name="height"></param>
/// <param name="countBitsPerPixel"></param>
/// <param name="countFrames"></param><param name="compressOptions"></param>
internal VideoStream(int frameSize, double frameRate, int width, int height, Int16 countBitsPerPixel, int countFrames, Avi.AVICOMPRESSOPTIONS compressOptions, bool writeCompressed) {
this.frameSize = frameSize;
this.frameRate = frameRate;
this.width = width;
this.height = height;
this.countBitsPerPixel = countBitsPerPixel;
this.countFrames = countFrames;
this.compressOptions = compressOptions;
this.writeCompressed = writeCompressed;
this.firstFrame = 0;
}
/// <summary>Initialize a new VideoStream</summary>
/// <remarks>Used only by constructors</remarks>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
private void Initialize(int aviFile, bool writeCompressed, double frameRate, Bitmap firstFrameBitmap) {
this.aviFile = aviFile;
this.writeCompressed = writeCompressed;
this.frameRate = frameRate;
this.firstFrame = 0;
BitmapData bmpData = firstFrameBitmap.LockBits(new Rectangle(
0, 0, firstFrameBitmap.Width, firstFrameBitmap.Height),
ImageLockMode.ReadOnly, firstFrameBitmap.PixelFormat);
this.frameSize = bmpData.Stride * bmpData.Height;
this.width = firstFrameBitmap.Width;
this.height = firstFrameBitmap.Height;
this.countBitsPerPixel = ConvertPixelFormatToBitCount(firstFrameBitmap.PixelFormat);
firstFrameBitmap.UnlockBits(bmpData);
}
/// <summary>Get the count of bits per pixel from a PixelFormat value</summary>
/// <param name="format">One of the PixelFormat members beginning with "Format..." - all others are not supported</param>
/// <returns>bit count</returns>
private Int16 ConvertPixelFormatToBitCount(PixelFormat format){
String formatName = format.ToString();
if(formatName.Substring(0, 6) != "Format"){
throw new Exception("Unknown pixel format: "+formatName);
}
formatName = formatName.Substring(6, 2);
Int16 bitCount = 0;
if( Char.IsNumber(formatName[1]) ){ //16, 32, 48
bitCount = Int16.Parse(formatName);
}else{ //4, 8
bitCount = Int16.Parse(formatName[0].ToString());
}
return bitCount;
}
/// <summary>Returns a PixelFormat value for a specific bit count</summary>
/// <param name="bitCount">count of bits per pixel</param>
/// <returns>A PixelFormat value for [bitCount]</returns>
private PixelFormat ConvertBitCountToPixelFormat(int bitCount){
String formatName;
if(bitCount > 16){
formatName = String.Format("Format{0}bppRgb", bitCount);
}else if(bitCount == 16){
formatName = "Format16bppRgb555";
}else{ // < 16
formatName = String.Format("Format{0}bppIndexed", bitCount);
}
return (PixelFormat)Enum.Parse(typeof(PixelFormat), formatName);
}
private Avi.AVISTREAMINFO GetStreamInfo(IntPtr aviStream){
Avi.AVISTREAMINFO streamInfo = new Avi.AVISTREAMINFO();
int result = Avi.AVIStreamInfo(StreamPointer, ref streamInfo, Marshal.SizeOf(streamInfo));
if(result != 0) {
throw new Exception("Exception in VideoStreamInfo: "+result.ToString());
}
return streamInfo;
}
private void GetRateAndScale(ref double frameRate, ref int scale) {
scale = 1;
while (frameRate != (long)frameRate) {
frameRate = frameRate * 10;
scale *= 10;
}
}
/// <summary>Create a new stream</summary>
private void CreateStreamWithoutFormat() {
int scale = 1;
double rate = frameRate;
GetRateAndScale(ref rate, ref scale);
Avi.AVISTREAMINFO strhdr = new Avi.AVISTREAMINFO();
strhdr.fccType = Avi.mmioStringToFOURCC("vids", 0);
strhdr.fccHandler = Avi.mmioStringToFOURCC("CVID", 0);
strhdr.dwFlags = 0;
strhdr.dwCaps = 0;
strhdr.wPriority = 0;
strhdr.wLanguage = 0;
strhdr.dwScale = (int)scale;
strhdr.dwRate = (int)rate; // Frames per Second
strhdr.dwStart = 0;
strhdr.dwLength = 0;
strhdr.dwInitialFrames = 0;
strhdr.dwSuggestedBufferSize = frameSize; //height_ * stride_;
strhdr.dwQuality = -1; //default
strhdr.dwSampleSize = 0;
strhdr.rcFrame.top = 0;
strhdr.rcFrame.left = 0;
strhdr.rcFrame.bottom = (uint)height;
strhdr.rcFrame.right = (uint)width;
strhdr.dwEditCount = 0;
strhdr.dwFormatChangeCount = 0;
strhdr.szName = new UInt16[64];
int result = Avi.AVIFileCreateStream(aviFile, out aviStream, ref strhdr);
if (result != 0) {
throw new Exception("Exception in AVIFileCreateStream: " + result.ToString());
}
}
/// <summary>Create a new stream</summary>
private void CreateStream() {
CreateStreamWithoutFormat();
if (writeCompressed) {
CreateCompressedStream();
} else {
SetFormat(aviStream);
}
}
/// <summary>Create a new stream</summary>
private void CreateStream(Avi.AVICOMPRESSOPTIONS options){
CreateStreamWithoutFormat();
CreateCompressedStream(options);
}
/// <summary>Create a compressed stream from an uncompressed stream</summary>
private void CreateCompressedStream(){
//display the compression options dialog...
Avi.AVICOMPRESSOPTIONS_CLASS options = new Avi.AVICOMPRESSOPTIONS_CLASS();
options.fccType = (uint)Avi.streamtypeVIDEO;
options.lpParms = IntPtr.Zero;
options.lpFormat = IntPtr.Zero;
Avi.AVISaveOptions(IntPtr.Zero, Avi.ICMF_CHOOSE_KEYFRAME | Avi.ICMF_CHOOSE_DATARATE, 1, ref aviStream, ref options);
Avi.AVISaveOptionsFree(1, ref options);
//..or set static options
/*Avi.AVICOMPRESSOPTIONS opts = new Avi.AVICOMPRESSOPTIONS();
opts.fccType = (UInt32)Avi.mmioStringToFOURCC("vids", 0);
opts.fccHandler = (UInt32)Avi.mmioStringToFOURCC("CVID", 0);
opts.dwKeyFrameEvery = 0;
opts.dwQuality = 0; // 0 .. 10000
opts.dwFlags = 0; // AVICOMRPESSF_KEYFRAMES = 4
opts.dwBytesPerSecond= 0;
opts.lpFormat = new IntPtr(0);
opts.cbFormat = 0;
opts.lpParms = new IntPtr(0);
opts.cbParms = 0;
opts.dwInterleaveEvery = 0;*/
//get the compressed stream
this.compressOptions = options.ToStruct();
int result = Avi.AVIMakeCompressedStream(out compressedStream, aviStream, ref compressOptions, 0);
if(result != 0) {
throw new Exception("Exception in AVIMakeCompressedStream: "+result.ToString());
}
SetFormat(compressedStream);
}
/// <summary>Create a compressed stream from an uncompressed stream</summary>
private void CreateCompressedStream(Avi.AVICOMPRESSOPTIONS options) {
int result = Avi.AVIMakeCompressedStream(out compressedStream, aviStream, ref options, 0);
if (result != 0) {
throw new Exception("Exception in AVIMakeCompressedStream: " + result.ToString());
}
this.compressOptions = options;
SetFormat(compressedStream);
}
/// <summary>Add one frame to a new stream</summary>
/// <param name="bmp"></param>
/// <remarks>
/// This works only with uncompressed streams,
/// and compressed streams that have not been saved yet.
/// Use DecompressToNewFile to edit saved compressed streams.
/// </remarks>
public void AddFrame(Bitmap bmp){
bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
BitmapData bmpDat = bmp.LockBits(
new Rectangle(
0,0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly, bmp.PixelFormat);
int result = Avi.AVIStreamWrite(writeCompressed ? compressedStream : StreamPointer,
countFrames, 1,
bmpDat.Scan0,
(Int32)(bmpDat.Stride * bmpDat.Height),
0, 0, 0);
if (result!= 0) {
throw new Exception("Exception in VideoStreamWrite: "+result.ToString());
}
bmp.UnlockBits(bmpDat);
countFrames++;
}
/// <summary>Apply a format to a new stream</summary>
/// <param name="aviStream">The IAVISTREAM</param>
/// <remarks>
/// The format must be set before the first frame can be written,
/// and it cannot be changed later.
/// </remarks>
private void SetFormat(IntPtr aviStream){
Avi.BITMAPINFOHEADER bi = new Avi.BITMAPINFOHEADER();
bi.biSize = Marshal.SizeOf(bi);
bi.biWidth = width;
bi.biHeight = height;
bi.biPlanes = 1;
bi.biBitCount = countBitsPerPixel;
bi.biSizeImage = frameSize;
int result = Avi.AVIStreamSetFormat(aviStream, 0, ref bi, bi.biSize);
if(result != 0){ throw new Exception("Error in VideoStreamSetFormat: "+result.ToString()); }
}
/// <summary>Prepare for decompressing frames</summary>
/// <remarks>
/// This method has to be called before GetBitmap and ExportBitmap.
/// Release ressources with GetFrameClose.
/// </remarks>
public void GetFrameOpen(){
Avi.AVISTREAMINFO streamInfo = GetStreamInfo(StreamPointer);
//Open frames
Avi.BITMAPINFOHEADER bih = new Avi.BITMAPINFOHEADER();
bih.biBitCount = countBitsPerPixel;
bih.biClrImportant = 0;
bih.biClrUsed = 0;
bih.biCompression = 0;
bih.biPlanes = 1;
bih.biSize = Marshal.SizeOf(bih);
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
// Corrections by M. Covington:
// If these are pre-set, interlaced video is not handled correctly.
// Better to give zeroes and let Windows fill them in.
bih.biHeight = 0; // was (Int32)streamInfo.rcFrame.bottom;
bih.biWidth = 0; // was (Int32)streamInfo.rcFrame.right;
// Corrections by M. Covington:
// Validate the bit count, because some AVI files give a bit count
// that is not one of the allowed values in a BitmapInfoHeader.
// Here 0 means for Windows to figure it out from other information.
if (bih.biBitCount > 24)
{
bih.biBitCount = 32;
}
else if (bih.biBitCount > 16)
{
bih.biBitCount = 24;
}
else if (bih.biBitCount > 8)
{
bih.biBitCount = 16;
}
else if (bih.biBitCount > 4)
{
bih.biBitCount = 8;
}
else if (bih.biBitCount > 0)
{
bih.biBitCount = 4;
}
getFrameObject = Avi.AVIStreamGetFrameOpen(StreamPointer, ref bih);
if(getFrameObject == 0){ throw new Exception("Exception in VideoStreamGetFrameOpen!"); }
}
/// <summary>Export a frame into a bitmap file</summary>
/// <param name="position">Position of the frame</param>
/// <param name="dstFileName">Name of the file to store the bitmap</param>
public void ExportBitmap(int position, String dstFileName){
Bitmap bmp = GetBitmap(position);
bmp.Save(dstFileName, ImageFormat.Bmp);
bmp.Dispose();
}
/// <summary>Export a frame into a bitmap</summary>
/// <param name="position">Position of the frame</param>
public Bitmap GetBitmap(int position){
if(position > countFrames){
throw new Exception("Invalid frame position: "+position);
}
Avi.AVISTREAMINFO streamInfo = GetStreamInfo(StreamPointer);
//Decompress the frame and return a pointer to the DIB
int dib = Avi.AVIStreamGetFrame(getFrameObject, firstFrame + position);
//Copy the bitmap header into a managed struct
Avi.BITMAPINFOHEADER bih = new Avi.BITMAPINFOHEADER();
bih = (Avi.BITMAPINFOHEADER)Marshal.PtrToStructure(new IntPtr(dib), bih.GetType());
if(bih.biSizeImage < 1){
throw new Exception("Exception in VideoStreamGetFrame");
}
//copy the image
byte[] bitmapData;
int address = dib + Marshal.SizeOf(bih);
if(bih.biBitCount < 16){
//copy palette and pixels
bitmapData = new byte[bih.biSizeImage + Avi.PALETTE_SIZE];
}else{
//copy only pixels
bitmapData = new byte[bih.biSizeImage];
}
Marshal.Copy(new IntPtr(address), bitmapData, 0, bitmapData.Length);
//copy bitmap info
byte[] bitmapInfo = new byte[Marshal.SizeOf(bih)];
IntPtr ptr;
ptr = Marshal.AllocHGlobal(bitmapInfo.Length);
Marshal.StructureToPtr(bih, ptr, false);
address = ptr.ToInt32();
Marshal.Copy(new IntPtr(address), bitmapInfo, 0, bitmapInfo.Length);
Marshal.FreeHGlobal(ptr);
//create file header
Avi.BITMAPFILEHEADER bfh = new Avi.BITMAPFILEHEADER();
bfh.bfType = Avi.BMP_MAGIC_COOKIE;
bfh.bfSize = (Int32)(55 + bih.biSizeImage); //size of file as written to disk
bfh.bfReserved1 = 0;
bfh.bfReserved2 = 0;
bfh.bfOffBits = Marshal.SizeOf(bih) + Marshal.SizeOf(bfh);
if(bih.biBitCount < 16){
//There is a palette between header and pixel data
bfh.bfOffBits += Avi.PALETTE_SIZE;
}
//write a bitmap stream
BinaryWriter bw = new BinaryWriter( new MemoryStream() );
//write header
bw.Write(bfh.bfType);
bw.Write(bfh.bfSize);
bw.Write(bfh.bfReserved1);
bw.Write(bfh.bfReserved2);
bw.Write(bfh.bfOffBits);
//write bitmap info
bw.Write(bitmapInfo);
//write bitmap data
bw.Write(bitmapData);
Bitmap bmp = (Bitmap)Image.FromStream(bw.BaseStream);
Bitmap saveableBitmap = new Bitmap(bmp.Width, bmp.Height);
Graphics g = Graphics.FromImage(saveableBitmap);
g.DrawImage(bmp, 0,0);
g.Dispose();
bmp.Dispose();
bw.Close();
return saveableBitmap;
}
/// <summary>Free ressources that have been used by GetFrameOpen</summary>
public void GetFrameClose(){
if(getFrameObject != 0){
Avi.AVIStreamGetFrameClose(getFrameObject);
getFrameObject = 0;
}
}
/// <summary>Copy all frames into a new file</summary>
/// <param name="fileName">Name of the new file</param>
/// <param name="recompress">true: Compress the new stream</param>
/// <returns>AviManager for the new file</returns>
/// <remarks>Use this method if you want to append frames to an existing, compressed stream</remarks>
public AviManager DecompressToNewFile(String fileName, bool recompress, out VideoStream newStream2){
AviManager newFile = new AviManager(fileName, false);
this.GetFrameOpen();
Bitmap frame = GetBitmap(0);
VideoStream newStream = newFile.AddVideoStream(recompress, frameRate, frame);
frame.Dispose();
for(int n=1; n<countFrames; n++){
frame = GetBitmap(n);
newStream.AddFrame(frame);
frame.Dispose();
}
this.GetFrameClose();
newStream2 = newStream;
return newFile;
}
/// <summary>Copy the stream into a new file</summary>
/// <param name="fileName">Name of the new file</param>
public override void ExportStream(String fileName){
Avi.AVICOMPRESSOPTIONS_CLASS opts = new Avi.AVICOMPRESSOPTIONS_CLASS();
opts.fccType = (uint)Avi.streamtypeVIDEO;
opts.lpParms = IntPtr.Zero;
opts.lpFormat = IntPtr.Zero;
IntPtr streamPointer = StreamPointer;
Avi.AVISaveOptions(IntPtr.Zero, Avi.ICMF_CHOOSE_KEYFRAME | Avi.ICMF_CHOOSE_DATARATE, 1, ref streamPointer, ref opts);
Avi.AVISaveOptionsFree(1, ref opts);
Avi.AVISaveV(fileName, 0, 0, 1, ref aviStream, ref opts);
}
}
}
| |
//---------------------------------------------------------------------
// This file is part of the CLR Managed Debugger (mdbg) Sample.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Samples.Debugging.Native;
using Microsoft.Samples.Debugging.Native.Private;
namespace Microsoft.Samples.Debugging.Native
{
public class IA64Context : INativeContext, IEquatable<INativeContext>, IDisposable
{
private int m_size;
private Platform m_platform;
private int m_imageFileMachine;
private IntPtr m_rawPtr;
~IA64Context()
{
this.Dispose(false);
}
// This is a private contstructor for cloning Context objects. It should not be used outside of this class.
private IA64Context(INativeContext ctx)
{
this.m_size = ctx.Size;
this.m_platform = ctx.Platform;
this.m_imageFileMachine = ctx.ImageFileMachine;
this.m_rawPtr = Marshal.AllocHGlobal(this.Size);
using (IContextDirectAccessor w = ctx.OpenForDirectAccess())
{
// The fact that Marshal.Copy cannot copy between to native memory locations is stupid.
for (int i = 0; i < this.m_size; i++)
{
// In theory, we could make this faster by copying larger units (i.e. Int64). We get our sizes in bytes
// so for now we'll just copy bytes to keep our units straight.
byte chunk = Marshal.ReadByte(w.RawBuffer, i);
Marshal.WriteByte(this.RawPtr, i, chunk);
}
}
}
public IA64Context()
: this(AgnosticContextFlags.ContextControl | AgnosticContextFlags.ContextInteger)
{
}
public IA64Context(AgnosticContextFlags aFlags)
{
InitializeContext();
WriteContextFlagsToBuffer(GetPSFlags(aFlags));
}
public IA64Context(ContextFlags flags)
{
InitializeContext();
WriteContextFlagsToBuffer(flags);
}
private void InitializeContext()
{
this.m_size = (int)ContextSize.IA64;
this.m_platform = Platform.IA64;
this.m_imageFileMachine = (int) Native.ImageFileMachine.IA64;
this.m_rawPtr = Marshal.AllocHGlobal(this.Size);
return;
}
private void WriteContextFlagsToBuffer(ContextFlags flags)
{
Debug.Assert(this.RawPtr != IntPtr.Zero);
Marshal.WriteInt32(this.RawPtr, (int)IA64Offsets.ContextFlags, (Int32)flags);
}
public IContextDirectAccessor OpenForDirectAccess()
{
// we can return a copy of ourself so that it will be destroyed once it goes out of scope.
return new ContextAccessor(this.RawPtr, this.Size);
}
public void ClearContext()
{
// make sure that we have access to the buffer
using (IContextDirectAccessor w = this.OpenForDirectAccess())
{
for (int i = 0; i < w.Size; i++)
{
Marshal.WriteByte(w.RawBuffer, i, (byte)0);
}
}
}
// returns the platform-specific Context Flags
public ContextFlags GetPSFlags(AgnosticContextFlags flags)
{
// We know that we need an ia64 context
this.m_platform = Platform.IA64;
ContextFlags cFlags = ContextFlags.IA64Context;
if ((flags & AgnosticContextFlags.ContextInteger) == AgnosticContextFlags.ContextInteger)
{
// ContextInteger is the same for all platforms, so we can do a blanket |=
cFlags |= (ContextFlags)AgnosticContextFlags.ContextInteger;
}
if ((flags & AgnosticContextFlags.ContextControl) == AgnosticContextFlags.ContextControl)
{
// IA64 has a different flag for ContextControl
cFlags |= ContextFlags.IA64ContextControl;
}
if ((flags & AgnosticContextFlags.ContextFloatingPoint) == AgnosticContextFlags.ContextFloatingPoint)
{
// IA64 has a different flag for ContextFloatingPoint
cFlags |= ContextFlags.IA64ContextFloatingPoint;
}
if ((flags & AgnosticContextFlags.ContextAll) == AgnosticContextFlags.ContextAll)
{
// ContextAll is the same for all platforms, so we can do a blanket |=
cFlags |= (ContextFlags)AgnosticContextFlags.ContextAll;
}
return cFlags;
}
// Sets m_platform the the platform represented by the context flags
private Platform GetPlatform(ContextFlags flags)
{
return Platform.IA64;
}
// returns the size of the Context
public int Size
{
get
{
return this.m_size;
}
}
// returns a pointer to the Context
private IntPtr RawPtr
{
get
{
return this.m_rawPtr;
}
}
// returns the ContextFlags for the Context
public ContextFlags Flags
{
get
{
Debug.Assert(this.RawPtr != IntPtr.Zero);
return (ContextFlags)Marshal.ReadInt32(this.RawPtr, (int)IA64Offsets.ContextFlags);
}
set
{
if ((value & ContextFlags.IA64Context) == 0)
{
throw new ArgumentException("Process architecture flag must be set");
}
if ((value & ~ContextFlags.IA64ContextAll) != 0)
{
throw new ArgumentException("Unsupported context flags for this architecture");
}
WriteContextFlagsToBuffer(value);
}
}
// returns the StackPointer for the Context
public IntPtr StackPointer
{
get
{
Debug.Assert(this.m_rawPtr != IntPtr.Zero, "The context has an invalid context pointer");
return (IntPtr)Marshal.ReadInt64(this.m_rawPtr, (int)IA64Offsets.IntSp);
}
}
// returns a Platform for the Context
public Platform Platform
{
get
{
return this.m_platform;
}
}
// returns the IP for the Context
public IntPtr InstructionPointer
{
get
{
IntPtr ip = IntPtr.Zero;
using (IContextDirectAccessor w = this.OpenForDirectAccess())
{
Int64 iip = Marshal.ReadInt64(w.RawBuffer, (int)IA64Offsets.StIIP);
Int64 StIPSR = Marshal.ReadInt64(w.RawBuffer, (int)IA64Offsets.StIPSR);
int PSR_RI = (int)IA64Flags.PSR_RI;
Int64 slot = (StIPSR >> PSR_RI) & 3;
iip |= slot << 2;
ip = (IntPtr)iip;
}
return ip;
}
set
{
using (IContextDirectAccessor w = this.OpenForDirectAccess())
{
UInt64 ipsr = 0;
UInt64 iip = (UInt64)value.ToInt64();
// slot = iip & (IA64_BUNDLE_SIZE - 1) >> 2
UInt64 slot = ((UInt64)iip) & ((int)IA64Flags.IA64_BUNDLE_SIZE - 1) >> 2;
// StIIP = iip & ~(IA64_BUNDLE_SIZE - 1)
Marshal.WriteIntPtr(w.RawBuffer, (int)IA64Offsets.StIIP, (IntPtr)(iip & ~((UInt64)((int)IA64Flags.IA64_BUNDLE_SIZE - 1))));
// StIPSR &= ~(0x3 << PSR_RI)
ipsr = (UInt64)Marshal.ReadIntPtr(w.RawBuffer, (int)IA64Offsets.StIPSR) & ~(((UInt64)0x3) << (int)IA64Flags.PSR_RI);
Marshal.WriteIntPtr(w.RawBuffer, (int)IA64Offsets.StIPSR, (IntPtr)ipsr);
// StIPSR |= (slot << PSR_RI)
ipsr = (UInt64)Marshal.ReadIntPtr(w.RawBuffer, (int)IA64Offsets.StIPSR) | (slot << (int)IA64Flags.PSR_RI);
Marshal.WriteIntPtr(w.RawBuffer, (int)IA64Offsets.StIPSR, (IntPtr)ipsr);
}
}
}
// returns the ImageFileMachine for the Context
public int ImageFileMachine
{
get
{
return this.m_imageFileMachine;
}
}
public void SetSingleStepFlag(bool fEnable)
{
if (fEnable)
{
Int64 stipsr = Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StIPSR) | (Int64)IA64Flags.SINGLE_STEP_FLAG;
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StIPSR, stipsr);
}
else
{
Int64 stipsr = Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StIPSR) & ~((Int64)IA64Flags.SINGLE_STEP_FLAG);
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StIPSR, stipsr);
}
}
public bool IsSingleStepFlagEnabled
{
get
{
return ((Marshal.ReadInt32(this.RawPtr, (int)IA64Offsets.StIPSR) & (long)IA64Flags.SINGLE_STEP_FLAG) != 0);
}
}
public INativeContext Clone()
{
return new IA64Context(this);
}
public bool Equals(INativeContext other)
{
if (this.Platform != other.Platform)
{
return false;
}
if (this.ImageFileMachine != other.ImageFileMachine)
{
return false;
}
if (this.Size != other.Size)
{
return false;
}
return CheckContexts(this, (IA64Context)other);
}
public bool CheckContexts(INativeContext a1, INativeContext a2)
{
return CheckIA64Contexts((IA64Context)a1, (IA64Context)a2);
}
// compare a chuck of the context record contained between the two offsets
private bool CheckContextChunk(IA64Context a1, IA64Context a2, int startOffset, int endOffset)
{
using (IContextDirectAccessor c1 = a1.OpenForDirectAccess())
{
using (IContextDirectAccessor c2 = a2.OpenForDirectAccess())
{
for (int i = startOffset; i < endOffset; i++)
{
if (Marshal.ReadByte(c1.RawBuffer, i) != Marshal.ReadByte(c2.RawBuffer, i))
{
return false;
}
}
}
}
return true;
}
private bool CheckIA64Contexts(IA64Context a1, IA64Context a2)
{
// CONTEXT_CONTROL contains: ApUNAT through rest of CONTEXT
if ((a1.Flags & ContextFlags.IA64ContextControl) == ContextFlags.IA64ContextControl)
{
if (!CheckContextChunk(a1, a2, (int)IA64Offsets.ApUNAT, (int)IA64Offsets.UNUSEDPACK))
{
return false;
}
}
// CONTEXT_CONTROL contains: IntGp through ApUNAT
if ((a1.Flags & ContextFlags.IA64ContextInteger) == ContextFlags.IA64ContextInteger)
{
if (!CheckContextChunk(a1, a2, (int)IA64Offsets.IntGp, (int)IA64Offsets.ApUNAT))
{
return false;
}
}
// CONTEXT_DEBUG contains: DbI0 through FltS0
if ((a1.Flags & ContextFlags.IA64ContextDebug) == ContextFlags.IA64ContextDebug)
{
if (!CheckContextChunk(a1, a2, (int)IA64Offsets.DbI0, (int)IA64Offsets.FltS0))
{
return false;
}
}
// CONTEXT_FLOATING_POINT contains: FltS0 through StFPSR
if ((a1.Flags & ContextFlags.IA64ContextFloatingPoint) == ContextFlags.IA64ContextFloatingPoint)
{
if (!CheckContextChunk(a1, a2, (int)IA64Offsets.FltS0, (int)IA64Offsets.StFPSR))
{
return false;
}
}
return true;
}
private bool HasFlags(ContextFlags flags)
{
return ((this.Flags & flags) == flags);
}
public IEnumerable<String> EnumerateRegisters()
{
return EnumerateIA64Registers();
}
private IEnumerable<String> EnumerateIA64Registers()
{
List<String> list = new List<String>();
// This includes the most commonly used flags.
if (HasFlags(ContextFlags.IA64ContextControl))
{
list.Add("ApUNAT");
list.Add("ApLC");
list.Add("ApEC");
list.Add("ApCCV");
list.Add("ApDCR");
list.Add("RsPFS");
list.Add("RsBSP");
list.Add("RsBSPSTORE");
list.Add("RsRSC");
list.Add("RsRNAT");
list.Add("StIPSR");
list.Add("StIIP");
list.Add("StIFS");
list.Add("StFCR");
list.Add("EFLAGS");
list.Add("SegCSD");
list.Add("SegSSD");
list.Add("Cflag");
list.Add("StFSR");
list.Add("StFIR");
list.Add("StFDR");
}
if (HasFlags(ContextFlags.IA64ContextInteger))
{
list.Add("IntGp");
list.Add("IntT0");
list.Add("IntT1");
list.Add("IntS0");
list.Add("IntS1");
list.Add("IntS2");
list.Add("IntS3");
list.Add("IntV0");
list.Add("IntT2");
list.Add("IntT3");
list.Add("IntT4");
list.Add("IntSp");
list.Add("IntTeb");
list.Add("IntT5");
list.Add("IntT6");
list.Add("IntT7");
list.Add("IntT8");
list.Add("IntT9");
list.Add("IntT10");
list.Add("IntT11");
list.Add("IntT12");
list.Add("IntT13");
list.Add("IntT14");
list.Add("IntT15");
list.Add("IntT16");
list.Add("IntT17");
list.Add("IntT18");
list.Add("IntT19");
list.Add("IntT20");
list.Add("IntT21");
list.Add("IntT22");
list.Add("IntNats");
list.Add("Preds");
list.Add("BrRp");
list.Add("BrS0");
list.Add("BrS1");
list.Add("BrS2");
list.Add("BrS3");
list.Add("BrS4");
list.Add("BrT0");
list.Add("BrT1");
}
if (HasFlags(ContextFlags.IA64ContextDebug))
{
list.Add("DbI0");
list.Add("DbI1");
list.Add("DbI2");
list.Add("DbI3");
list.Add("DbI4");
list.Add("DbI5");
list.Add("DbI6");
list.Add("DbI7");
list.Add("DbD0");
list.Add("DbD1");
list.Add("DbD2");
list.Add("DbD3");
list.Add("DbD4");
list.Add("DbD5");
list.Add("DbD6");
list.Add("DbD7");
}
return list;
}
public object FindRegisterByName(String name)
{
return IA64FindRegisterByName(name);
}
private object IA64FindRegisterByName(String name)
{
name = name.ToUpperInvariant();
if (HasFlags(ContextFlags.IA64ContextControl))
{
if (name == "APUNAT") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.ApUNAT);
if (name == "APLC") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.ApLC);
if (name == "APEC") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.ApEC);
if (name == "APCCV") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.ApCCV);
if (name == "APDCR") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.ApDCR);
if (name == "RSPFS") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.RsPFS);
if (name == "RSBSP") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.RsBSP);
if (name == "RSBSPSTORE") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.RsBSPSTORE);
if (name == "RSRSC") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.RsRSC);
if (name == "RSRNAT") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.RsRNAT);
if (name == "STIPSR") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StIPSR);
if (name == "STIIP") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StIIP);
if (name == "STIFS") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StIFS);
if (name == "STFCR") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StFCR);
if (name == "EFLAG") return Marshal.ReadInt32(this.RawPtr, (int)IA64Offsets.Eflag);
if (name == "SEGCSD") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.SegCSD);
if (name == "SEGSSD") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.SegSSD);
if (name == "CFLAG") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.Cflag);
if (name == "STFSR") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StFSR);
if (name == "STFIR") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StFIR);
if (name == "STFDR") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.StFDR);
}
if (HasFlags(ContextFlags.IA64ContextInteger))
{
if (name == "INTGP") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntGp);
if (name == "INTT0") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT0);
if (name == "INTT1") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT1);
if (name == "INTS0") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntS0);
if (name == "INTS1") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntS1);
if (name == "INTS2") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntS2);
if (name == "INTS3") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntS3);
if (name == "INTV0") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntV0);
if (name == "INTT2") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT2);
if (name == "INTT3") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT3);
if (name == "INTT4") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT4);
if (name == "INTSP") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntSp);
if (name == "INTTEB") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntTeb);
if (name == "INTT5") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT5);
if (name == "INTT6") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT6);
if (name == "INTT7") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT7);
if (name == "INTT8") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT8);
if (name == "INTT9") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT9);
if (name == "INTT10") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT10);
if (name == "INTT11") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT11);
if (name == "INTT12") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT11);
if (name == "INTT13") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT13);
if (name == "INTT14") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT14);
if (name == "INTT15") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT15);
if (name == "INTT16") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT16);
if (name == "INTT17") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT17);
if (name == "INTT18") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT18);
if (name == "INTT19") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT19);
if (name == "INTT20") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT20);
if (name == "INTT21") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT21);
if (name == "INTT22") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntT22);
if (name == "INTNATS") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.IntNats);
if (name == "PREDS") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.Preds);
if (name == "BRRp") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrRp);
if (name == "BRS0") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrS0);
if (name == "BRS1") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrS1);
if (name == "BRS2") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrS2);
if (name == "BRS3") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrS3);
if (name == "BRS4") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrS4);
if (name == "BRT0") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrT0);
if (name == "BRT1") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.BrT1);
}
if (HasFlags(ContextFlags.IA64ContextDebug))
{
if (name == "DBI0") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI0);
if (name == "DBI1") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI1);
if (name == "DBI2") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI2);
if (name == "DBI3") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI3);
if (name == "DBI4") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI4);
if (name == "DBI5") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI5);
if (name == "DBI6") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI6);
if (name == "DBI7") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbI7);
if (name == "DBD0") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD0);
if (name == "DBD1") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD1);
if (name == "DBD2") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD2);
if (name == "DBD3") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD3);
if (name == "DBD4") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD4);
if (name == "DBD5") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD5);
if (name == "DBD6") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD6);
if (name == "DBD7") return Marshal.ReadInt64(this.RawPtr, (int)IA64Offsets.DbD7);
}
throw new InvalidOperationException(String.Format("Register '{0}' is not in the context", name));
}
public void SetRegisterByName(String name, object value)
{
IA64SetRegisterByName(name, value);
}
private void IA64SetRegisterByName(String name, object value)
{
name = name.ToUpperInvariant();
if (HasFlags(ContextFlags.IA64ContextControl))
{
if (name == "APUNAT")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.ApUNAT, (Int64)value);
return;
}
if (name == "APLC")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.ApLC, (Int64)value);
return;
}
if (name == "APEC")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.ApEC, (Int64)value);
return;
}
if (name == "APCCV")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.ApCCV, (Int64)value);
return;
}
if (name == "APDCR")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.ApDCR, (Int64)value);
return;
}
if (name == "RSPFS")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.RsPFS, (Int64)value);
return;
}
if (name == "RSBSP")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.RsBSP, (Int64)value);
return;
}
if (name == "RSBSPSTORE")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.RsBSPSTORE, (Int64)value);
return;
}
if (name == "RSRSC")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.RsRSC, (Int64)value);
return;
}
if (name == "RSRNAT")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.RsRNAT, (Int64)value);
return;
}
if (name == "STIPSR")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StIPSR, (Int64)value);
return;
}
if (name == "STIIP")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StIIP, (Int64)value);
return;
}
if (name == "STIFS")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StIFS, (Int64)value);
return;
}
if (name == "STFCR")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StFCR, (Int64)value);
return;
}
if (name == "EFLAG")
{
Marshal.WriteInt32(this.RawPtr, (int)IA64Offsets.Eflag, (Int32)value);
return;
}
if (name == "SEGCSD")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.SegCSD, (Int64)value);
return;
}
if (name == "SEGSSD")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.SegSSD, (Int64)value);
return;
}
if (name == "CFLAG")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.Cflag, (Int64)value);
return;
}
if (name == "STFSR")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StFSR, (Int64)value);
return;
}
if (name == "STFIR")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StFIR, (Int64)value);
return;
}
if (name == "STFDR")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.StFDR, (Int64)value);
return;
}
}
if (HasFlags(ContextFlags.IA64ContextInteger))
{
if (name == "INTGP")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntGp, (Int64)value);
return;
}
if (name == "INTT0")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT0, (Int64)value);
return;
}
if (name == "INTT1")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT1, (Int64)value);
return;
}
if (name == "INTS0")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntS0, (Int64)value);
return;
}
if (name == "INTS1")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntS1, (Int64)value);
return;
}
if (name == "INTS2")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntS2, (Int64)value);
return;
}
if (name == "INTS3")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntS3, (Int64)value);
return;
}
if (name == "INTV0")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntV0, (Int64)value);
return;
}
if (name == "INTT2")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT2, (Int64)value);
return;
}
if (name == "INTT3")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT3, (Int64)value);
return;
}
if (name == "INTT4")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT4, (Int64)value);
return;
}
if (name == "INTSP")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntSp, (Int64)value);
return;
}
if (name == "INTTEB")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntTeb, (Int64)value);
return;
}
if (name == "INTT5")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT5, (Int64)value);
return;
}
if (name == "INTT6")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT6, (Int64)value);
return;
}
if (name == "INTT7")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT7, (Int64)value);
return;
}
if (name == "INTT8")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT8, (Int64)value);
return;
}
if (name == "INTT9")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT9, (Int64)value);
return;
}
if (name == "INTT10")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT10, (Int64)value);
return;
}
if (name == "INTT11")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT11, (Int64)value);
return;
}
if (name == "INTT12")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT11, (Int64)value);
return;
}
if (name == "INTT13")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT13, (Int64)value);
return;
}
if (name == "INTT14")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT14, (Int64)value);
return;
}
if (name == "INTT15")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT15, (Int64)value);
return;
}
if (name == "INTT16")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT16, (Int64)value);
return;
}
if (name == "INTT17")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT17, (Int64)value);
return;
}
if (name == "INTT18")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT18, (Int64)value);
return;
}
if (name == "INTT19")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT19, (Int64)value);
return;
}
if (name == "INTT20")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT20, (Int64)value);
return;
}
if (name == "INTT21")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT21, (Int64)value);
return;
}
if (name == "INTT22")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntT22, (Int64)value);
return;
}
if (name == "INTNATS")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.IntNats, (Int64)value);
return;
}
if (name == "PREDS")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.Preds, (Int64)value);
return;
}
if (name == "BRRp")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrRp, (Int64)value);
return;
}
if (name == "BRS0")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrS0, (Int64)value);
return;
}
if (name == "BRS1")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrS1, (Int64)value);
return;
}
if (name == "BRS2")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrS2, (Int64)value);
return;
}
if (name == "BRS3")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrS3, (Int64)value);
return;
}
if (name == "BRS4")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrS4, (Int64)value);
return;
}
if (name == "BRT0")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrT0, (Int64)value);
return;
}
if (name == "BRT1")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.BrT1, (Int64)value);
return;
}
}
if (HasFlags(ContextFlags.IA64ContextDebug))
{
if (name == "DBI0")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI0, (Int64)value);
return;
}
if (name == "DBI1")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI1, (Int64)value);
return;
}
if (name == "DBI2")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI2, (Int64)value);
return;
}
if (name == "DBI3")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI3, (Int64)value);
return;
}
if (name == "DBI4")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI4, (Int64)value);
return;
}
if (name == "DBI5")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI5, (Int64)value);
return;
}
if (name == "DBI6")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI6, (Int64)value);
return;
}
if (name == "DBI7")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbI7, (Int64)value);
return;
}
if (name == "DBD0")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD0, (Int64)value);
return;
}
if (name == "DBD1")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD1, (Int64)value);
return;
}
if (name == "DBD2")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD2, (Int64)value);
return;
}
if (name == "DBD3")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD3, (Int64)value);
return;
}
if (name == "DBD4")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD4, (Int64)value);
return;
}
if (name == "DBD5")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD5, (Int64)value);
return;
}
if (name == "DBD6")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD6, (Int64)value);
return;
}
if (name == "DBD7")
{
Marshal.WriteInt64(this.RawPtr, (int)IA64Offsets.DbD7, (Int64)value);
return;
}
}
throw new InvalidOperationException(String.Format("Register '{0}' is not in the context", name));
}
#region IDisposable Members
public void Dispose()
{
this.Dispose(true);
}
public void Dispose(bool supressPendingFinalizer)
{
this.m_imageFileMachine = 0;
this.m_platform = Platform.None;
Marshal.FreeHGlobal(this.m_rawPtr);
this.m_size = 0;
this.m_rawPtr = IntPtr.Zero;
if (supressPendingFinalizer)
{
GC.SuppressFinalize(this);
}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Input.StateChanges;
using osu.Framework.Logging;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.API;
using osu.Game.Online.Spectator;
using osu.Game.Replays;
using osu.Game.Replays.Legacy;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Tests.Visual.UserInterface;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneSpectatorPlayback : OsuManualInputManagerTestScene
{
protected override bool UseOnlineAPI => true;
private TestRulesetInputManager playbackManager;
private TestRulesetInputManager recordingManager;
private Replay replay;
private readonly IBindableList<int> users = new BindableList<int>();
private TestReplayRecorder recorder;
private readonly ManualClock manualClock = new ManualClock();
private OsuSpriteText latencyDisplay;
private TestFramedReplayInputHandler replayHandler;
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private SpectatorClient spectatorClient { get; set; }
[Cached]
private GameplayState gameplayState = new GameplayState(new Beatmap(), new OsuRuleset(), Array.Empty<Mod>());
[SetUp]
public void SetUp() => Schedule(() =>
{
replay = new Replay();
users.BindTo(spectatorClient.PlayingUsers);
users.BindCollectionChanged((obj, args) =>
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
Debug.Assert(args.NewItems != null);
foreach (int user in args.NewItems)
{
if (user == api.LocalUser.Value.Id)
spectatorClient.WatchUser(user);
}
break;
case NotifyCollectionChangedAction.Remove:
Debug.Assert(args.OldItems != null);
foreach (int user in args.OldItems)
{
if (user == api.LocalUser.Value.Id)
spectatorClient.StopWatchingUser(user);
}
break;
}
}, true);
spectatorClient.OnNewFrames += onNewFrames;
Add(new GridContainer
{
RelativeSizeAxes = Axes.Both,
Content = new[]
{
new Drawable[]
{
recordingManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
{
Recorder = recorder = new TestReplayRecorder
{
ScreenSpaceToGamefield = pos => recordingManager.ToLocalSpace(pos),
},
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Brown,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Text = "Sending",
Scale = new Vector2(3),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new TestInputConsumer()
}
},
}
},
new Drawable[]
{
playbackManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique)
{
Clock = new FramedClock(manualClock),
ReplayInputHandler = replayHandler = new TestFramedReplayInputHandler(replay)
{
GamefieldToScreenSpace = pos => playbackManager.ToScreenSpace(pos),
},
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
Colour = Color4.DarkBlue,
RelativeSizeAxes = Axes.Both,
},
new OsuSpriteText
{
Text = "Receiving",
Scale = new Vector2(3),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
new TestInputConsumer()
}
},
}
}
}
});
Add(latencyDisplay = new OsuSpriteText());
});
private void onNewFrames(int userId, FrameDataBundle frames)
{
Logger.Log($"Received {frames.Frames.Count()} new frames ({string.Join(',', frames.Frames.Select(f => ((int)f.Time).ToString()))})");
foreach (var legacyFrame in frames.Frames)
{
var frame = new TestReplayFrame();
frame.FromLegacy(legacyFrame, null);
replay.Frames.Add(frame);
}
}
[Test]
public void TestBasic()
{
}
private double latency = SpectatorClient.TIME_BETWEEN_SENDS;
protected override void Update()
{
base.Update();
if (latencyDisplay == null) return;
// propagate initial time value
if (manualClock.CurrentTime == 0)
{
manualClock.CurrentTime = Time.Current;
return;
}
if (!replayHandler.HasFrames)
return;
var lastFrame = replay.Frames.LastOrDefault();
// this isn't perfect as we basically can't be aware of the rate-of-send here (the streamer is not sending data when not being moved).
// in gameplay playback, the case where NextFrame is null would pause gameplay and handle this correctly; it's strictly a test limitation / best effort implementation.
if (lastFrame != null)
latency = Math.Max(latency, Time.Current - lastFrame.Time);
latencyDisplay.Text = $"latency: {latency:N1}";
double proposedTime = Time.Current - latency + Time.Elapsed;
// this will either advance by one or zero frames.
double? time = replayHandler.SetFrameFromTime(proposedTime);
if (time == null)
return;
manualClock.CurrentTime = time.Value;
}
[TearDownSteps]
public void TearDown()
{
AddStep("stop recorder", () =>
{
recorder.Expire();
spectatorClient.OnNewFrames -= onNewFrames;
});
}
public class TestFramedReplayInputHandler : FramedReplayInputHandler<TestReplayFrame>
{
public TestFramedReplayInputHandler(Replay replay)
: base(replay)
{
}
public override void CollectPendingInputs(List<IInput> inputs)
{
inputs.Add(new MousePositionAbsoluteInput { Position = GamefieldToScreenSpace(CurrentFrame?.Position ?? Vector2.Zero) });
inputs.Add(new ReplayState<TestAction> { PressedActions = CurrentFrame?.Actions ?? new List<TestAction>() });
}
}
public class TestInputConsumer : CompositeDrawable, IKeyBindingHandler<TestAction>
{
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parent.ReceivePositionalInputAt(screenSpacePos);
private readonly Box box;
public TestInputConsumer()
{
Size = new Vector2(30);
Origin = Anchor.Centre;
InternalChildren = new Drawable[]
{
box = new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
};
}
protected override bool OnMouseMove(MouseMoveEvent e)
{
Position = e.MousePosition;
return base.OnMouseMove(e);
}
public bool OnPressed(KeyBindingPressEvent<TestAction> e)
{
box.Colour = Color4.White;
return true;
}
public void OnReleased(KeyBindingReleaseEvent<TestAction> e)
{
box.Colour = Color4.Black;
}
}
public class TestRulesetInputManager : RulesetInputManager<TestAction>
{
public TestRulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
: base(ruleset, variant, unique)
{
}
protected override KeyBindingContainer<TestAction> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique)
=> new TestKeyBindingContainer();
internal class TestKeyBindingContainer : KeyBindingContainer<TestAction>
{
public override IEnumerable<IKeyBinding> DefaultKeyBindings => new[]
{
new KeyBinding(InputKey.MouseLeft, TestAction.Down),
};
}
}
public class TestReplayFrame : ReplayFrame, IConvertibleReplayFrame
{
public Vector2 Position;
public List<TestAction> Actions = new List<TestAction>();
public TestReplayFrame(double time, Vector2 position, params TestAction[] actions)
: base(time)
{
Position = position;
Actions.AddRange(actions);
}
public TestReplayFrame()
{
}
public void FromLegacy(LegacyReplayFrame currentFrame, IBeatmap beatmap, ReplayFrame lastFrame = null)
{
Position = currentFrame.Position;
Time = currentFrame.Time;
if (currentFrame.MouseLeft)
Actions.Add(TestAction.Down);
}
public LegacyReplayFrame ToLegacy(IBeatmap beatmap)
{
ReplayButtonState state = ReplayButtonState.None;
if (Actions.Contains(TestAction.Down))
state |= ReplayButtonState.Left1;
return new LegacyReplayFrame(Time, Position.X, Position.Y, state);
}
}
public enum TestAction
{
Down,
}
internal class TestReplayRecorder : ReplayRecorder<TestAction>
{
public TestReplayRecorder()
: base(new Score { ScoreInfo = { BeatmapInfo = new BeatmapInfo() } })
{
}
protected override ReplayFrame HandleFrame(Vector2 mousePosition, List<TestAction> actions, ReplayFrame previousFrame)
{
return new TestReplayFrame(Time.Current, mousePosition, actions.ToArray());
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.ToolManifest;
using Microsoft.DotNet.ToolPackage;
using Microsoft.DotNet.Tools.Test.Utilities;
using Microsoft.DotNet.Tools.Tests.ComponentMocks;
using Microsoft.DotNet.Tools.Tests.Utilities;
using Microsoft.DotNet.Tools.Tool.Restore;
using Microsoft.Extensions.DependencyModel.Tests;
using Microsoft.Extensions.EnvironmentAbstractions;
using Microsoft.TemplateEngine.Cli;
using NuGet.Frameworks;
using NuGet.Versioning;
using Xunit;
using LocalizableStrings = Microsoft.DotNet.Tools.Tool.Restore.LocalizableStrings;
using Parser = Microsoft.DotNet.Cli.Parser;
namespace Microsoft.DotNet.Tests.Commands.Tool
{
public class ToolRestoreCommandTests
{
private readonly IFileSystem _fileSystem;
private readonly IToolPackageStore _toolPackageStore;
private readonly ToolPackageInstallerMock _toolPackageInstallerMock;
private readonly AppliedOption _appliedCommand;
private readonly ParseResult _parseResult;
private readonly BufferedReporter _reporter;
private readonly string _temporaryDirectory;
private readonly string _pathToPlacePackages;
private readonly ILocalToolsResolverCache _localToolsResolverCache;
private readonly PackageId _packageIdA = new PackageId("local.tool.console.a");
private readonly PackageId _packageIdWithCommandNameCollisionWithA =
new PackageId("command.name.collision.with.package.a");
private readonly NuGetVersion _packageVersionWithCommandNameCollisionWithA;
private readonly NuGetVersion _packageVersionA;
private readonly ToolCommandName _toolCommandNameA = new ToolCommandName("a");
private readonly PackageId _packageIdB = new PackageId("local.tool.console.B");
private readonly NuGetVersion _packageVersionB;
private readonly ToolCommandName _toolCommandNameB = new ToolCommandName("b");
private readonly DirectoryPath _nugetGlobalPackagesFolder;
private int _installCalledCount = 0;
public ToolRestoreCommandTests()
{
_packageVersionA = NuGetVersion.Parse("1.0.4");
_packageVersionWithCommandNameCollisionWithA = NuGetVersion.Parse("1.0.9");
_packageVersionB = NuGetVersion.Parse("1.0.4");
_reporter = new BufferedReporter();
_fileSystem = new FileSystemMockBuilder().UseCurrentSystemTemporaryDirectory().Build();
_nugetGlobalPackagesFolder = new DirectoryPath(NuGetGlobalPackagesFolder.GetLocation());
_temporaryDirectory = _fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath;
_pathToPlacePackages = Path.Combine(_temporaryDirectory, "pathToPlacePackage");
ToolPackageStoreMock toolPackageStoreMock =
new ToolPackageStoreMock(new DirectoryPath(_pathToPlacePackages), _fileSystem);
_toolPackageStore = toolPackageStoreMock;
_toolPackageInstallerMock = new ToolPackageInstallerMock(
_fileSystem,
_toolPackageStore,
new ProjectRestorerMock(
_fileSystem,
_reporter,
new List<MockFeed>
{
new MockFeed
{
Type = MockFeedType.ImplicitAdditionalFeed,
Packages = new List<MockFeedPackage>
{
new MockFeedPackage
{
PackageId = _packageIdA.ToString(),
Version = _packageVersionA.ToNormalizedString(),
ToolCommandName = _toolCommandNameA.ToString()
},
new MockFeedPackage
{
PackageId = _packageIdB.ToString(),
Version = _packageVersionB.ToNormalizedString(),
ToolCommandName = _toolCommandNameB.ToString()
},
new MockFeedPackage
{
PackageId = _packageIdWithCommandNameCollisionWithA.ToString(),
Version = _packageVersionWithCommandNameCollisionWithA.ToNormalizedString(),
ToolCommandName = "A"
}
}
}
}),
installCallback: () => _installCalledCount++);
ParseResult result = Parser.Instance.Parse("dotnet tool restore");
_appliedCommand = result["dotnet"]["tool"]["restore"];
Cli.CommandLine.Parser parser = Parser.Instance;
_parseResult = parser.ParseFrom("dotnet tool", new[] {"restore"});
_localToolsResolverCache
= new LocalToolsResolverCache(
_fileSystem,
new DirectoryPath(Path.Combine(_temporaryDirectory, "cache")),
1);
}
[Fact]
public void WhenRunItCanSaveCommandsToCache()
{
IToolManifestFinder manifestFinder =
new MockManifestFinder(new[]
{
new ToolManifestPackage(_packageIdA, _packageVersionA,
new[] {_toolCommandNameA},
new DirectoryPath(_temporaryDirectory)),
new ToolManifestPackage(_packageIdB, _packageVersionB,
new[] {_toolCommandNameB},
new DirectoryPath(_temporaryDirectory))
});
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
toolRestoreCommand.Execute().Should().Be(0);
_localToolsResolverCache.TryLoad(
new RestoredCommandIdentifier(
_packageIdA,
_packageVersionA,
NuGetFramework.Parse(BundledTargetFramework.GetTargetFrameworkMoniker()),
Constants.AnyRid,
_toolCommandNameA), out RestoredCommand restoredCommand)
.Should().BeTrue();
_fileSystem.File.Exists(restoredCommand.Executable.Value)
.Should().BeTrue($"Cached command should be found at {restoredCommand.Executable.Value}");
}
[Fact]
public void WhenRunItCanSaveCommandsToCacheAndShowSuccessMessage()
{
IToolManifestFinder manifestFinder =
new MockManifestFinder(new[]
{
new ToolManifestPackage(_packageIdA, _packageVersionA,
new[] {_toolCommandNameA},
new DirectoryPath(_temporaryDirectory)),
new ToolManifestPackage(_packageIdB, _packageVersionB,
new[] {_toolCommandNameB},
new DirectoryPath(_temporaryDirectory))
});
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
toolRestoreCommand.Execute().Should().Be(0);
_reporter.Lines.Should().Contain(l => l.Contains(string.Format(
LocalizableStrings.RestoreSuccessful, _packageIdA,
_packageVersionA.ToNormalizedString(), _toolCommandNameA)));
_reporter.Lines.Should().Contain(l => l.Contains(string.Format(
LocalizableStrings.RestoreSuccessful, _packageIdB,
_packageVersionB.ToNormalizedString(), _toolCommandNameB)));
_reporter.Lines.Should().Contain(l => l.Contains("\x1B[32m"),
"ansicolor code for green, message should be green");
}
[Fact]
public void WhenRestoredCommandHasTheSameCommandNameItThrows()
{
IToolManifestFinder manifestFinder =
new MockManifestFinder(new[]
{
new ToolManifestPackage(_packageIdA, _packageVersionA,
new[] {_toolCommandNameA},
new DirectoryPath(_temporaryDirectory)),
new ToolManifestPackage(_packageIdWithCommandNameCollisionWithA,
_packageVersionWithCommandNameCollisionWithA, new[] {_toolCommandNameA},
new DirectoryPath(_temporaryDirectory))
});
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
var allPossibleErrorMessage = new[]
{
string.Format(LocalizableStrings.PackagesCommandNameCollisionConclusion,
string.Join(Environment.NewLine,
new[]
{
"\t" + string.Format(LocalizableStrings.PackagesCommandNameCollisionForOnePackage,
_toolCommandNameA.Value,
_packageIdA.ToString()),
"\t" + string.Format(LocalizableStrings.PackagesCommandNameCollisionForOnePackage,
"A",
_packageIdWithCommandNameCollisionWithA.ToString())
})),
string.Format(LocalizableStrings.PackagesCommandNameCollisionConclusion,
string.Join(Environment.NewLine,
new[]
{
"\t" + string.Format(LocalizableStrings.PackagesCommandNameCollisionForOnePackage,
"A",
_packageIdWithCommandNameCollisionWithA.ToString()),
"\t" + string.Format(LocalizableStrings.PackagesCommandNameCollisionForOnePackage,
_toolCommandNameA.Value,
_packageIdA.ToString()),
})),
};
Action a = () => toolRestoreCommand.Execute();
a.ShouldThrow<ToolPackageException>()
.And.Message
.Should().BeOneOf(allPossibleErrorMessage, "Run in parallel, no order guarantee");
}
[Fact]
public void WhenSomePackageFailedToRestoreItCanRestorePartiallySuccessful()
{
IToolManifestFinder manifestFinder =
new MockManifestFinder(new[]
{
new ToolManifestPackage(_packageIdA, _packageVersionA,
new[] {_toolCommandNameA},
new DirectoryPath(_temporaryDirectory)),
new ToolManifestPackage(new PackageId("non-exists"), NuGetVersion.Parse("1.0.0"),
new[] {new ToolCommandName("non-exists")},
new DirectoryPath(_temporaryDirectory))
});
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
int executeResult = toolRestoreCommand.Execute();
_reporter.Lines.Should()
.Contain(l => l.Contains(string.Format(LocalizableStrings.PackageFailedToRestore,
"non-exists", "")));
_reporter.Lines.Should().Contain(l => l.Contains(LocalizableStrings.RestorePartiallyFailed));
executeResult.Should().Be(1);
_localToolsResolverCache.TryLoad(
new RestoredCommandIdentifier(
_packageIdA,
_packageVersionA,
NuGetFramework.Parse(BundledTargetFramework.GetTargetFrameworkMoniker()),
Constants.AnyRid,
_toolCommandNameA), out _)
.Should().BeTrue("Existing package will succeed despite other package failed");
}
[Fact]
public void ItShouldFailWhenPackageCommandNameDoesNotMatchManifestCommands()
{
ToolCommandName differentCommandNameA = new ToolCommandName("different-command-nameA");
ToolCommandName differentCommandNameB = new ToolCommandName("different-command-nameB");
IToolManifestFinder manifestFinder =
new MockManifestFinder(new[]
{
new ToolManifestPackage(_packageIdA, _packageVersionA,
new[] {differentCommandNameA, differentCommandNameB},
new DirectoryPath(_temporaryDirectory)),
});
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
toolRestoreCommand.Execute().Should().Be(1);
_reporter.Lines.Should()
.Contain(l =>
l.Contains(
string.Format(LocalizableStrings.CommandsMismatch,
"\"different-command-nameA\" \"different-command-nameB\"", _packageIdA, "\"a\"")));
}
[Fact]
public void WhenCannotFindManifestFileItPrintsWarning()
{
IToolManifestFinder realManifestFinderImplementationWithMockFinderSystem =
new ToolManifestFinder(new DirectoryPath(Path.GetTempPath()), _fileSystem, new FakeDangerousFileDetector());
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
realManifestFinderImplementationWithMockFinderSystem,
_localToolsResolverCache,
_fileSystem,
_reporter
);
toolRestoreCommand.Execute().Should().Be(0);
_reporter.Lines.Should()
.Contain(l =>
l.Contains(ToolManifest.LocalizableStrings.CannotFindAManifestFile));
}
[Fact]
public void WhenPackageIsRestoredAlreadyItWillNotRestoreItAgain()
{
IToolManifestFinder manifestFinder =
new MockManifestFinder(new[]
{
new ToolManifestPackage(_packageIdA, _packageVersionA,
new[] {_toolCommandNameA},
new DirectoryPath(_temporaryDirectory))
});
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
toolRestoreCommand.Execute();
var installCallCountBeforeTheSecondRestore = _installCalledCount;
toolRestoreCommand.Execute();
installCallCountBeforeTheSecondRestore.Should().BeGreaterThan(0);
_installCalledCount.Should().Be(installCallCountBeforeTheSecondRestore);
}
[Fact]
public void WhenPackageIsRestoredAlreadyButDllIsRemovedItRestoresAgain()
{
IToolManifestFinder manifestFinder =
new MockManifestFinder(new[]
{
new ToolManifestPackage(_packageIdA, _packageVersionA,
new[] {_toolCommandNameA},
new DirectoryPath(_temporaryDirectory))
});
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
toolRestoreCommand.Execute();
_fileSystem.Directory.Delete(_nugetGlobalPackagesFolder.Value, true);
var installCallCountBeforeTheSecondRestore = _installCalledCount;
toolRestoreCommand.Execute();
installCallCountBeforeTheSecondRestore.Should().BeGreaterThan(0);
_installCalledCount.Should().Be(installCallCountBeforeTheSecondRestore + 1);
}
[Fact]
public void WhenRunWithoutManifestFileItShouldPrintSpecificRestoreErrorMessage()
{
IToolManifestFinder manifestFinder =
new CannotFindManifestFinder();
ToolRestoreCommand toolRestoreCommand = new ToolRestoreCommand(_appliedCommand,
_parseResult,
_toolPackageInstallerMock,
manifestFinder,
_localToolsResolverCache,
_fileSystem,
_reporter
);
toolRestoreCommand.Execute().Should().Be(0);
_reporter.Lines.Should().Contain(l =>
l.Contains(Cli.Utils.AnsiColorExtensions.Yellow(LocalizableStrings.NoToolsWereRestored)));
}
private class MockManifestFinder : IToolManifestFinder
{
private readonly IReadOnlyCollection<ToolManifestPackage> _toReturn;
public MockManifestFinder(IReadOnlyCollection<ToolManifestPackage> toReturn)
{
_toReturn = toReturn;
}
public IReadOnlyCollection<ToolManifestPackage> Find(FilePath? filePath = null)
{
return _toReturn;
}
public FilePath FindFirst()
{
throw new NotImplementedException();
}
public IReadOnlyList<FilePath> FindByPackageId(PackageId packageId)
{
throw new NotImplementedException();
}
}
private class CannotFindManifestFinder : IToolManifestFinder
{
public IReadOnlyCollection<ToolManifestPackage> Find(FilePath? filePath = null)
{
throw new ToolManifestCannotBeFoundException("In test cannot find manifest");
}
public FilePath FindFirst()
{
throw new NotImplementedException();
}
public IReadOnlyList<FilePath> FindByPackageId(PackageId packageId)
{
throw new NotImplementedException();
}
}
}
}
| |
// 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.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis.Analyzer {
sealed class FunctionScope : InterpreterScope {
private ListParameterVariableDef _seqParameters;
private DictParameterVariableDef _dictParameters;
public readonly VariableDef ReturnValue;
public readonly CoroutineInfo Coroutine;
public readonly GeneratorInfo Generator;
public FunctionScope(
FunctionInfo function,
Node node,
InterpreterScope declScope,
IPythonProjectEntry declModule
)
: base(function, node, declScope) {
ReturnValue = new VariableDef();
if (Function.FunctionDefinition.IsCoroutine) {
Coroutine = new CoroutineInfo(function.ProjectState, declModule);
ReturnValue.AddTypes(function.ProjectEntry, Coroutine.SelfSet, false, declModule);
} else if (Function.FunctionDefinition.IsGenerator) {
Generator = new GeneratorInfo(function.ProjectState, declModule);
ReturnValue.AddTypes(function.ProjectEntry, Generator.SelfSet, false, declModule);
}
}
internal void AddReturnTypes(Node node, AnalysisUnit unit, IAnalysisSet types, bool enqueue = true) {
if (Coroutine != null) {
Coroutine.AddReturn(node, unit, types, enqueue);
} else if (Generator != null) {
Generator.AddReturn(node, unit, types, enqueue);
} else {
ReturnValue.MakeUnionStrongerIfMoreThan(unit.ProjectState.Limits.ReturnTypes, types);
ReturnValue.AddTypes(unit, types, enqueue);
}
}
internal void EnsureParameters(FunctionAnalysisUnit unit) {
var astParams = Function.FunctionDefinition.Parameters;
for (int i = 0; i < astParams.Count; ++i) {
VariableDef param;
if (!TryGetVariable(astParams[i].Name, out param)) {
if (astParams[i].Kind == ParameterKind.List) {
param = _seqParameters = _seqParameters ?? new ListParameterVariableDef(unit, astParams[i]);
} else if (astParams[i].Kind == ParameterKind.Dictionary) {
param = _dictParameters = _dictParameters ?? new DictParameterVariableDef(unit, astParams[i]);
} else {
param = new LocatedVariableDef(unit.ProjectEntry, astParams[i]);
}
AddVariable(astParams[i].Name, param);
}
}
}
internal void AddParameterReferences(AnalysisUnit caller, NameExpression[] names) {
foreach (var name in names) {
VariableDef param;
if (name != null && TryGetVariable(name.Name, out param)) {
param.AddReference(name, caller);
}
}
}
internal bool UpdateParameters(FunctionAnalysisUnit unit, ArgumentSet others, bool enqueue = true, FunctionScope scopeWithDefaultParameters = null) {
EnsureParameters(unit);
var astParams = Function.FunctionDefinition.Parameters;
bool added = false;
var entry = unit.DependencyProject;
var state = unit.ProjectState;
var limits = state.Limits;
for (int i = 0; i < others.Args.Length && i < astParams.Count; ++i) {
VariableDef param;
if (!TryGetVariable(astParams[i].Name, out param)) {
Debug.Assert(false, "Parameter " + astParams[i].Name + " has no variable in this scope");
param = AddVariable(astParams[i].Name);
}
param.MakeUnionStrongerIfMoreThan(limits.NormalArgumentTypes, others.Args[i]);
added |= param.AddTypes(entry, others.Args[i], false, unit.ProjectEntry);
}
if (_seqParameters != null) {
_seqParameters.List.MakeUnionStrongerIfMoreThan(limits.ListArgumentTypes, others.SequenceArgs);
added |= _seqParameters.List.AddTypes(unit, new[] { others.SequenceArgs });
}
if (_dictParameters != null) {
_dictParameters.Dict.MakeUnionStrongerIfMoreThan(limits.DictArgumentTypes, others.DictArgs);
added |= _dictParameters.Dict.AddTypes(Function.FunctionDefinition, unit, state.GetConstant(""), others.DictArgs);
}
if (scopeWithDefaultParameters != null) {
for (int i = 0; i < others.Args.Length && i < astParams.Count; ++i) {
VariableDef defParam, param;
if (TryGetVariable(astParams[i].Name, out param) &&
!param.HasTypes &&
scopeWithDefaultParameters.TryGetVariable(astParams[i].Name, out defParam)) {
param.MakeUnionStrongerIfMoreThan(
limits.NormalArgumentTypes,
defParam.GetTypesNoCopy(unit, AnalysisValue.DeclaringModule)
);
added |= param.AddTypes(entry, defParam.GetTypesNoCopy(unit, AnalysisValue.DeclaringModule), false, unit.ProjectEntry);
}
}
}
if (enqueue && added) {
unit.Enqueue();
}
return added;
}
public FunctionInfo Function {
get {
return (FunctionInfo)AnalysisValue;
}
}
public override IEnumerable<KeyValuePair<string, VariableDef>> GetAllMergedVariables() {
if (this != Function.AnalysisUnit.Scope) {
// Many scopes reference one FunctionInfo, which references one
// FunctionAnalysisUnit which references one scope. Since we
// are not that scope, we won't look at _allCalls for other
// variables.
return AllVariables;
}
var scopes = new HashSet<InterpreterScope>();
var result = AllVariables;
if (Function._allCalls != null) {
foreach (var callUnit in Function._allCalls.Values) {
scopes.Add(callUnit.Scope);
}
scopes.Remove(this);
foreach (var scope in scopes) {
result = result.Concat(scope.GetAllMergedVariables());
}
}
return result;
}
public override IEnumerable<VariableDef> GetMergedVariables(string name) {
VariableDef res;
FunctionScope fnScope;
var nodes = new HashSet<Node>();
var seen = new HashSet<InterpreterScope>();
var queue = new Queue<FunctionScope>();
queue.Enqueue(this);
while (queue.Any()) {
var scope = queue.Dequeue();
if (scope == null || !seen.Add(scope)) {
continue;
}
if (scope.Node == Node && scope.TryGetVariable(name, out res)) {
yield return res;
}
if (scope.Function._allCalls != null) {
foreach (var callUnit in scope.Function._allCalls.Values) {
fnScope = callUnit.Scope as FunctionScope;
if (fnScope != null && fnScope != this) {
queue.Enqueue(fnScope);
}
}
}
foreach (var keyValue in scope.AllNodeScopes.Where(kv => nodes.Contains(kv.Key))) {
if ((fnScope = keyValue.Value as FunctionScope) != null) {
queue.Enqueue(fnScope);
}
}
if ((fnScope = scope.OuterScope as FunctionScope) != null) {
nodes.Add(scope.Node);
queue.Enqueue(fnScope);
}
}
}
public override IEnumerable<AnalysisValue> GetMergedAnalysisValues() {
yield return AnalysisValue;
if (Function._allCalls != null) {
foreach (var callUnit in Function._allCalls.Values) {
if (callUnit.Scope != this) {
yield return callUnit.Scope.AnalysisValue;
}
}
}
}
public override int GetBodyStart(PythonAst ast) {
return ast.IndexToLocation(((FunctionDefinition)Node).HeaderIndex).Index;
}
public override string Name {
get { return Function.FunctionDefinition.Name; }
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenMetaverse.Messages.Linden;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
using System.IO;
using System.IO.Compression;
namespace OpenSim.Region.CoreModules.Capabilities
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class EventQueueGetModule : IEventQueue, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <value>
/// Debug level.
/// </value>
public int DebugLevel { get; set; }
protected Scene m_Scene;
private const int m_timeout = 15 * 1000; // 15 seconds
private Dictionary<UUID, EventQueueGetRequestHandler> queues =
new Dictionary<UUID, EventQueueGetRequestHandler>();
#region INonSharedRegionModule methods
public virtual void Initialise(IConfigSource config)
{
MainConsole.Instance.Commands.AddCommand(
"Comms",
false,
"debug eq",
"debug eq [0|1]",
"Turn on event queue debugging",
"debug eq 1 will turn on event queue debugging. This will log all outgoing event queue messages to clients.\n"
+ "debug eq 0 will turn off event queue debugging.",
HandleDebugEq);
}
public void PostInitialise()
{
}
public virtual void Close()
{
}
public void AddRegion(Scene scene)
{
m_Scene = scene;
}
public void RemoveRegion(Scene scene)
{
m_Scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
m_Scene.EventManager.OnDeregisterCaps -= OnDeregisterCaps;
}
public void RegionLoaded(Scene scene)
{
m_Scene.RegisterModuleInterface<IEventQueue>(this);
m_Scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_Scene.EventManager.OnDeregisterCaps += OnDeregisterCaps;
}
public virtual string Name
{
get { return "EventQueueGetModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
protected void HandleDebugEq(string module, string[] args)
{
int debugLevel;
if (!(args.Length == 3 && int.TryParse(args[2], out debugLevel)))
{
MainConsole.Instance.OutputFormat("Usage: debug eq [0|1]");
}
else
{
DebugLevel = debugLevel;
MainConsole.Instance.OutputFormat(
"Set event queue debug level to {0} in {1}", DebugLevel, m_Scene.RegionInfo.RegionName);
lock (queues)
{
foreach (EventQueueGetRequestHandler handler in new List<EventQueueGetRequestHandler>(queues.Values))
{
handler.DebugLevel = debugLevel;
}
}
}
}
public void OnRegisterCaps(UUID agentID, Caps caps)
{
m_log.DebugFormat("[EVENTQUEUE]: Register caps for client {0} in region {1}", agentID, m_Scene.RegionInfo.RegionName);
lock (queues)
{
EventQueueGetRequestHandler queue;
if (queues.TryGetValue(agentID, out queue) == true)
{
// shouldn't happen
m_log.ErrorFormat("[EVENTQUEUE]: OnRegisterCaps and an EQ already exists for client {0} in region {1}!", agentID, m_Scene.RegionInfo.RegionName);
}
else
{
string capsUrl = "/CAPS/EQG/" + UUID.Random().ToString() + "/";
queue = new EventQueueGetRequestHandler("POST", capsUrl, agentID, caps, DebugLevel);
queues.Add(agentID, queue);
}
caps.RegisterHandler("EventQueueGet", queue);
}
}
public void OnDeregisterCaps(UUID AgentID, Caps caps)
{
m_log.DebugFormat("[EVENTQUEUE]: Deregister caps for client {0} in region {1}", AgentID, m_Scene.RegionInfo.RegionName);
lock (queues)
{
caps.DeregisterHandler("EventQueueGet");
// If there is a posted request signal it. We'll send a 404 in the handler
EventQueueGetRequestHandler queue;
if (queues.TryGetValue(AgentID, out queue) == true)
{
queues.Remove(AgentID);
queue.DumpQueue();
}
}
}
#region IEventQueue Members
public bool Enqueue(OSD ev, UUID avatarID)
{
return EnqueueWithPriority(ev, avatarID, false);
}
private bool EnqueueWithPriority(OSD ev, UUID avatarID, bool highPriority)
{
EventQueueGetRequestHandler queue = null;
//m_log.DebugFormat("[EVENTQUEUE]: Enqueuing event for {0} in region {1}", avatarID, m_scene.RegionInfo.RegionName);
lock (queues)
{
if (queues.TryGetValue(avatarID, out queue) != true)
{
m_log.ErrorFormat("[EVENTQUEUE]: Could not enqueue request for {0}, queue for avatar not found", avatarID);
return (false);
}
}
queue.Enqueue(ev, highPriority);
return (true);
}
public void DisableSimulator(ulong handle, UUID avatarID)
{
OSD item = EventQueueHelper.DisableSimulator(handle);
Enqueue(item, avatarID);
}
public virtual bool EnableSimulator(ulong handle, IPEndPoint endPoint, UUID avatarID)
{
OSD item = EventQueueHelper.EnableSimulator(handle, endPoint);
return EnqueueWithPriority(item, avatarID, true);
}
public virtual bool EstablishAgentCommunication(UUID avatarID, IPEndPoint endPoint, string capsPath)
{
OSD item = EventQueueHelper.EstablishAgentCommunication(avatarID, endPoint.ToString(), capsPath);
return EnqueueWithPriority(item, avatarID, true);
}
public virtual bool TeleportFinishEvent(ulong regionHandle, byte simAccess,
IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL,
UUID avatarID)
{
OSD item = EventQueueHelper.TeleportFinishEvent(regionHandle, simAccess, regionExternalEndPoint,
locationID, flags, capsURL, avatarID);
return EnqueueWithPriority(item, avatarID, true);
}
public virtual bool CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint,
string capsURL, UUID avatarID, UUID sessionID)
{
OSD item = EventQueueHelper.CrossRegion(handle, pos, lookAt, newRegionExternalEndPoint,
capsURL, avatarID, sessionID);
return EnqueueWithPriority(item, avatarID, true);
}
public void ChatterboxInvitation(UUID sessionID, string sessionName,
UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog,
uint timeStamp, bool offline, int parentEstateID, Vector3 position,
uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket)
{
OSD item = EventQueueHelper.ChatterboxInvitation(sessionID, sessionName, fromAgent, message, toAgent, fromName, dialog,
timeStamp, offline, parentEstateID, position, ttl, transactionID,
fromGroup, binaryBucket);
Enqueue(item, toAgent);
//m_log.InfoFormat("########### eq ChatterboxInvitation #############\n{0}", item);
}
public void ChatterBoxSessionAgentListUpdates(UUID sessionID, UUID fromAgent, UUID toAgent, bool canVoiceChat,
bool isModerator, bool textMute, byte dialog)
{
OSD item = EventQueueHelper.ChatterBoxSessionAgentListUpdates(sessionID, fromAgent, canVoiceChat,
isModerator, textMute, dialog);
Enqueue(item, toAgent);
//m_log.InfoFormat("########### eq ChatterBoxSessionAgentListUpdates #############\n{0}", item);
}
public void ParcelProperties(ParcelPropertiesMessage parcelPropertiesMessage, UUID avatarID)
{
OSD item = EventQueueHelper.ParcelProperties(parcelPropertiesMessage);
Enqueue(item, avatarID);
}
public void GroupMembership(AgentGroupDataUpdatePacket groupUpdate, UUID avatarID)
{
OSD item = EventQueueHelper.GroupMembership(groupUpdate);
Enqueue(item, avatarID);
}
public void ScriptRunning(UUID objectID, UUID itemID, bool running, bool mono, UUID avatarID)
{
OSD item = EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, running, mono);
Enqueue(item, avatarID);
}
public void QueryReply(PlacesReplyPacket groupUpdate, UUID avatarID)
{
OSD item = EventQueueHelper.PlacesQuery(groupUpdate);
Enqueue(item, avatarID);
}
public OSD BuildEvent(string eventName, OSD eventBody)
{
return EventQueueHelper.BuildEvent(eventName, eventBody);
}
public void PartPhysicsProperties(uint localID, byte physhapetype,
float density, float friction, float bounce, float gravmod, UUID avatarID)
{
OSD item = EventQueueHelper.PartPhysicsProperties(localID, physhapetype,
density, friction, bounce, gravmod);
Enqueue(item, avatarID);
}
#endregion
protected class EventQueueGetRequestHandler : BaseRequestHandler, IAsyncRequestHandler
{
private object m_eqLock;
private readonly UUID m_agentID;
private readonly Caps m_Caps;
private Queue<OSD> m_highPriorityItems;
private Queue<OSD> m_Items;
private AsyncHttpRequest m_Request;
private int m_SequenceNumber;
public EventQueueGetRequestHandler(string httpMethod, string path, UUID agentID, Caps caps, int debugLevel)
: base(httpMethod, path, "EventQueueGetHandler", "AsyncRequest")
{
m_eqLock = new object();
m_agentID = agentID;
m_Caps = caps;
m_highPriorityItems = new Queue<OSD>();
m_Items = new Queue<OSD>();
Random rnd = new Random(Environment.TickCount);
m_SequenceNumber = rnd.Next(30000000);
DebugLevel = debugLevel;
}
public int DebugLevel { get; set; }
public bool isQueueValid
{
get { return (m_Items != null); }
}
private void TimeoutHandler(AsyncHttpRequest pRequest)
{
UUID sessionid = pRequest.AgentID;
Hashtable eventsToSend = null;
lock (m_eqLock)
{
if (isQueueValid == false)
return;
if (m_Request == pRequest)
{
m_Request = null;
eventsToSend = GetEvents(pRequest);
}
}
if (eventsToSend != null)
pRequest.SendResponse(eventsToSend);
}
public void Handle(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
AsyncHttpRequest pendingRequest = null;
AsyncHttpRequest eventQueueRequest =
new AsyncHttpRequest(server, httpRequest, httpResponse, m_agentID, TimeoutHandler, m_timeout);
Hashtable responseToSend = null;
lock (m_eqLock)
{
if (!isQueueValid)
{
m_log.ErrorFormat("[EVENTQUEUE]: HandleRequest for {0} failed, isQueueValid == false", m_agentID);
m_Request = null;
return;
}
pendingRequest = m_Request;
m_Request = eventQueueRequest;
if ((pendingRequest == null) && (m_highPriorityItems.Count > 0 || m_Items.Count > 0))
{
pendingRequest = m_Request;
m_Request = null;
responseToSend = GetEvents(pendingRequest);
}
}
if (responseToSend != null)
{
pendingRequest.SendResponse(responseToSend);
}
}
public void Enqueue(OSD ev, bool highPriority)
{
AsyncHttpRequest pendingRequest = null;
Hashtable responseToSend = null;
lock (m_eqLock)
{
if (isQueueValid == false)
{
m_log.ErrorFormat("[EVENTQUEUE]: Unable to enqueue new event. isQueueValid == false");
return;
}
if (highPriority)
{
m_highPriorityItems.Enqueue(ev);
}
else
{
m_Items.Enqueue(ev);
}
if (m_Request != null)
{
pendingRequest = m_Request;
m_Request = null;
responseToSend = GetEvents(pendingRequest);
}
}
if (responseToSend != null)
{
pendingRequest.SendResponse(responseToSend);
}
}
public void DumpQueue()
{
AsyncHttpRequest pendingRequest = null;
Hashtable responseToSend = null;
lock (m_eqLock)
{
if (isQueueValid == true)
{
m_highPriorityItems.Clear();
m_highPriorityItems = null;
m_Items.Clear();
m_Items = null;
}
// If a request is pending signal it. The response handler will send a 404
if (m_Request != null)
{
pendingRequest = m_Request;
m_Request = null;
responseToSend = GetEvents(pendingRequest);
}
}
if (responseToSend != null)
{
pendingRequest.SendResponse(responseToSend);
}
}
public Hashtable GetEvents(AsyncHttpRequest pRequest)
{
Hashtable responsedata = new Hashtable();
lock (m_eqLock) // should already be locked on entry to this function
{
// If the queue is gone we're being cleaned up. Send a 404
if (isQueueValid == false)
{
responsedata["int_response_code"] = 404;
responsedata["content_type"] = "text/plain";
responsedata["str_response_string"] = "Not Found";
responsedata["error_status_text"] = "Not Found";
return responsedata;
}
if (m_highPriorityItems.Count == 0 && m_Items.Count == 0)
{
/*
** The format of this response is important. If its not setup this way the client will
** stop polling for new events. http://wiki.secondlife.com/wiki/EventQueueGet
*/
responsedata["int_response_code"] = 502;
responsedata["content_type"] = "text/plain";
responsedata["str_response_string"] = "Upstream error: ";
responsedata["error_status_text"] = "Upstream error:";
responsedata["http_protocol_version"] = "1.0";
if (DebugLevel > 0)
{
m_log.DebugFormat(
"[EVENT QUEUE GET MODULE]: Eq TIMEOUT/502 to client {0} in region {1}",
m_agentID,
m_Caps.RegionName);
}
return responsedata;
}
// Return the events we have queued
OSDArray array = new OSDArray();
//if there are no high priority items, then dequeue the normal
//priority items
if (!DequeueIntoArray(m_highPriorityItems, array))
{
DequeueIntoArray(m_Items, array);
}
// m_log.ErrorFormat("[EVENTQUEUE]: Responding with {0} events to viewer.", array.Count.ToString());
OSDMap events = new OSDMap();
events.Add("events", array);
events.Add("id", new OSDInteger(m_SequenceNumber));
responsedata["int_response_code"] = 200;
responsedata["content_type"] = "application/xml";
var eventData = OSDParser.SerializeLLSDXmlString(events);
responsedata["str_response_string"] = eventData;
//warn at 512kB of uncompressed data
const int WARN_THRESHOLD = 524288;
if (eventData.Length > WARN_THRESHOLD)
{
m_log.WarnFormat("[EVENTQUEUE]: Very large message being enqueued. Size: {0}, Items{1}. Contents: ",
eventData.Length, array.Count);
foreach (var e in array)
{
OSDMap evt = (OSDMap)e;
m_log.WarnFormat("[EVENTQUEUE]: {0}", evt["message"]);
}
}
return responsedata;
}
}
private bool DequeueIntoArray(Queue<OSD> queue, OSDArray array)
{
OSD element = null;
bool hadItems = queue.Count > 0;
while (queue.Count > 0)
{
element = queue.Dequeue();
array.Add(element);
m_SequenceNumber++;
if ((DebugLevel > 0) && (element is OSDMap))
{
OSDMap ev = (OSDMap)element;
m_log.DebugFormat(
"[EVENT QUEUE GET MODULE]: Eq OUT {0} to client {1} in region {2}",
ev["message"],
m_agentID,
m_Caps.RegionName);
}
}
return hadItems;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace FWWebService.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NMock2;
using NUnit.Framework;
using System.Reflection;
using System;
namespace OpenQA.Selenium.Support.UI
{
[TestFixture]
public class SelectTests
{
private Mockery mocks;
private IWebElement webElement;
[SetUp]
public void SetUp()
{
mocks = new Mockery();
webElement = mocks.NewMock<IWebElement>();
}
[Test]
public void ThrowUnexpectedTagNameExceptionWhenNotSelectTag()
{
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("form"));
Assert.Throws<UnexpectedTagNameException>(() => new SelectElement(webElement));
}
[Test]
public void CanCreateNewInstanceOfSelectWithNormalSelectElement()
{
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Assert.IsFalse(new SelectElement(webElement).IsMultiple);
}
[Test]
public void CanCreateNewInstanceOfSelectWithMultipleSelectElement()
{
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Assert.IsTrue(new SelectElement(webElement).IsMultiple);
}
[Test]
public void CanGetListOfOptions()
{
IList<IWebElement> options = new List<IWebElement>();
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
Assert.AreEqual(options, new SelectElement(webElement).Options);
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanGetSingleSelectedOption()
{
IWebElement selected = mocks.NewMock<IWebElement>();
IWebElement notSelected = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(selected = mocks.NewMock<IWebElement>());
options.Add(notSelected = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Stub.On(selected).GetProperty("Selected").Will(Return.Value(true));
Stub.On(notSelected).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
IWebElement option = new SelectElement(webElement).SelectedOption;
Assert.AreEqual(selected, option);
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanGetAllSelectedOptions()
{
IWebElement selected = mocks.NewMock<IWebElement>();
IWebElement notSelected = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(selected = mocks.NewMock<IWebElement>());
options.Add(notSelected = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Stub.On(selected).GetProperty("Selected").Will(Return.Value(true));
Stub.On(notSelected).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
IList<IWebElement> returnedOption = new SelectElement(webElement).AllSelectedOptions;
Assert.That(returnedOption.Count == 1);
Assert.AreEqual(selected, returnedOption[0]);
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanSetSingleOptionSelectedByText()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(webElement).Method("FindElements").With(By.XPath(".//option[normalize-space(.) = \"Select Me\"]")).Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).SelectByText("Select Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanSetSingleOptionSelectedByValue()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).SelectByValue("Select Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanSetSingleOptionSelectedByIndex()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Expect.Once.On(option1).Method("GetAttribute").Will(Return.Value("2"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).SelectByIndex(2);
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanSetMultipleOptionSelectedByText()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IWebElement option2 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
options.Add(option2 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(option2).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option2).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).SelectByText("Select Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanSetMultipleOptionSelectedByValue()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IWebElement option2 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
options.Add(option2 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(option2).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option2).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).SelectByValue("Select Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanSetMultipleOptionSelectedByIndex()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IWebElement option2 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
options.Add(option2 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Expect.Once.On(option1).Method("GetAttribute").Will(Return.Value("2"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(option2).Method("GetAttribute").Will(Return.Value("2"));
Expect.Once.On(option2).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(option2).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).SelectByIndex(2);
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanDeselectSingleOptionSelectedByText()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).DeselectByText("Deselect Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanDeselectSingleOptionSelectedByValue()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).DeselectByValue("Deselect Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanDeselectSingleOptionSelectedByIndex()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value(null));
Expect.Once.On(option1).Method("GetAttribute").Will(Return.Value("2"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).DeselectByIndex(2);
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanDeselectMultipleOptionSelectedByText()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IWebElement option2 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
options.Add(option2 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(option2).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option2).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).DeselectByText("Deselect Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanDeselectMultipleOptionSelectedByValue()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IWebElement option2 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
options.Add(option2 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(option2).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option2).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).DeselectByValue("Deselect Me");
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void CanDeselectMultipleOptionSelectedByIndex()
{
IWebElement option1 = mocks.NewMock<IWebElement>();
IWebElement option2 = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(option1 = mocks.NewMock<IWebElement>());
options.Add(option2 = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Expect.Once.On(option1).Method("GetAttribute").Will(Return.Value("2"));
Expect.Once.On(option1).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option1).Method("Click");
Expect.Once.On(option2).Method("GetAttribute").Will(Return.Value("2"));
Expect.Once.On(option2).GetProperty("Selected").Will(Return.Value(true));
Expect.Once.On(option2).Method("Click");
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
new SelectElement(webElement).DeselectByIndex(2);
mocks.VerifyAllExpectationsHaveBeenMet();
}
[Test]
public void SelectedOptionPropertyShouldThrowExceptionWhenNoOptionSelected()
{
IWebElement selected = mocks.NewMock<IWebElement>();
IWebElement notSelected = mocks.NewMock<IWebElement>();
IList<IWebElement> options = new List<IWebElement>();
options.Add(notSelected = mocks.NewMock<IWebElement>());
Stub.On(webElement).GetProperty("TagName").Will(Return.Value("select"));
Stub.On(webElement).Method("GetAttribute").With("multiple").Will(Return.Value("true"));
Stub.On(notSelected).GetProperty("Selected").Will(Return.Value(false));
Expect.Once.On(webElement).Method("FindElements").Will(Return.Value(new ReadOnlyCollection<IWebElement>(options)));
SelectElement element = new SelectElement(webElement);
Assert.Throws<NoSuchElementException>(() => { IWebElement selectedOption = element.SelectedOption; });
}
[Test]
public void ShouldConvertAnUnquotedStringIntoOneWithQuotes()
{
string result = EscapeQuotes("foo");
Assert.AreEqual("\"foo\"", result);
}
[Test]
public void ShouldConvertAStringWithATickIntoOneWithQuotes()
{
string result = EscapeQuotes("f'oo");
Assert.AreEqual("\"f'oo\"", result);
}
[Test]
public void ShouldConvertAStringWithAQuotIntoOneWithTicks()
{
string result = EscapeQuotes("f\"oo");
Assert.AreEqual("'f\"oo'", result);
}
[Test]
public void ShouldProvideConcatenatedStringsWhenStringToEscapeContainsTicksAndQuotes()
{
string result = EscapeQuotes("f\"o'o");
Assert.AreEqual("concat(\"f\", '\"', \"o'o\")", result);
}
/**
* Tests that escapeQuotes returns concatenated strings when the given
* string contains a tick and and ends with a quote.
*/
[Test]
public void ShouldProvideConcatenatedStringsWhenStringEndsWithQuote()
{
string result = EscapeQuotes("Bar \"Rock'n'Roll\"");
Assert.AreEqual("concat(\"Bar \", '\"', \"Rock'n'Roll\", '\"')", result);
}
private string EscapeQuotes(string toEscape)
{
Type selectElementType = typeof(SelectElement);
MethodInfo escapeQuotesMethod = selectElementType.GetMethod("EscapeQuotes", BindingFlags.Static | BindingFlags.NonPublic);
string result = escapeQuotesMethod.Invoke(null, new object[] { toEscape }).ToString();
return result;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using System.Collections;
using NPOI.DDF;
using NPOI.Util;
using System.Collections.Generic;
using NPOI.HSSF.Util;
/**
* The escher container record is used to hold escher records. It is abstract and
* must be subclassed for maximum benefit.
*
* @author Glen Stampoultzis (glens at apache.org)
* @author Michael Zalewski (zalewski at optonline.net)
*/
public abstract class AbstractEscherHolderRecord : Record
{
private static bool DESERIALISE;
static AbstractEscherHolderRecord()
{
DESERIALISE = false;
//try
//{
// DESERIALISE = (System.Configuration.ConfigurationManager.AppSettings["poi.deserialize.escher"] != null);
//}
//catch (Exception)
//{
// DESERIALISE = false;
//}
}
private List<EscherRecord> escherRecords;
private LazilyConcatenatedByteArray rawDataContainer = new LazilyConcatenatedByteArray();
//private byte[] rawData;
public AbstractEscherHolderRecord()
{
escherRecords = new List<EscherRecord>();
}
/**
* Constructs a Bar record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public AbstractEscherHolderRecord(RecordInputStream in1)
{
escherRecords = new List<EscherRecord>();
if (!DESERIALISE)
{
rawDataContainer.Concatenate(in1.ReadRemainder());
}
else
{
byte[] data = in1.ReadAllContinuedRemainder();
ConvertToEscherRecords(0, data.Length, data);
}
}
protected void ConvertRawBytesToEscherRecords()
{
byte[] rawData = RawData;
ConvertToEscherRecords(0, rawData.Length, rawData);
}
private void ConvertToEscherRecords(int offset, int size, byte[] data)
{
escherRecords.Clear();
IEscherRecordFactory recordFactory = new DefaultEscherRecordFactory();
int pos = offset;
while (pos < offset + size)
{
EscherRecord r = recordFactory.CreateRecord(data, pos);
int bytesRead = r.FillFields(data, pos, recordFactory);
escherRecords.Add(r);
pos += bytesRead;
}
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
String nl = Environment.NewLine;
buffer.Append('[' + RecordName + ']' + nl);
if (escherRecords.Count == 0)
buffer.Append("No Escher Records Decoded" + nl);
foreach (EscherRecord r in escherRecords)
{
buffer.Append(r.ToString());
}
buffer.Append("[/" + RecordName + ']' + nl);
return buffer.ToString();
}
protected abstract String RecordName { get; }
public override int Serialize(int offset, byte[] data)
{
LittleEndian.PutShort(data, 0 + offset, Sid);
LittleEndian.PutShort(data, 2 + offset, (short)(RecordSize - 4));
byte[] rawData = RawData;
if (escherRecords.Count == 0 && rawData != null)
{
LittleEndian.PutShort(data, 0 + offset, Sid);
LittleEndian.PutShort(data, 2 + offset, (short)(RecordSize - 4));
Array.Copy(rawData, 0, data, 4 + offset, rawData.Length);
return rawData.Length + 4;
}
LittleEndian.PutShort(data, 0 + offset, Sid);
LittleEndian.PutShort(data, 2 + offset, (short)(RecordSize - 4));
int pos = offset + 4;
foreach (EscherRecord r in escherRecords)
{
pos += r.Serialize(pos, data, new NullEscherSerializationListener());
}
return RecordSize;
}
/**
* Size of record (including 4 byte header)
*/
public override int RecordSize
{
get
{
byte[] rawData = RawData;
if (escherRecords.Count == 0 && rawData != null)
{
return rawData.Length + 4;
}
else
{
int size = 4;
foreach (EscherRecord r in escherRecords)
{
//EscherRecord r = (EscherRecord)iterator.Current;
size += r.RecordSize;
}
return size;
}
}
}
public override object Clone()
{
return CloneViaReserialise();
}
/**
* Clone the current record, via a call to serialise
* it, and another to Create a new record from the
* bytes.
* May only be used for classes which don't have
* internal counts / ids in them. For those which
* do, a full record-aware serialise is needed, which
* allocates new ids / counts as needed.
*/
//public override Record CloneViaReserialise()
//{
// // Do it via a re-serialise
// // It's a cheat, but it works...
// byte[] b = this.Serialize();
// using (var ms = new System.IO.MemoryStream(b))
// {
// RecordInputStream rinp = new RecordInputStream(ms);
// rinp.NextRecord();
// Record[] r = RecordFactory.CreateRecord(rinp);
// if (r.Length != 1)
// {
// throw new InvalidOperationException("Re-serialised a record to Clone it, but got " + r.Length + " records back!");
// }
// return r[0];
// }
//}
public void AddEscherRecord(int index, EscherRecord element)
{
escherRecords.Insert(index, element);
}
public bool AddEscherRecord(EscherRecord element)
{
escherRecords.Add(element);
return true;
}
public List<EscherRecord> EscherRecords
{
get { return escherRecords; }
}
public void ClearEscherRecords()
{
escherRecords.Clear();
}
/**
* If we have a EscherContainerRecord as one of our
* children (and most top level escher holders do),
* then return that.
*/
public EscherContainerRecord GetEscherContainer()
{
for (IEnumerator it = escherRecords.GetEnumerator(); it.MoveNext(); )
{
Object er = it.Current;
if (er is EscherContainerRecord)
{
return (EscherContainerRecord)er;
}
}
return null;
}
/**
* Descends into all our children, returning the
* first EscherRecord with the given id, or null
* if none found
*/
public EscherRecord FindFirstWithId(short id)
{
return FindFirstWithId(id, EscherRecords);
}
private EscherRecord FindFirstWithId(short id, List<EscherRecord> records)
{
// Check at our level
for (IEnumerator it = records.GetEnumerator(); it.MoveNext(); )
{
EscherRecord r = (EscherRecord)it.Current;
if (r.RecordId == id)
{
return r;
}
}
// Then Check our children in turn
for (IEnumerator it = records.GetEnumerator(); it.MoveNext(); )
{
EscherRecord r = (EscherRecord)it.Current;
if (r.IsContainerRecord)
{
EscherRecord found =
FindFirstWithId(id, r.ChildRecords);
if (found != null)
{
return found;
}
}
}
// Not found in this lot
return null;
}
public EscherRecord GetEscherRecord(int index)
{
return (EscherRecord)escherRecords[index];
}
/**
* Big drawing Group records are split but it's easier to deal with them
* as a whole Group so we need to join them toGether.
*/
public void Join(AbstractEscherHolderRecord record)
{
rawDataContainer.Concatenate(record.RawData);
}
public void ProcessContinueRecord(byte[] record)
{
rawDataContainer.Concatenate(record);
}
public byte[] RawData
{
get { return rawDataContainer.ToArray(); }
set
{
rawDataContainer.Clear();
rawDataContainer.Concatenate(value);
}
}
/**
* Convert raw data to escher records.
*/
public void Decode()
{
if (null == escherRecords || 0 == escherRecords.Count)
{
byte[] rawData = RawData;
ConvertToEscherRecords(0, rawData.Length, rawData);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>KeywordView</c> resource.</summary>
public sealed partial class KeywordViewName : gax::IResourceName, sys::IEquatable<KeywordViewName>
{
/// <summary>The possible contents of <see cref="KeywordViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
CustomerAdGroupCriterion = 1,
}
private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/keywordViews/{ad_group_id_criterion_id}");
/// <summary>Creates a <see cref="KeywordViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="KeywordViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static KeywordViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new KeywordViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="KeywordViewName"/> with the pattern
/// <c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="KeywordViewName"/> constructed from the provided ids.</returns>
public static KeywordViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) =>
new KeywordViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordViewName"/> with pattern
/// <c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KeywordViewName"/> with pattern
/// <c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c>.
/// </returns>
public static string Format(string customerId, string adGroupId, string criterionId) =>
FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="KeywordViewName"/> with pattern
/// <c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="KeywordViewName"/> with pattern
/// <c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c>.
/// </returns>
public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) =>
s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}");
/// <summary>Parses the given resource name string into a new <see cref="KeywordViewName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="KeywordViewName"/> if successful.</returns>
public static KeywordViewName Parse(string keywordViewName) => Parse(keywordViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="KeywordViewName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="KeywordViewName"/> if successful.</returns>
public static KeywordViewName Parse(string keywordViewName, bool allowUnparsed) =>
TryParse(keywordViewName, allowUnparsed, out KeywordViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="keywordViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordViewName, out KeywordViewName result) =>
TryParse(keywordViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="KeywordViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="keywordViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="KeywordViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keywordViewName, bool allowUnparsed, out KeywordViewName result)
{
gax::GaxPreconditions.CheckNotNull(keywordViewName, nameof(keywordViewName));
gax::TemplatedResourceName resourceName;
if (s_customerAdGroupCriterion.TryParseName(keywordViewName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(keywordViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private KeywordViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AdGroupId = adGroupId;
CriterionId = criterionId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="KeywordViewName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/keywordViews/{ad_group_id}~{criterion_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public KeywordViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string AdGroupId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as KeywordViewName);
/// <inheritdoc/>
public bool Equals(KeywordViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(KeywordViewName a, KeywordViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(KeywordViewName a, KeywordViewName b) => !(a == b);
}
public partial class KeywordView
{
/// <summary>
/// <see cref="KeywordViewName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal KeywordViewName ResourceNameAsKeywordViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : KeywordViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using Alexa.NET.Request;
using Alexa.NET.Response;
using Amazon.Lambda.Core;
using JustEat.HttpClientInterception;
namespace MartinCostello.LondonTravel.Skill;
public class CommuteTests : FunctionTests
{
public CommuteTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Fact]
public async Task Can_Invoke_Function_When_The_Skill_Is_Not_Linked()
{
// Arrange
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequestWithToken(accessToken: null);
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
ResponseBody response = AssertResponse(actual);
response.Card.ShouldNotBeNull();
response.Card.ShouldBeOfType<LinkAccountCard>();
response.Reprompt.ShouldBeNull();
response.OutputSpeech.ShouldNotBeNull();
response.OutputSpeech.Type.ShouldBe("SSML");
var ssml = response.OutputSpeech.ShouldBeOfType<SsmlOutputSpeech>();
ssml.Ssml.ShouldBe("<speak>You need to link your account to be able to ask me about your commute.</speak>");
}
[Fact]
public async Task Can_Invoke_Function_When_The_Skill_Token_Is_Invalid()
{
// Arrange
Interceptor.RegisterBundle(Path.Combine("Bundles", "skill-api-invalid-token.json"));
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequestWithToken(accessToken: "invalid-access-token");
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
ResponseBody response = AssertResponse(actual);
response.Card.ShouldNotBeNull();
response.Card.ShouldBeOfType<LinkAccountCard>();
response.Reprompt.ShouldBeNull();
response.OutputSpeech.ShouldNotBeNull();
response.OutputSpeech.Type.ShouldBe("SSML");
var ssml = response.OutputSpeech.ShouldBeOfType<SsmlOutputSpeech>();
ssml.Ssml.ShouldBe("<speak>It looks like you've disabled account linking. You need to re-link your account to be able to ask me about your commute.</speak>");
}
[Fact]
public async Task Can_Invoke_Function_When_The_Skill_Api_Fails()
{
// Arrange
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequestWithToken(accessToken: "random-access-token");
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
ResponseBody response = AssertResponse(actual);
response.Card.ShouldBeNull();
response.Reprompt.ShouldBeNull();
response.OutputSpeech.ShouldNotBeNull();
response.OutputSpeech.Type.ShouldBe("SSML");
var ssml = response.OutputSpeech.ShouldBeOfType<SsmlOutputSpeech>();
ssml.Ssml.ShouldBe("<speak>Sorry, something went wrong.</speak>");
}
[Fact]
public async Task Can_Invoke_Function_When_The_Skill_Is_Linked_And_Has_No_Favorite_Lines()
{
// Arrange
Interceptor.RegisterBundle(Path.Combine("Bundles", "skill-api-no-favorites.json"));
Interceptor.RegisterBundle(Path.Combine("Bundles", "tfl-line-statuses.json"));
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequestWithToken(accessToken: "token-for-no-favorites");
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
AssertResponse(
actual,
"<speak>You have not selected any favourite lines yet. Visit the London Travel website to set your preferences.</speak>",
"You have not selected any favourite lines yet. Visit the London Travel website to set your preferences.");
}
[Fact]
public async Task Can_Invoke_Function_When_The_Skill_Is_Linked_And_Only_The_Elizabeth_Line_Is_A_Favorite()
{
// Arrange
Interceptor.RegisterBundle(Path.Combine("Bundles", "skill-api-elizabeth.json"));
Interceptor.RegisterBundle(Path.Combine("Bundles", "tfl-line-statuses.json"));
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequestWithToken(accessToken: "token-for-only-elizabeth-line");
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
AssertResponse(
actual,
"<speak>You have not selected any favourite lines yet. Visit the London Travel website to set your preferences.</speak>",
"You have not selected any favourite lines yet. Visit the London Travel website to set your preferences.");
}
[Fact]
public async Task Can_Invoke_Function_When_The_Skill_Is_Linked_And_Has_One_Favorite_Line()
{
// Arrange
Interceptor.RegisterBundle(Path.Combine("Bundles", "skill-api-one-favorite.json"));
Interceptor.RegisterBundle(Path.Combine("Bundles", "tfl-line-statuses.json"));
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequestWithToken(accessToken: "token-for-one-favorite");
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
AssertResponse(
actual,
"<speak>Saturday 19 and Sunday 20 October, no service between Hammersmith / Wimbledon / Kensington Olympia and South Kensington / Edgware Road. Replacement buses operate.</speak>",
"Saturday 19 and Sunday 20 October, no service between Hammersmith / Wimbledon / Kensington Olympia and South Kensington / Edgware Road. Replacement buses operate.");
}
[Fact]
public async Task Can_Invoke_Function_When_The_Skill_Is_Linked_And_Has_Two_Favorite_Lines()
{
// Arrange
Interceptor.RegisterBundle(Path.Combine("Bundles", "skill-api-two-favorites.json"));
Interceptor.RegisterBundle(Path.Combine("Bundles", "tfl-line-statuses.json"));
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequestWithToken(accessToken: "token-for-two-favorites");
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
AssertResponse(
actual,
"<speak><p>Northern Line: There is a good service on the Northern line.</p><p>Victoria Line: There is a good service on the Victoria line.</p></speak>",
"Northern Line: There is a good service on the Northern line.\nVictoria Line: There is a good service on the Victoria line.");
}
private void AssertResponse(SkillResponse actual, string expectedSsml, string expectedCardContent)
{
ResponseBody response = AssertResponse(actual);
response.Reprompt.ShouldBeNull();
response.OutputSpeech.ShouldNotBeNull();
response.OutputSpeech.Type.ShouldBe("SSML");
var ssml = response.OutputSpeech.ShouldBeOfType<SsmlOutputSpeech>();
ssml.Ssml.ShouldBe(expectedSsml);
response.Card.ShouldNotBeNull();
var card = response.Card.ShouldBeOfType<StandardCard>();
card.Type.ShouldBe("Standard");
card.Title.ShouldBe("Your Commute");
card.Content.ShouldBe(expectedCardContent);
}
private SkillRequest CreateIntentRequestWithToken(string accessToken = null, string locale = null)
{
var request = CreateIntentRequest("CommuteIntent");
if (accessToken != null)
{
request.Session.User = new User()
{
AccessToken = accessToken,
UserId = Guid.NewGuid().ToString(),
};
}
if (locale != null)
{
request.Request.Locale = locale;
}
return request;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Xml;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Data;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Hypergrid;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
namespace OpenSim.Services.GridService
{
public class HypergridLinker : IHypergridLinker
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static uint m_autoMappingX = 0;
private static uint m_autoMappingY = 0;
private static bool m_enableAutoMapping = false;
protected IRegionData m_Database;
protected GridService m_GridService;
protected IAssetService m_AssetService;
protected GatekeeperServiceConnector m_GatekeeperConnector;
protected UUID m_ScopeID = UUID.Zero;
// protected bool m_Check4096 = true;
protected string m_MapTileDirectory = string.Empty;
protected string m_ThisGatekeeper = string.Empty;
protected Uri m_ThisGatekeeperURI = null;
protected GridRegion m_DefaultRegion;
protected GridRegion DefaultRegion
{
get
{
if (m_DefaultRegion == null)
{
List<GridRegion> defs = m_GridService.GetDefaultHypergridRegions(m_ScopeID);
if (defs != null && defs.Count > 0)
m_DefaultRegion = defs[0];
else
{
// Get any region
defs = m_GridService.GetRegionsByName(m_ScopeID, "", 1);
if (defs != null && defs.Count > 0)
m_DefaultRegion = defs[0];
else
{
// This shouldn't happen
m_DefaultRegion = new GridRegion(1000, 1000);
m_log.Error("[HYPERGRID LINKER]: Something is wrong with this grid. It has no regions?");
}
}
}
return m_DefaultRegion;
}
}
public HypergridLinker(IConfigSource config, GridService gridService, IRegionData db)
{
IConfig gridConfig = config.Configs["GridService"];
if (gridConfig == null)
return;
if (!gridConfig.GetBoolean("HypergridLinker", false))
return;
m_Database = db;
m_GridService = gridService;
m_log.DebugFormat("[HYPERGRID LINKER]: Starting with db {0}", db.GetType());
string assetService = gridConfig.GetString("AssetService", string.Empty);
Object[] args = new Object[] { config };
if (assetService != string.Empty)
m_AssetService = ServerUtils.LoadPlugin<IAssetService>(assetService, args);
string scope = gridConfig.GetString("ScopeID", string.Empty);
if (scope != string.Empty)
UUID.TryParse(scope, out m_ScopeID);
// m_Check4096 = gridConfig.GetBoolean("Check4096", true);
m_MapTileDirectory = gridConfig.GetString("MapTileDirectory", "maptiles");
m_ThisGatekeeper = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "GridService" }, String.Empty);
// Legacy. Remove soon!
m_ThisGatekeeper = gridConfig.GetString("Gatekeeper", m_ThisGatekeeper);
try
{
m_ThisGatekeeperURI = new Uri(m_ThisGatekeeper);
}
catch
{
m_log.WarnFormat("[HYPERGRID LINKER]: Malformed URL in [GridService], variable Gatekeeper = {0}", m_ThisGatekeeper);
}
m_GatekeeperConnector = new GatekeeperServiceConnector(m_AssetService);
m_log.Debug("[HYPERGRID LINKER]: Loaded all services...");
if (!string.IsNullOrEmpty(m_MapTileDirectory))
{
try
{
Directory.CreateDirectory(m_MapTileDirectory);
}
catch (Exception e)
{
m_log.WarnFormat("[HYPERGRID LINKER]: Could not create map tile storage directory {0}: {1}", m_MapTileDirectory, e);
m_MapTileDirectory = string.Empty;
}
}
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-region",
"link-region <Xloc> <Yloc> <ServerURI> [<RemoteRegionName>]",
"Link a HyperGrid Region. Examples for <ServerURI>: http://grid.net:8002/ or http://example.org/path/foo.php", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-region",
"link-region <Xloc> <Yloc> <RegionIP> <RegionPort> [<RemoteRegionName>]",
"Link a hypergrid region (deprecated)", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "unlink-region",
"unlink-region <local name>",
"Unlink a hypergrid region", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-mapping", "link-mapping [<x> <y>]",
"Set local coordinate to map HG regions to", RunCommand);
MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "show hyperlinks", "show hyperlinks",
"List the HG regions", HandleShow);
}
}
#region Link Region
// from map search
public GridRegion LinkRegion(UUID scopeID, string regionDescriptor)
{
string reason = string.Empty;
uint xloc = Util.RegionToWorldLoc((uint)random.Next(0, Int16.MaxValue));
return TryLinkRegionToCoords(scopeID, regionDescriptor, (int)xloc, 0, out reason);
}
private static Random random = new Random();
// From the command line link-region (obsolete) and the map
private GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, out string reason)
{
return TryLinkRegionToCoords(scopeID, mapName, xloc, yloc, UUID.Zero, out reason);
}
public GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, UUID ownerID, out string reason)
{
reason = string.Empty;
GridRegion regInfo = null;
mapName = mapName.Trim();
if (!mapName.StartsWith("http"))
{
// Formats: grid.example.com:8002:region name
// grid.example.com:region name
// grid.example.com:8002
// grid.example.com
string host;
uint port = 80;
string regionName = "";
string[] parts = mapName.Split(new char[] { ':' });
if (parts.Length == 0)
{
reason = "Wrong format for link-region";
return null;
}
host = parts[0];
if (parts.Length >= 2)
{
// If it's a number then assume it's a port. Otherwise, it's a region name.
if (!UInt32.TryParse(parts[1], out port))
regionName = parts[1];
}
// always take the last one
if (parts.Length >= 3)
{
regionName = parts[2];
}
bool success = TryCreateLink(scopeID, xloc, yloc, regionName, port, host, ownerID, out regInfo, out reason);
if (success)
{
regInfo.RegionName = mapName;
return regInfo;
}
}
else
{
// Formats: http://grid.example.com region name
// http://grid.example.com "region name"
// http://grid.example.com
string serverURI;
string regionName = "";
string[] parts = mapName.Split(new char[] { ' ' });
if (parts.Length == 0)
{
reason = "Wrong format for link-region";
return null;
}
serverURI = parts[0];
if (parts.Length >= 2)
{
regionName = mapName.Substring(serverURI.Length);
regionName = regionName.Trim(new char[] { '"', ' ' });
}
if (TryCreateLink(scopeID, xloc, yloc, regionName, 0, null, serverURI, ownerID, out regInfo, out reason))
{
regInfo.RegionName = mapName;
return regInfo;
}
}
return null;
}
private bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, UUID ownerID, out GridRegion regInfo, out string reason)
{
return TryCreateLink(scopeID, xloc, yloc, remoteRegionName, externalPort, externalHostName, null, ownerID, out regInfo, out reason);
}
private bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, string serverURI, UUID ownerID, out GridRegion regInfo, out string reason)
{
lock (this)
{
return TryCreateLinkImpl(scopeID, xloc, yloc, remoteRegionName, externalPort, externalHostName, serverURI, ownerID, out regInfo, out reason);
}
}
private bool TryCreateLinkImpl(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, string serverURI, UUID ownerID, out GridRegion regInfo, out string reason)
{
m_log.InfoFormat("[HYPERGRID LINKER]: Link to {0} {1}, in <{2},{3}>",
((serverURI == null) ? (externalHostName + ":" + externalPort) : serverURI),
remoteRegionName, Util.WorldToRegionLoc((uint)xloc), Util.WorldToRegionLoc((uint)yloc));
reason = string.Empty;
Uri uri = null;
regInfo = new GridRegion();
if (externalPort > 0)
regInfo.HttpPort = externalPort;
else
regInfo.HttpPort = 80;
if (externalHostName != null)
regInfo.ExternalHostName = externalHostName;
else
regInfo.ExternalHostName = "0.0.0.0";
if (serverURI != null)
{
regInfo.ServerURI = serverURI;
try
{
uri = new Uri(serverURI);
regInfo.ExternalHostName = uri.Host;
regInfo.HttpPort = (uint)uri.Port;
}
catch {}
}
if (remoteRegionName != string.Empty)
regInfo.RegionName = remoteRegionName;
regInfo.RegionLocX = xloc;
regInfo.RegionLocY = yloc;
regInfo.ScopeID = scopeID;
regInfo.EstateOwner = ownerID;
// Make sure we're not hyperlinking to regions on this grid!
if (m_ThisGatekeeperURI != null)
{
if (regInfo.ExternalHostName == m_ThisGatekeeperURI.Host && regInfo.HttpPort == m_ThisGatekeeperURI.Port)
{
m_log.InfoFormat("[HYPERGRID LINKER]: Cannot hyperlink to regions on the same grid");
reason = "Cannot hyperlink to regions on the same grid";
return false;
}
}
else
m_log.WarnFormat("[HYPERGRID LINKER]: Please set this grid's Gatekeeper's address in [GridService]!");
// Check for free coordinates
GridRegion region = m_GridService.GetRegionByPosition(regInfo.ScopeID, regInfo.RegionLocX, regInfo.RegionLocY);
if (region != null)
{
m_log.WarnFormat("[HYPERGRID LINKER]: Coordinates <{0},{1}> are already occupied by region {2} with uuid {3}",
Util.WorldToRegionLoc((uint)regInfo.RegionLocX), Util.WorldToRegionLoc((uint)regInfo.RegionLocY),
region.RegionName, region.RegionID);
reason = "Coordinates are already in use";
return false;
}
try
{
regInfo.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)0);
}
catch (Exception e)
{
m_log.Warn("[HYPERGRID LINKER]: Wrong format for link-region: " + e.Message);
reason = "Internal error";
return false;
}
// Finally, link it
ulong handle = 0;
UUID regionID = UUID.Zero;
string externalName = string.Empty;
string imageURL = string.Empty;
if (!m_GatekeeperConnector.LinkRegion(regInfo, out regionID, out handle, out externalName, out imageURL, out reason))
return false;
if (regionID == UUID.Zero)
{
m_log.Warn("[HYPERGRID LINKER]: Unable to link region");
reason = "Remote region could not be found";
return false;
}
region = m_GridService.GetRegionByUUID(scopeID, regionID);
if (region != null)
{
m_log.DebugFormat("[HYPERGRID LINKER]: Region already exists in coordinates <{0},{1}>",
Util.WorldToRegionLoc((uint)region.RegionLocX), Util.WorldToRegionLoc((uint)region.RegionLocY));
regInfo = region;
return true;
}
// We are now performing this check for each individual teleport in the EntityTransferModule instead. This
// allows us to give better feedback when teleports fail because of the distance reason (which can't be
// done here) and it also hypergrid teleports that are within range (possibly because the source grid
// itself has regions that are very far apart).
// uint x, y;
// if (m_Check4096 && !Check4096(handle, out x, out y))
// {
// //RemoveHyperlinkRegion(regInfo.RegionID);
// reason = "Region is too far (" + x + ", " + y + ")";
// m_log.Info("[HYPERGRID LINKER]: Unable to link, region is too far (" + x + ", " + y + ")");
// //return false;
// }
regInfo.RegionID = regionID;
if (externalName == string.Empty)
regInfo.RegionName = regInfo.ServerURI;
else
regInfo.RegionName = externalName;
m_log.DebugFormat("[HYPERGRID LINKER]: naming linked region {0}, handle {1}", regInfo.RegionName, handle.ToString());
// Get the map image
regInfo.TerrainImage = GetMapImage(regionID, imageURL);
// Store the origin's coordinates somewhere
regInfo.RegionSecret = handle.ToString();
AddHyperlinkRegion(regInfo, handle);
m_log.InfoFormat("[HYPERGRID LINKER]: Successfully linked to region {0} at <{1},{2}> with image {3}",
regInfo.RegionName, Util.WorldToRegionLoc((uint)regInfo.RegionLocX), Util.WorldToRegionLoc((uint)regInfo.RegionLocY), regInfo.TerrainImage);
return true;
}
public bool TryUnlinkRegion(string mapName)
{
m_log.DebugFormat("[HYPERGRID LINKER]: Request to unlink {0}", mapName);
GridRegion regInfo = null;
List<RegionData> regions = m_Database.Get(Util.EscapeForLike(mapName), m_ScopeID);
if (regions != null && regions.Count > 0)
{
OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(regions[0].Data["flags"]);
if ((rflags & OpenSim.Framework.RegionFlags.Hyperlink) != 0)
{
regInfo = new GridRegion();
regInfo.RegionID = regions[0].RegionID;
regInfo.ScopeID = m_ScopeID;
}
}
if (regInfo != null)
{
RemoveHyperlinkRegion(regInfo.RegionID);
return true;
}
else
{
m_log.InfoFormat("[HYPERGRID LINKER]: Region {0} not found", mapName);
return false;
}
}
// Not currently used
// /// <summary>
// /// Cope with this viewer limitation.
// /// </summary>
// /// <param name="regInfo"></param>
// /// <returns></returns>
// public bool Check4096(ulong realHandle, out uint x, out uint y)
// {
// uint ux = 0, uy = 0;
// Utils.LongToUInts(realHandle, out ux, out uy);
// x = Util.WorldToRegionLoc(ux);
// y = Util.WorldToRegionLoc(uy);
//
// const uint limit = Util.RegionToWorldLoc(4096 - 1);
// uint xmin = ux - limit;
// uint xmax = ux + limit;
// uint ymin = uy - limit;
// uint ymax = uy + limit;
// // World map boundary checks
// if (xmin < 0 || xmin > ux)
// xmin = 0;
// if (xmax > int.MaxValue || xmax < ux)
// xmax = int.MaxValue;
// if (ymin < 0 || ymin > uy)
// ymin = 0;
// if (ymax > int.MaxValue || ymax < uy)
// ymax = int.MaxValue;
//
// // Check for any regions that are within the possible teleport range to the linked region
// List<GridRegion> regions = m_GridService.GetRegionRange(m_ScopeID, (int)xmin, (int)xmax, (int)ymin, (int)ymax);
// if (regions.Count == 0)
// {
// return false;
// }
// else
// {
// // Check for regions which are not linked regions
// List<GridRegion> hyperlinks = m_GridService.GetHyperlinks(m_ScopeID);
// IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks);
// if (availableRegions.Count() == 0)
// return false;
// }
//
// return true;
// }
private void AddHyperlinkRegion(GridRegion regionInfo, ulong regionHandle)
{
RegionData rdata = m_GridService.RegionInfo2RegionData(regionInfo);
int flags = (int)OpenSim.Framework.RegionFlags.Hyperlink + (int)OpenSim.Framework.RegionFlags.NoDirectLogin + (int)OpenSim.Framework.RegionFlags.RegionOnline;
rdata.Data["flags"] = flags.ToString();
m_Database.Store(rdata);
}
private void RemoveHyperlinkRegion(UUID regionID)
{
m_Database.Delete(regionID);
}
public UUID GetMapImage(UUID regionID, string imageURL)
{
return m_GatekeeperConnector.GetMapImage(regionID, imageURL, m_MapTileDirectory);
}
#endregion
#region Console Commands
public void HandleShow(string module, string[] cmd)
{
if (cmd.Length != 2)
{
MainConsole.Instance.Output("Syntax: show hyperlinks");
return;
}
List<RegionData> regions = m_Database.GetHyperlinks(UUID.Zero);
if (regions == null || regions.Count < 1)
{
MainConsole.Instance.Output("No hyperlinks");
return;
}
MainConsole.Instance.Output("Region Name");
MainConsole.Instance.Output("Location Region UUID");
MainConsole.Instance.Output(new string('-', 72));
foreach (RegionData r in regions)
{
MainConsole.Instance.Output(
String.Format("{0}\n{2,-32} {1}\n",
r.RegionName, r.RegionID,
String.Format("{0},{1} ({2},{3})", r.posX, r.posY,
Util.WorldToRegionLoc((uint)r.posX), Util.WorldToRegionLoc((uint)r.posY)
)
)
);
}
return;
}
public void RunCommand(string module, string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
RunHGCommand(command, cmdparams);
}
private void RunLinkRegionCommand(string[] cmdparams)
{
int xloc, yloc;
string serverURI;
string remoteName = null;
xloc = (int)Util.RegionToWorldLoc((uint)Convert.ToInt32(cmdparams[0]));
yloc = (int)Util.RegionToWorldLoc((uint)Convert.ToInt32(cmdparams[1]));
serverURI = cmdparams[2];
if (cmdparams.Length > 3)
remoteName = string.Join(" ", cmdparams, 3, cmdparams.Length - 3);
string reason = string.Empty;
GridRegion regInfo;
if (TryCreateLink(UUID.Zero, xloc, yloc, remoteName, 0, null, serverURI, UUID.Zero, out regInfo, out reason))
MainConsole.Instance.Output("Hyperlink established");
else
MainConsole.Instance.Output("Failed to link region: " + reason);
}
private void RunHGCommand(string command, string[] cmdparams)
{
if (command.Equals("link-mapping"))
{
if (cmdparams.Length == 2)
{
try
{
m_autoMappingX = Convert.ToUInt32(cmdparams[0]);
m_autoMappingY = Convert.ToUInt32(cmdparams[1]);
m_enableAutoMapping = true;
}
catch (Exception)
{
m_autoMappingX = 0;
m_autoMappingY = 0;
m_enableAutoMapping = false;
}
}
}
else if (command.Equals("link-region"))
{
if (cmdparams.Length < 3)
{
if ((cmdparams.Length == 1) || (cmdparams.Length == 2))
{
LoadXmlLinkFile(cmdparams);
}
else
{
LinkRegionCmdUsage();
}
return;
}
//this should be the prefererred way of setting up hg links now
if (cmdparams[2].StartsWith("http"))
{
RunLinkRegionCommand(cmdparams);
}
else if (cmdparams[2].Contains(":"))
{
// New format
string[] parts = cmdparams[2].Split(':');
if (parts.Length > 2)
{
// Insert remote region name
ArrayList parameters = new ArrayList(cmdparams);
parameters.Insert(3, parts[2]);
cmdparams = (string[])parameters.ToArray(typeof(string));
}
cmdparams[2] = "http://" + parts[0] + ':' + parts[1];
RunLinkRegionCommand(cmdparams);
}
else
{
// old format
GridRegion regInfo;
uint xloc, yloc;
uint externalPort;
string externalHostName;
try
{
xloc = Convert.ToUInt32(cmdparams[0]);
yloc = Convert.ToUInt32(cmdparams[1]);
externalPort = Convert.ToUInt32(cmdparams[3]);
externalHostName = cmdparams[2];
//internalPort = Convert.ToUInt32(cmdparams[4]);
//remotingPort = Convert.ToUInt32(cmdparams[5]);
}
catch (Exception e)
{
MainConsole.Instance.Output("[HGrid] Wrong format for link-region command: " + e.Message);
LinkRegionCmdUsage();
return;
}
// Convert cell coordinates given by the user to meters
xloc = Util.RegionToWorldLoc(xloc);
yloc = Util.RegionToWorldLoc(yloc);
string reason = string.Empty;
if (TryCreateLink(UUID.Zero, (int)xloc, (int)yloc,
string.Empty, externalPort, externalHostName, UUID.Zero, out regInfo, out reason))
{
// What is this? The GridRegion instance will be discarded anyway,
// which effectively ignores any local name given with the command.
//if (cmdparams.Length >= 5)
//{
// regInfo.RegionName = "";
// for (int i = 4; i < cmdparams.Length; i++)
// regInfo.RegionName += cmdparams[i] + " ";
//}
}
}
return;
}
else if (command.Equals("unlink-region"))
{
if (cmdparams.Length < 1)
{
UnlinkRegionCmdUsage();
return;
}
string region = string.Join(" ", cmdparams);
if (TryUnlinkRegion(region))
MainConsole.Instance.Output("Successfully unlinked " + region);
else
MainConsole.Instance.Output("Unable to unlink " + region + ", region not found.");
}
}
private void LoadXmlLinkFile(string[] cmdparams)
{
//use http://www.hgurl.com/hypergrid.xml for test
try
{
XmlReader r = XmlReader.Create(cmdparams[0]);
XmlConfigSource cs = new XmlConfigSource(r);
string[] excludeSections = null;
if (cmdparams.Length == 2)
{
if (cmdparams[1].ToLower().StartsWith("excludelist:"))
{
string excludeString = cmdparams[1].ToLower();
excludeString = excludeString.Remove(0, 12);
char[] splitter = { ';' };
excludeSections = excludeString.Split(splitter);
}
}
for (int i = 0; i < cs.Configs.Count; i++)
{
bool skip = false;
if ((excludeSections != null) && (excludeSections.Length > 0))
{
for (int n = 0; n < excludeSections.Length; n++)
{
if (excludeSections[n] == cs.Configs[i].Name.ToLower())
{
skip = true;
break;
}
}
}
if (!skip)
{
ReadLinkFromConfig(cs.Configs[i]);
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
private void ReadLinkFromConfig(IConfig config)
{
GridRegion regInfo;
uint xloc, yloc;
uint externalPort;
string externalHostName;
uint realXLoc, realYLoc;
xloc = Convert.ToUInt32(config.GetString("xloc", "0"));
yloc = Convert.ToUInt32(config.GetString("yloc", "0"));
externalPort = Convert.ToUInt32(config.GetString("externalPort", "0"));
externalHostName = config.GetString("externalHostName", "");
realXLoc = Convert.ToUInt32(config.GetString("real-xloc", "0"));
realYLoc = Convert.ToUInt32(config.GetString("real-yloc", "0"));
if (m_enableAutoMapping)
{
xloc = (xloc % 100) + m_autoMappingX;
yloc = (yloc % 100) + m_autoMappingY;
}
if (((realXLoc == 0) && (realYLoc == 0)) ||
(((realXLoc - xloc < 3896) || (xloc - realXLoc < 3896)) &&
((realYLoc - yloc < 3896) || (yloc - realYLoc < 3896))))
{
xloc = Util.RegionToWorldLoc(xloc);
yloc = Util.RegionToWorldLoc(yloc);
string reason = string.Empty;
if (TryCreateLink(UUID.Zero, (int)xloc, (int)yloc,
string.Empty, externalPort, externalHostName, UUID.Zero, out regInfo, out reason))
{
regInfo.RegionName = config.GetString("localName", "");
}
else
MainConsole.Instance.Output("Unable to link " + externalHostName + ": " + reason);
}
}
private void LinkRegionCmdUsage()
{
MainConsole.Instance.Output("Usage: link-region <Xloc> <Yloc> <ServerURI> [<RemoteRegionName>]");
MainConsole.Instance.Output("Usage (deprecated): link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>]");
MainConsole.Instance.Output("Usage (deprecated): link-region <Xloc> <Yloc> <HostName> <HttpPort> [<LocalName>]");
MainConsole.Instance.Output("Usage: link-region <URI_of_xml> [<exclude>]");
}
private void UnlinkRegionCmdUsage()
{
MainConsole.Instance.Output("Usage: unlink-region <LocalName>");
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace SharpFormEditorDemo
{
/// <summary>
/// Summary description for SelectionUIOverlay.
/// </summary>
public class SelectionUIOverlay : System.Windows.Forms.Control
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private Form m_Form;
private RectTracker m_tracker = new RectTracker();
private FormRectTracker m_FormTracker = new FormRectTracker();
public Control m_seletedCtrl = null;
public SelectionUIOverlay(Form frm)
{
m_Form = frm;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitComponent call
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.Name = "SelectionUIOverlay";
this.AllowDrop = true;
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.SelectionUIOverlay_MouseDown);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.SelectionUIOverlay_DragDrop);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.SelectionUIOverlay_Paint);
this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.SelectionUIOverlay_MouseMove);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.SelectionUIOverlay_DragEnter);
}
#endregion
protected override CreateParams CreateParams
{
get
{
CreateParams cp=base.CreateParams;
cp.ExStyle|=0x00000020; //WS_EX_TRANSPARENT
return cp;
}
}
protected override void OnCreateControl()
{
base.OnCreateControl ();
m_FormTracker.m_rect = GetFormRect();
//MainForm.m_propertyWindow.SetSelectedObject(m_Form);
}
private Rectangle GetFormRect()
{
Rectangle rc = m_Form.Bounds;
rc = Parent.RectangleToScreen(rc);
rc = this.RectangleToClient(rc);
return rc;
}
public void UpdatePropertyWindow()
{
if(m_seletedCtrl != null)
{
// MainForm.m_propertyWindow.SetSelectedObject(m_seletedCtrl);
}
else
{
m_FormTracker.m_rect = GetFormRect();
//MainForm.m_propertyWindow.SetSelectedObject(m_Form);
}
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
private void InvalidateEx()
{
Invalidate();
//let parent redraw the background
if(Parent==null)
return;
Rectangle rc=new Rectangle(this.Location,this.Size);
Parent.Invalidate(rc,true);
if(!m_FormTracker.IsEmpty())
{
rc = m_FormTracker.m_rect;
rc = this.RectangleToScreen(rc);
rc = Parent.RectangleToClient(rc);
m_Form.SetBounds(rc.Left, rc.Top, rc.Width, rc.Height);
m_Form.Refresh();
}
if(m_seletedCtrl != null)
{
rc = m_tracker.m_rect;
rc = this.RectangleToScreen(rc);
rc = m_Form.RectangleToClient(rc);
m_seletedCtrl.SetBounds(rc.Left, rc.Top, rc.Width, rc.Height);
m_seletedCtrl.Refresh();
}
}
private void SelectionUIOverlay_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button != MouseButtons .Left)
return;
//
Point pt=new Point(e.X,e.Y);
Rectangle rcForm = GetFormRect();
if(rcForm.Contains(pt)){
Rectangle rcObject;
if (m_tracker.HitTest(pt) == RectTracker.TrackerHit.hitNothing) {
m_seletedCtrl = null;
m_tracker.m_rect = new Rectangle(0,0,0,0);
// just to demonstrate RectTracker::TrackRubberBand
RectTracker tracker=new RectTracker();
if (tracker.TrackRubberBand(this, pt, false)){
// see if rubber band intersects with the doc's tracker
tracker.NormalizeRect(ref tracker.m_rect);
Rectangle rectIntersect = tracker.m_rect;
foreach (Control ctrl in m_Form.Controls){
rcObject = ctrl.Bounds;
rcObject = m_Form.RectangleToScreen(rcObject);
rcObject = this.RectangleToClient(rcObject);
if(tracker.m_rect.Contains(rcObject)){
m_tracker.m_rect = rcObject;
m_seletedCtrl = ctrl;
// MainForm.m_propertyWindow.SetSelectedObject(m_seletedCtrl);
break;
}
}
}
else{
// No rubber band, see if the point selects an object.
foreach (Control ctrl in m_Form.Controls){
rcObject = ctrl.Bounds ;
rcObject = m_Form.RectangleToScreen(rcObject);
rcObject = this.RectangleToClient(rcObject);
if(rcObject.Contains(pt)){
m_tracker.m_rect = rcObject;
m_seletedCtrl = ctrl;
// MainForm.m_propertyWindow.SetSelectedObject(ctrl);
break;
}
}
}
if(m_seletedCtrl == null){
//MainForm.m_propertyWindow.SetSelectedObject(m_Form);
m_FormTracker.m_rect = rcForm;
}
else{
m_FormTracker.Clear();
}
}
else if(m_seletedCtrl != null){// normal tracking action, when tracker is hit
m_tracker.Track(this, pt, false,null);
}
}
else{
if(m_seletedCtrl == null){//select the container form
// MainForm.m_propertyWindow.SetSelectedObject(m_Form);
if(m_FormTracker.HitTest(pt) == RectTracker.TrackerHit.hitNothing)
{
m_FormTracker.m_rect = rcForm;
}
else if(!m_FormTracker.IsEmpty())
{
m_FormTracker.Track(this, pt, false,null);
}
}
else{
m_FormTracker.Clear();
}
}
InvalidateEx();
}
private void SelectionUIOverlay_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
Point mousept=new Point(e.X,e.Y);
if(m_seletedCtrl != null){
if(!m_tracker.SetCursor(this,0,mousept))
this.Cursor=Cursors.Arrow;
}
else{
if(!m_FormTracker.SetCursor(this,0,mousept))
this.Cursor=Cursors.Arrow;
}
}
private void SelectionUIOverlay_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void SelectionUIOverlay_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
if(m_seletedCtrl != null)
m_tracker.Draw(e.Graphics);
else
m_FormTracker.Draw(e.Graphics);
}
private void SelectionUIOverlay_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
//ToolBoxItem DragData = (ToolBoxItem)e.Data.GetData(typeof(ToolBoxItem));
//Control ctrl = ControlFactory.CreateControl(DragData.Caption,DragData.Object.ToString()) as Control;
/*
ctrl.Location = m_Form.PointToClient(new Point(e.X,e.Y));
if(! (ctrl is DateTimePicker))//DateTimePicker can not set Text property
ctrl.Text = DragData.Caption;
Rectangle rect = ctrl.Bounds;
rect = m_Form.RectangleToScreen(rect);
rect = this.RectangleToClient(rect);
m_Form.Controls.Add(ctrl);
ctrl.BringToFront();
m_tracker.m_rect = rect;
m_seletedCtrl = ctrl;
m_FormTracker.Clear();
MainForm.m_propertyWindow.SetSelectedObject(ctrl);
*/
InvalidateEx();
}
public void Cut()
{
if(m_seletedCtrl != null)
{
Copy();
Delete();
}
}
public void Copy()
{
if(m_seletedCtrl != null)
{
//ControlFactory.CopyCtrl2ClipBoard(m_seletedCtrl);
}
}
public void Paste()
{
/*Control ctrl = ControlFactory.GetCtrlFromClipBoard() as Control;
Rectangle rcObject = ctrl.Bounds;
rcObject.Offset(10,10);
ctrl.SetBounds(rcObject.X,rcObject.Y,rcObject.Width,rcObject.Height);
m_Form.Controls.Add(ctrl);
ctrl.BringToFront();
;
rcObject = m_Form.RectangleToScreen(rcObject);
rcObject = this.RectangleToClient(rcObject);
m_tracker.m_rect = rcObject;
m_seletedCtrl = ctrl;
MainForm.m_propertyWindow.SetSelectedObject(m_seletedCtrl);
*/
InvalidateEx();
}
public void Delete()
{
if(m_seletedCtrl != null)
{
m_Form.Controls.Remove(m_seletedCtrl);
m_seletedCtrl = null;
// MainForm.m_propertyWindow.SetSelectedObject(m_Form);
m_FormTracker.m_rect = GetFormRect();
InvalidateEx();
}
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// NotaryJurisdictionList
/// </summary>
[DataContract]
public partial class NotaryJurisdictionList : IEquatable<NotaryJurisdictionList>, IValidatableObject
{
public NotaryJurisdictionList()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="NotaryJurisdictionList" /> class.
/// </summary>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="NotaryJurisdictions">NotaryJurisdictions.</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public NotaryJurisdictionList(string EndPosition = default(string), string NextUri = default(string), List<NotaryJurisdiction> NotaryJurisdictions = default(List<NotaryJurisdiction>), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string))
{
this.EndPosition = EndPosition;
this.NextUri = NextUri;
this.NotaryJurisdictions = NotaryJurisdictions;
this.PreviousUri = PreviousUri;
this.ResultSetSize = ResultSetSize;
this.StartPosition = StartPosition;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// Gets or Sets NotaryJurisdictions
/// </summary>
[DataMember(Name="notaryJurisdictions", EmitDefaultValue=false)]
public List<NotaryJurisdiction> NotaryJurisdictions { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class NotaryJurisdictionList {\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" NotaryJurisdictions: ").Append(NotaryJurisdictions).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as NotaryJurisdictionList);
}
/// <summary>
/// Returns true if NotaryJurisdictionList instances are equal
/// </summary>
/// <param name="other">Instance of NotaryJurisdictionList to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(NotaryJurisdictionList other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.NotaryJurisdictions == other.NotaryJurisdictions ||
this.NotaryJurisdictions != null &&
this.NotaryJurisdictions.SequenceEqual(other.NotaryJurisdictions)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.NotaryJurisdictions != null)
hash = hash * 59 + this.NotaryJurisdictions.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Util;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using Console = Lucene.Net.Support.SystemConsole;
using Occur = Lucene.Net.Search.Occur;
namespace Lucene.Net
{
/*
* 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>
/// JUnit adaptation of an older test case SearchTest. </summary>
public class TestSearch_ : LuceneTestCase
{
[Test]
public virtual void TestNegativeQueryBoost()
{
Query q = new TermQuery(new Term("foo", "bar"));
q.Boost = -42f;
Assert.AreEqual(-42f, q.Boost, 0.0f);
Store.Directory directory = NewDirectory();
try
{
Analyzer analyzer = new MockAnalyzer(Random());
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
IndexWriter writer = new IndexWriter(directory, conf);
try
{
Documents.Document d = new Documents.Document();
d.Add(NewTextField("foo", "bar", Field.Store.YES));
writer.AddDocument(d);
}
finally
{
writer.Dispose();
}
IndexReader reader = DirectoryReader.Open(directory);
try
{
IndexSearcher searcher = NewSearcher(reader);
ScoreDoc[] hits = searcher.Search(q, null, 1000).ScoreDocs;
Assert.AreEqual(1, hits.Length);
Assert.IsTrue(hits[0].Score < 0, "score is not negative: " + hits[0].Score);
Explanation explain = searcher.Explain(q, hits[0].Doc);
Assert.AreEqual(hits[0].Score, explain.Value, 0.001f, "score doesn't match explanation");
Assert.IsTrue(explain.IsMatch, "explain doesn't think doc is a match");
}
finally
{
reader.Dispose();
}
}
finally
{
directory.Dispose();
}
}
/// <summary>
/// this test performs a number of searches. It also compares output
/// of searches using multi-file index segments with single-file
/// index segments.
///
/// TODO: someone should check that the results of the searches are
/// still correct by adding assert statements. Right now, the test
/// passes if the results are the same between multi-file and
/// single-file formats, even if the results are wrong.
/// </summary>
[Test]
public virtual void TestSearch()
{
StringWriter sw;
string multiFileOutput;
string singleFileOutput;
using (sw = new StringWriter())
{
DoTestSearch(Random(), sw, false);
multiFileOutput = sw.ToString();
}
//System.out.println(multiFileOutput);
using (sw = new StringWriter())
{
DoTestSearch(Random(), sw, true);
singleFileOutput = sw.ToString();
}
Assert.AreEqual(multiFileOutput, singleFileOutput);
}
private void DoTestSearch(Random random, StringWriter @out, bool useCompoundFile)
{
Store.Directory directory = NewDirectory();
Analyzer analyzer = new MockAnalyzer(random);
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
MergePolicy mp = conf.MergePolicy;
mp.NoCFSRatio = useCompoundFile ? 1.0 : 0.0;
IndexWriter writer = new IndexWriter(directory, conf);
string[] docs = new string[] { "a b c d e", "a b c d e a b c d e", "a b c d e f g h i j", "a c e", "e c a", "a c e a c e", "a c e a b c" };
for (int j = 0; j < docs.Length; j++)
{
Documents.Document d = new Documents.Document();
d.Add(NewTextField("contents", docs[j], Field.Store.YES));
d.Add(NewStringField("id", "" + j, Field.Store.NO));
writer.AddDocument(d);
}
writer.Dispose();
IndexReader reader = DirectoryReader.Open(directory);
IndexSearcher searcher = NewSearcher(reader);
ScoreDoc[] hits = null;
Sort sort = new Sort(SortField.FIELD_SCORE, new SortField("id", SortFieldType.INT32));
foreach (Query query in BuildQueries())
{
@out.WriteLine("Query: " + query.ToString("contents"));
if (VERBOSE)
{
Console.WriteLine("TEST: query=" + query);
}
hits = searcher.Search(query, null, 1000, sort).ScoreDocs;
@out.WriteLine(hits.Length + " total results");
for (int i = 0; i < hits.Length && i < 10; i++)
{
Documents.Document d = searcher.Doc(hits[i].Doc);
@out.WriteLine(i + " " + hits[i].Score + " " + d.Get("contents"));
}
}
reader.Dispose();
directory.Dispose();
}
private IList<Query> BuildQueries()
{
IList<Query> queries = new List<Query>();
BooleanQuery booleanAB = new BooleanQuery();
booleanAB.Add(new TermQuery(new Term("contents", "a")), Occur.SHOULD);
booleanAB.Add(new TermQuery(new Term("contents", "b")), Occur.SHOULD);
queries.Add(booleanAB);
PhraseQuery phraseAB = new PhraseQuery();
phraseAB.Add(new Term("contents", "a"));
phraseAB.Add(new Term("contents", "b"));
queries.Add(phraseAB);
PhraseQuery phraseABC = new PhraseQuery();
phraseABC.Add(new Term("contents", "a"));
phraseABC.Add(new Term("contents", "b"));
phraseABC.Add(new Term("contents", "c"));
queries.Add(phraseABC);
BooleanQuery booleanAC = new BooleanQuery();
booleanAC.Add(new TermQuery(new Term("contents", "a")), Occur.SHOULD);
booleanAC.Add(new TermQuery(new Term("contents", "c")), Occur.SHOULD);
queries.Add(booleanAC);
PhraseQuery phraseAC = new PhraseQuery();
phraseAC.Add(new Term("contents", "a"));
phraseAC.Add(new Term("contents", "c"));
queries.Add(phraseAC);
PhraseQuery phraseACE = new PhraseQuery();
phraseACE.Add(new Term("contents", "a"));
phraseACE.Add(new Term("contents", "c"));
phraseACE.Add(new Term("contents", "e"));
queries.Add(phraseACE);
return queries;
}
}
}
| |
//! \file ArcCommon.cs
//! \date Tue Aug 19 09:45:38 2014
//! \brief Classes and functions common for various resource files.
//
// Copyright (C) 2014-2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using GameRes.Utility;
using System;
using System.IO;
using System.Linq;
using System.ComponentModel.Composition;
namespace GameRes.Formats
{
public class AutoEntry : Entry
{
private Lazy<IResource> m_res;
private Lazy<string> m_name;
private Lazy<string> m_type;
public override string Name
{
get { return m_name.Value; }
set { m_name = new Lazy<string> (() => value); }
}
public override string Type
{
get { return m_type.Value; }
set { m_type = new Lazy<string> (() => value); }
}
public AutoEntry (string name, Func<IResource> type_checker)
{
m_res = new Lazy<IResource> (type_checker);
m_name = new Lazy<string> (() => GetName (name));
m_type = new Lazy<string> (GetEntryType);
}
public static AutoEntry Create (ArcView file, long offset, string base_name)
{
return new AutoEntry (base_name, () => DetectFileType (file.View.ReadUInt32 (offset))) { Offset = offset };
}
public static IResource DetectFileType (uint signature)
{
if (0 == signature) return null;
// resolve some special cases first
if (OggAudio.Instance.Signature == signature)
return OggAudio.Instance;
if (AudioFormat.Wav.Signature == signature)
return AudioFormat.Wav;
if (0x4D42 == (signature & 0xFFFF)) // 'BM'
return ImageFormat.Bmp;
var res = FormatCatalog.Instance.LookupSignature (signature);
if (!res.Any())
return null;
if (res.Skip (1).Any()) // type is ambiguous
return null;
return res.First();
}
private string GetName (string name)
{
if (null == m_res.Value)
return name;
var ext = m_res.Value.Extensions.FirstOrDefault();
if (string.IsNullOrEmpty (ext))
return name;
return Path.ChangeExtension (name, ext);
}
private string GetEntryType ()
{
return null == m_res.Value ? "" : m_res.Value.Type;
}
}
public static class StringExtensions
{
/// <summary>
/// Check if <paramref name="filename"/> has specified extension <param name="ext"/>.
/// </summary>
public static bool HasExtension (this string filename, string ext)
{
bool ext_is_empty = string.IsNullOrEmpty (ext);
if (!ext_is_empty && '.' == ext[0])
return filename.EndsWith (ext, StringComparison.InvariantCultureIgnoreCase);
int ext_start = GetExtensionIndex (filename);
// filename extension length
int l_ext_length = filename.Length - ext_start;
if (ext_is_empty)
return 0 == l_ext_length;
return (l_ext_length == ext.Length
&& filename.EndsWith (ext, StringComparison.InvariantCultureIgnoreCase));
}
/// <summary>
/// Check if filename ends with any of the extensions from the <paramref name="ext_list"/>.
/// </summary>
public static bool HasAnyOfExtensions (this string filename, params string[] ext_list)
{
int ext_start = GetExtensionIndex (filename);
int l_ext_length = filename.Length - ext_start;
foreach (string ext in ext_list)
{
if (string.IsNullOrEmpty (ext) || "." == ext)
{
if (0 == l_ext_length)
return true;
}
else if ('.' == ext[0] || l_ext_length == ext.Length)
{
if (filename.EndsWith (ext, StringComparison.InvariantCultureIgnoreCase))
return true;
}
}
return false;
}
internal static int GetExtensionIndex (string filename)
{
int name_start = filename.LastIndexOfAny (VFS.PathSeparatorChars);
if (-1 == name_start)
name_start = 0;
else
name_start++;
if (filename.Length == name_start) // path ends with '\'
return name_start;
int ext_start = filename.LastIndexOf ('.', filename.Length-1, filename.Length - name_start);
if (-1 == ext_start)
return filename.Length;
else
return ext_start + 1;
}
/// <summary>
/// Returns copy of this string with ASCII characters converted to lower case.
/// </summary>
public static string ToLowerAscii (this string str)
{
int i;
for (i = 0; i < str.Length; ++i)
{
if (str[i] >= 'A' && str[i] <= 'Z')
break;
}
if (i == str.Length)
return str;
var builder = new System.Text.StringBuilder (str, 0, i, str.Length);
builder.Append ((char)(str[i++] | 0x20));
while (i < str.Length)
{
char c = str[i];
if (c >= 'A' && c <= 'Z')
c = (char)(c | 0x20);
builder.Append (c);
++i;
}
return builder.ToString();
}
/// <summary>
/// Returns string in Shift-JIS encoding with ASCII characters converted to lower case.
/// </summary>
public static byte[] ToLowerShiftJis (this string text)
{
var text_bytes = Encodings.cp932.GetBytes (text);
text_bytes.ToLowerShiftJis();
return text_bytes;
}
public static void ToLowerShiftJis (this byte[] text_bytes)
{
for (int i = 0; i < text_bytes.Length; ++i)
{
byte c = text_bytes[i];
if (c >= 'A' && c <= 'Z')
text_bytes[i] += 0x20;
else if (c > 0x7F && c < 0xA1 || c > 0xDF)
++i;
}
}
}
/// <summary>
/// Create stream in TGA format from the given image pixels.
/// </summary>
[Obsolete]
public static class TgaStream
{
public static Stream Create (ImageMetaData info, byte[] pixels, bool flipped = false)
{
var header = new byte[0x12];
header[2] = (byte)(info.BPP > 8 ? 2 : 3);
LittleEndian.Pack ((short)info.OffsetX, header, 8);
LittleEndian.Pack ((short)info.OffsetY, header, 0xa);
LittleEndian.Pack ((ushort)info.Width, header, 0xc);
LittleEndian.Pack ((ushort)info.Height, header, 0xe);
header[0x10] = (byte)info.BPP;
if (!flipped)
header[0x11] = 0x20;
return new PrefixStream (header, new MemoryStream (pixels));
}
public static Stream Create (ImageMetaData info, int stride, byte[] pixels, bool flipped = false)
{
int tga_stride = (int)info.Width * info.BPP / 8;
if (stride != tga_stride)
{
var adjusted = new byte[tga_stride * (int)info.Height];
int src = 0;
int dst = 0;
for (uint y = 0; y < info.Height; ++y)
{
Buffer.BlockCopy (pixels, src, adjusted, dst, tga_stride);
src += stride;
dst += tga_stride;
}
pixels = adjusted;
}
return Create (info, pixels, flipped);
}
}
public static class MMX
{
public static ulong PAddB (ulong x, ulong y)
{
ulong r = 0;
for (ulong mask = 0xFF; mask != 0; mask <<= 8)
{
r |= ((x & mask) + (y & mask)) & mask;
}
return r;
}
public static uint PAddB (uint x, uint y)
{
uint r13 = (x & 0xFF00FF00u) + (y & 0xFF00FF00u);
uint r02 = (x & 0x00FF00FFu) + (y & 0x00FF00FFu);
return (r13 & 0xFF00FF00u) | (r02 & 0x00FF00FFu);
}
public static ulong PAddW (ulong x, ulong y)
{
ulong mask = 0xffff;
ulong r = ((x & mask) + (y & mask)) & mask;
mask <<= 16;
r |= ((x & mask) + (y & mask)) & mask;
mask <<= 16;
r |= ((x & mask) + (y & mask)) & mask;
mask <<= 16;
r |= ((x & mask) + (y & mask)) & mask;
return r;
}
public static ulong PAddD (ulong x, ulong y)
{
ulong mask = 0xffffffff;
ulong r = ((x & mask) + (y & mask)) & mask;
mask <<= 32;
return r | ((x & mask) + (y & mask)) & mask;
}
public static ulong PSubB (ulong x, ulong y)
{
ulong r = 0;
for (ulong mask = 0xFF; mask != 0; mask <<= 8)
{
r |= ((x & mask) - (y & mask)) & mask;
}
return r;
}
public static ulong PSubW (ulong x, ulong y)
{
ulong mask = 0xffff;
ulong r = ((x & mask) - (y & mask)) & mask;
mask <<= 16;
r |= ((x & mask) - (y & mask)) & mask;
mask <<= 16;
r |= ((x & mask) - (y & mask)) & mask;
mask <<= 16;
r |= ((x & mask) - (y & mask)) & mask;
return r;
}
public static ulong PSubD (ulong x, ulong y)
{
ulong mask = 0xffffffff;
ulong r = ((x & mask) - (y & mask)) & mask;
mask <<= 32;
return r | ((x & mask) - (y & mask)) & mask;
}
public static ulong PSllD (ulong x, int count)
{
count &= 0x1F;
ulong mask = 0xFFFFFFFFu << count;
mask |= mask << 32;
return (x << count) & mask;
}
public static ulong PSrlD (ulong x, int count)
{
count &= 0x1F;
ulong mask = 0xFFFFFFFFu >> count;
mask |= mask << 32;
return (x >> count) & mask;
}
}
public static class Dump
{
public static string DirectoryName = Environment.GetFolderPath (Environment.SpecialFolder.UserProfile);
[System.Diagnostics.Conditional("DEBUG")]
public static void Write (byte[] mem, string filename = "index.dat")
{
using (var dump = File.Create (Path.Combine (DirectoryName, filename)))
dump.Write (mem, 0, mem.Length);
}
}
[Export(typeof(ScriptFormat))]
public class DataFileFormat : GenericScriptFormat
{
public override string Type { get { return ""; } }
public override string Tag { get { return "DAT/GENERIC"; } }
public override string Description { get { return "Unidentified data file"; } }
public override uint Signature { get { return 0; } }
}
}
| |
namespace MiniUML.Model.ViewModels.Shapes
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Xml;
using MiniUML.Framework;
using MiniUML.Framework.Command;
using MiniUML.Model.ViewModels.Interfaces;
/// <summary>
/// Base class to manage data items for
/// each shape that is visible and resizeable on the canvas.
/// </summary>
public abstract class ShapeViewModelBase : BaseViewModel, IShapeViewModelBase
{
#region fields
private readonly ObservableCollection<ShapeViewModelBase> mElements = new ObservableCollection<ShapeViewModelBase>();
private string _ID = string.Empty;
private string _TypeKey = string.Empty;
private string _UmlControlKey = string.Empty;
private string _Name = string.Empty;
private bool _IsSelected = false;
private double _Left = 0;
private double _Top = 0;
private RelayCommand<object> _BringToFront = null;
private RelayCommand<object> _SendToBack = null;
private IShapeParent _Parent = null;
#endregion fields
#region constructor
/// <summary>
/// Standard contructor
/// </summary>
public ShapeViewModelBase(IShapeParent parent)
{
this._Parent = parent;
}
#endregion constructor
#region properties
/// <summary>
/// Name of XML element that will repesent this object in data.
/// </summary>
public abstract string XElementName
{
get;
}
/// <summary>
/// Get/set unique identifier for this shape.
/// </summary>
public string ID
{
get
{
return this._ID;
}
set
{
if (this._ID != value)
{
this._ID = value;
this.NotifyPropertyChanged(() => this.ID);
}
}
}
public abstract string TypeKey { get; }
/// <summary>
/// Get/set label (short string that is usually
/// displayed below shape) for this shape.
/// </summary>
public string Name
{
get
{
return this._Name;
}
set
{
if (this._Name != value)
{
this._Name = value;
this.NotifyPropertyChanged(() => this.Name);
}
}
}
#region shape position
/// <summary>
/// Get/set X-positon of this shape.
/// </summary>
public double Left
{
get
{
return this._Left;
}
set
{
if (_Left != value)
{
_Left = value;
NotifyPropertyChanged(() => Left);
NotifyPropertyChanged(() => Position);
}
}
}
/// <summary>
/// Get/set Y-positon of this shape.
/// </summary>
public double Top
{
get
{
return this._Top;
}
set
{
if (_Top != value)
{
_Top = value;
NotifyPropertyChanged(() => Top);
NotifyPropertyChanged(() => Position);
}
}
}
/// <summary>
/// Get/set X,Y-positon of this shape.
/// </summary>
public Point Position
{
get
{
return new Point(Left, Top);
}
set
{
if (Point.Equals(value, new Point(Left, Top)) == false)
{
Left = value.X;
Top = value.Y;
NotifyPropertyChanged(() => Position);
NotifyPropertyChanged(() => Top);
NotifyPropertyChanged(() => Left);
}
}
}
#endregion shape position
/// <summary>
/// Get/set whether this shape is currently selected or not.
/// </summary>
public bool IsSelected
{
get
{
return _IsSelected;
}
internal set
{
if (_IsSelected != value)
{
_IsSelected = value;
NotifyPropertyChanged(() => IsSelected);
}
}
}
#region Commands
/// <summary>
/// Get ICommand that implements Bring to Front functinoality for this shape.
/// </summary>
public RelayCommand<object> BringToFront
{
get
{
if (_BringToFront == null)
_BringToFront = new RelayCommand<object>(p => this.BringToFront_Executed());
return _BringToFront;
}
}
/// <summary>
/// Get ICommand that implements Send to Back functinoality for this shape.
/// </summary>
public RelayCommand<object> SendToBack
{
get
{
if (this._SendToBack == null)
this._SendToBack = new RelayCommand<object>(p => this.SendToBack_Executed());
return this._SendToBack;
}
}
#endregion Commands
/// <summary>
/// Get first child node (if any) or null.
/// (Simple clr - Non-viewmodel property)
/// </summary>
/// <returns></returns>
public ShapeViewModelBase FirstNode
{
get
{
if (this.mElements.Count == 0)
return null;
return this.mElements[0];
}
}
/// <summary>
/// Get last child node (if any) or null.
/// (Simple clr - Non-viewmodel property)
/// </summary>
/// <returns></returns>
public ShapeViewModelBase LastNode
{
get
{
if (this.mElements.Count == 0)
return null;
return this.mElements[this.mElements.Count - 1];
}
}
protected IShapeParent Parent
{
get
{
return this._Parent;
}
}
#endregion properties
#region methods
/// <summary>
/// Add child objects
/// into the collection of child objects.
/// </summary>
/// <param name="shape"></param>
public void Add(ShapeViewModelBase shape)
{
this.mElements.Add(shape);
}
/// <summary>
/// Add child objects from a given collection
/// into the collection of child objects.
/// </summary>
/// <param name="shapes"></param>
public void Add(IEnumerable<ShapeViewModelBase> shapes)
{
if (shapes != null)
{
foreach (var item in shapes)
{
this.mElements.Add(item);
}
}
}
/// <summary>
/// Remove this object instance from the parent (if any)
/// </summary>
public void Remove()
{
if (this._Parent != null)
this._Parent.Remove(this);
}
/// <summary>
/// Persist the contents of this object into the given
/// parameter <paramref name="writer"/> object.
///
/// Inheriting classes have to overwrite this method to provide
/// their custom persistence method.
/// </summary>
/// <param name="writer"></param>
public abstract void SaveDocument(XmlWriter writer, IEnumerable<ShapeViewModelBase> root);
/// <summary>
/// Gets a collection of shapes stored in this shapes object.
/// </summary>
/// <returns></returns>
public IEnumerable<ShapeViewModelBase> Elements()
{
return (IEnumerable<ShapeViewModelBase>)this.mElements;
}
/// <summary>
/// Gets a count of the elements in the <see cref="Elements"/> collection.
/// </summary>
/// <returns></returns>
public int ElementsCount()
{
return this.mElements.Count;
}
/// <summary>
/// Brings the shape into front of the canvas view
/// (moves shape on top of virtual Z-axis)
/// </summary>
protected void BringToFront_Executed()
{
if (this._Parent != null)
this._Parent.BringToFront(this);
}
/// <summary>
/// Brings the shape into the back of the canvas view
/// (moves shape to the bottom of virtual Z-axis)
/// </summary>
protected void SendToBack_Executed()
{
if (this._Parent != null)
this._Parent.SendToBack(this);
}
#endregion methods
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Calendar.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Design;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using WebCntrls = System.Web.UI.WebControls;
using System.Security.Permissions;
namespace System.Web.UI.MobileControls
{
/*
* Mobile Calendar class.
* The Calendar control allows developers to easily add date picking
* functionality to a Mobile application.
*
* Copyright (c) 2000 Microsoft Corporation
*/
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar"]/*' />
[
DataBindingHandler(typeof(System.Web.UI.Design.MobileControls.CalendarDataBindingHandler)),
DefaultEvent("SelectionChanged"),
DefaultProperty("SelectedDate"),
Designer(typeof(System.Web.UI.Design.MobileControls.CalendarDesigner)),
DesignerAdapter(typeof(System.Web.UI.Design.MobileControls.Adapters.DesignerCalendarAdapter)),
ToolboxData("<{0}:Calendar runat=\"server\"></{0}:Calendar>"),
ToolboxItem("System.Web.UI.Design.WebControlToolboxItem, " + AssemblyRef.SystemDesign)
]
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public class Calendar : MobileControl, IPostBackEventHandler
{
private WebCntrls.Calendar _webCalendar;
// Static objects to identify individual events stored in Events
// property.
private static readonly Object EventSelectionChanged = new Object();
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.Calendar"]/*' />
public Calendar() : base()
{
_webCalendar = CreateWebCalendar();
_webCalendar.Visible = false;
Controls.Add(_webCalendar);
// Adding wrapper event handlers for event properties exposed by
// the aggregated control. For more details about the mechanism,
// please see the comment in the constructor of
// Mobile.UI.AdRotator.
EventHandler eventHandler =
new EventHandler(WebSelectionChanged);
_webCalendar.SelectionChanged += eventHandler;
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.CreateWebCalendar"]/*' />
protected virtual WebCntrls.Calendar CreateWebCalendar()
{
return new WebCntrls.Calendar();
}
/////////////////////////////////////////////////////////////////////
// Mimic some of the properties exposed in the original Web Calendar
// control. Only those properties that are meaningful and useful to
// mobile device adapters are exposed. Other properties, which are
// used mostly for the complex HTML specific rendering (like the one
// rendered by WebForms Calendar), can be set via the property that
// exposed the aggregated WebForms Calendar directly.
//
// Most properties are got and set directly from the original Calendar
// control. For event properties, event references are stored locally
// as they cannot be returned from the aggregated child control.
/////////////////////////////////////////////////////////////////////
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.WebCalendar"]/*' />
[
Bindable(false),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public WebCntrls.Calendar WebCalendar
{
get
{
return _webCalendar;
}
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.FirstDayOfWeek"]/*' />
[
Bindable(true),
DefaultValue(FirstDayOfWeek.Default),
MobileCategory(SR.Category_Appearance),
MobileSysDescription(SR.Calendar_FirstDayOfWeek)
]
public FirstDayOfWeek FirstDayOfWeek
{
get
{
return _webCalendar.FirstDayOfWeek;
}
set
{
_webCalendar.FirstDayOfWeek = value;
}
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.SelectedDate"]/*' />
[
Bindable(true),
DefaultValue(typeof(DateTime), "1/1/0001"),
MobileSysDescription(SR.Calendar_SelectedDate)
]
public DateTime SelectedDate
{
get
{
return _webCalendar.SelectedDate;
}
set
{
_webCalendar.SelectedDate = value;
}
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.SelectedDates"]/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
public SelectedDatesCollection SelectedDates
{
get
{
return _webCalendar.SelectedDates;
}
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.SelectionMode"]/*' />
[
Bindable(true),
DefaultValue(CalendarSelectionMode.Day),
MobileCategory(SR.Category_Behavior),
MobileSysDescription(SR.Calendar_SelectionMode)
]
public CalendarSelectionMode SelectionMode
{
get
{
return _webCalendar.SelectionMode;
}
set
{
_webCalendar.SelectionMode = value;
}
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.ShowDayHeader"]/*' />
[
Bindable(true),
DefaultValue(true),
MobileCategory(SR.Category_Appearance),
MobileSysDescription(SR.Calendar_ShowDayHeader)
]
public bool ShowDayHeader
{
get
{
return _webCalendar.ShowDayHeader;
}
set
{
_webCalendar.ShowDayHeader = value;
}
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.VisibleDate"]/*' />
[
Bindable(true),
DefaultValue(typeof(DateTime), "1/1/0001"),
MobileSysDescription(SR.Calendar_VisibleDate)
]
public DateTime VisibleDate
{
get
{
return _webCalendar.VisibleDate;
}
set
{
_webCalendar.VisibleDate = value;
}
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.CalendarEntryText"]/*' />
[
Bindable(true),
DefaultValue(""),
MobileCategory(SR.Category_Appearance),
MobileSysDescription(SR.Calendar_CalendarEntryText)
]
public String CalendarEntryText
{
get
{
String s = (String) ViewState["CalendarEntryText"];
return((s != null) ? s : String.Empty);
}
set
{
ViewState["CalendarEntryText"] = value;
}
}
/////////////////////////////////////////////////////////////////////
// BEGIN STYLE PROPERTIES
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// END STYLE PROPERTIES
/////////////////////////////////////////////////////////////////////
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.SelectionChanged"]/*' />
[
MobileCategory(SR.Category_Action),
MobileSysDescription(SR.Calendar_OnSelectionChanged)
]
public event EventHandler SelectionChanged
{
add
{
Events.AddHandler(EventSelectionChanged, value);
}
remove
{
Events.RemoveHandler(EventSelectionChanged, value);
}
}
// protected method (which can be overridden by subclasses) for
// raising user events
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.OnSelectionChanged"]/*' />
protected virtual void OnSelectionChanged()
{
EventHandler handler = (EventHandler)Events[EventSelectionChanged];
if (handler != null)
{
handler(this, new EventArgs());
}
}
private void WebSelectionChanged(Object sender, EventArgs e)
{
// Invoke user events for further manipulation specified by user
OnSelectionChanged();
}
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.IPostBackEventHandler.RaisePostBackEvent"]/*' />
/// <internalonly/>
protected void RaisePostBackEvent(String eventArgument)
{
// There can be cases that the original form is
// involved in the generation of multiple cards in the same WML
// deck. Here is to reset the right active form.
if (MobilePage.ActiveForm != Form)
{
MobilePage.ActiveForm = Form;
}
Adapter.HandlePostBackEvent(eventArgument);
}
// A wrapper to raise the SelectionChangedEvent when a date is selected
// by the user. This can be called by different adapters when they have
// collected the selected date.
/// <include file='doc\Calendar.uex' path='docs/doc[@for="Calendar.RaiseSelectionChangedEvent"]/*' />
public void RaiseSelectionChangedEvent()
{
WebSelectionChanged(this, new EventArgs());
}
#region IPostBackEventHandler implementation
void IPostBackEventHandler.RaisePostBackEvent(String eventArgument) {
RaisePostBackEvent(eventArgument);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEditor;
using System.Collections.Generic;
using System;
using UnityEditorInternal;
using CurveExtended;
using LitJson;
using UnityEditor.Animations;
namespace UnitySpineImporter{
public class AtlasImageNotFoundException: System.Exception{
public AtlasImageNotFoundException(string message):base(message){
}
}
public class AtlasImageDuplicateSpriteName:System.Exception{
public AtlasImageDuplicateSpriteName(string message):base(message){
}
}
public class SpineUtil {
public static string SLOT_PREFIX = "slot";
public static string SKIN_PREFIX = "skin";
public static string ANIMATION_FOLDER = "animation";
public static string SLASH_REPLACEMENT = "|";
public static Vector2 lineToVector2(string line){
string[] xy = null;
try{
line = line.Split(':')[1];
xy = line.Split(',');
} finally{
}
return new Vector2(int.Parse(xy[0]), int.Parse( xy[1]));
}
public static void buildPrefab(GameObject gameObject, string directory, string name){
string prefabPath = directory + "/" + name + ".prefab";
UnityEngine.Object oldPrefab = AssetDatabase.LoadAssetAtPath( prefabPath, typeof(GameObject));
if (oldPrefab == null)
PrefabUtility.CreatePrefab(prefabPath, gameObject, ReplacePrefabOptions.ConnectToPrefab);
else
PrefabUtility.ReplacePrefab(gameObject, oldPrefab, ReplacePrefabOptions.ReplaceNameBased);
}
public static void builAvatarMask(GameObject gameObject, SpineData spineData, Animator animator, string directory, string name){
Avatar avatar = AvatarBuilder.BuildGenericAvatar(gameObject,"");
animator.avatar = avatar;
AvatarMask avatarMask = new AvatarMask();
string[] transofrmPaths = getTransformPaths(gameObject, spineData);
avatarMask.transformCount = transofrmPaths.Length;
for (int i=0; i< transofrmPaths.Length; i++){
avatarMask.SetTransformPath(i, transofrmPaths[i]);
avatarMask.SetTransformActive(i, true);
}
createFolderIfNoExists(directory, ANIMATION_FOLDER);
AssetDatabase.CreateAsset(avatar , directory + "/" + ANIMATION_FOLDER + "/" + name + ".anim.asset");
AssetDatabase.CreateAsset(avatarMask, directory + "/" + ANIMATION_FOLDER + "/" + name + ".mask.asset");
}
public static string[] getTransformPaths(GameObject go, SpineData spineData){
List<String> result = new List<string>();
result.Add("");
foreach(Transform t in go.GetComponentsInChildren<Transform>(true)){
string path = AnimationUtility.CalculateTransformPath(t,go.transform);
if (t.name.StartsWith(SLOT_PREFIX+" [") && t.name.EndsWith("]")){
string slotName = t.name.Remove(t.name.Length -1);
slotName = slotName.Remove(0,(SLOT_PREFIX+" [").Length );
if (spineData.slotPathByName.ContainsKey(slotName) && spineData.slotPathByName[slotName]==path)
result.Add(path);
}else {
if (spineData.bonePathByName.ContainsKey(t.name) && spineData.bonePathByName[t.name]==path)
result.Add(path);
}
}
return result.ToArray();
}
static int[] sizes = new int[]{0, 32, 64, 128, 256, 512, 1024, 2048, 4096};
static string[] platforms = new string[]{"Web", "Standalone", "iPhone", "Android", "FlashPlayer"};
static void fixTextureSize(string imagePath){
TextureImporter importer = TextureImporter.GetAtPath(imagePath) as TextureImporter;
if (importer != null) {
int width, height;
UnityInternalMethods.GetTextureSize(importer, out width, out height);
int max = Mathf.Max(width,height);
if (max > 4096){
Debug.LogError("original texture size is to big " + imagePath + " size=" + width + "x" + height);
return;
}
int fitSize = 0;
for (int i = 0,nextI =1; i < max && fitSize==0; i=nextI++ ) {
if (max > sizes[i] && max <= sizes[nextI] )
fitSize = sizes[nextI];
}
if (importer.maxTextureSize!=fitSize){
Debug.LogWarning("change default size to " + fitSize+ " for "+imagePath);
importer.maxTextureSize = fitSize;
}
foreach(string platform in platforms){
int maxTextureSize;
TextureImporterFormat textureFormat;
importer.GetPlatformTextureSettings(platform, out maxTextureSize, out textureFormat);
if (maxTextureSize != fitSize){
Debug.LogWarning("change specific size to " + fitSize + "on " + platform + " for " + imagePath);
importer.SetPlatformTextureSettings(platform, fitSize, textureFormat);
}
}
AssetDatabase.ImportAsset(imagePath, ImportAssetOptions.ForceSynchronousImport);
}
}
public static void updateImporters(SpineMultiatlas multiatlas, string directory, int pixelsPerUnit, out SpritesByName spriteByName){
spriteByName = new SpritesByName();
foreach (SpineAtlas spineAtlas in multiatlas){
string imagePath = directory + "/" + spineAtlas.imageName;
if (!File.Exists(imagePath))
throw new AtlasImageNotFoundException("can't find " + spineAtlas.imageName + " image in " + directory + " folder");
fixTextureSize(imagePath);
Texture2D tex = AssetDatabase.LoadAssetAtPath(imagePath, typeof(Texture2D )) as Texture2D;
Vector2 atlasSize = new Vector2(tex.width, tex.height);
TextureImporter importer = TextureImporter.GetAtPath(imagePath) as TextureImporter;
importer.spritesheet = getSpriteMetadata(spineAtlas, atlasSize);
importer.textureType = TextureImporterType.Sprite;
importer.spriteImportMode = SpriteImportMode.Multiple;
importer.spritePixelsToUnits = pixelsPerUnit;
AssetDatabase.ImportAsset(imagePath, ImportAssetOptions.ForceUpdate);
AssetDatabase.SaveAssets();
foreach(UnityEngine.Object obj in AssetDatabase.LoadAllAssetsAtPath(imagePath)){
Sprite s = obj as Sprite;
if (s!=null){
try{
spriteByName.Add(s.name,s);
} catch (ArgumentException e) {
throw new AtlasImageDuplicateSpriteName("source images has duplicate name "+s.name +"\n"+e);
}
}
}
foreach(SpineSprite spineSprite in spineAtlas.sprites){
if (spineSprite.rotate){
spriteByName.rotatedSprites.Add(spriteByName[spineSprite.name]);
}
}
}
}
public static SpriteMetaData[] getSpriteMetadata(SpineAtlas spineAtlas, Vector2 atlasImageSize){
SpriteMetaData[] result = new SpriteMetaData[spineAtlas.sprites.Count];
SpineSprite spineSprite;
for (int i = 0; i < result.Length; i++) {
spineSprite = spineAtlas.sprites[i];
result[i] = new SpriteMetaData();
result[i].name = spineSprite.name;
result[i].rect = getRectFromSpineSprite(spineSprite, atlasImageSize);
if (spineSprite.orig != spineSprite.size){
result[i].alignment = (int) SpriteAlignment.Custom;
result[i].pivot = getPivotFromSpineSprite(spineSprite);
}
}
return result;
}
public static Rect getRectFromSpineSprite(SpineSprite sprite, Vector2 atlasImageSize){
float x,y,width,height;
x = sprite.xy.x;
width = sprite.size.x;
height = sprite.size.y;
if (sprite.rotate){
y = atlasImageSize.y - sprite.size.x - sprite.xy.y;
swap2Float(ref width, ref height);
}else {
y = atlasImageSize.y - sprite.size.y - sprite.xy.y;
}
return new Rect(x, y, width, height);
}
public static Vector2 getPivotFromSpineSprite(SpineSprite sprite){
float offsetX = sprite.offset.x;
float offsetY = sprite.offset.y;
if (sprite.rotate)
swap2Float(ref offsetX, ref offsetY);
float x = 0.5f + (float)((offsetX + sprite.size.x/2 - sprite.orig.x/2)/ sprite.size.x);
float y = 0.5f + (float)(((sprite.orig.y - offsetY - sprite.size.y/2) - sprite.orig.y / 2)/ sprite.size.y);
if (sprite.rotate)
swap2Float(ref x, ref y);
return new Vector2(x,y);
}
public static void swap2Float(ref float float1, ref float float2){
float tmp = float1;
float1 = float2;
float2 = tmp;
}
public static GameObject buildSceleton( string name, SpineData data, int pixelsPerUnit, float zStep, out Dictionary<string, GameObject> boneGOByName, out Dictionary<string, Slot> slotByName ) {
float ratio = 1.0f / (float)pixelsPerUnit;
boneGOByName = new Dictionary<string, GameObject>();
slotByName = new Dictionary<string, Slot>();
GameObject rootGO = new GameObject(name);
foreach(SpineBone bone in data.bones){
GameObject go = new GameObject(bone.name);
boneGOByName.Add(bone.name, go);
}
foreach(SpineBone bone in data.bones){
GameObject go = boneGOByName[bone.name];
if (bone.parent == null)
go.transform.parent = rootGO.transform;
else
go.transform.parent = boneGOByName[bone.parent].transform;
Vector3 position = new Vector3((float)bone.x * ratio, (float)bone.y * ratio, 0.0f);
Vector3 scale = new Vector3((float)bone.scaleX, (float)bone.scaleY, 1.0f);
Quaternion rotation = Quaternion.Euler(0, 0, (float)bone.rotation);
go.transform.localPosition = position;
go.transform.localScale = scale;
go.transform.localRotation = rotation;
}
foreach(SpineSlot spineSlot in data.slots){
GameObject go = new GameObject(getSlotGOName(spineSlot.name));
go.transform.parent = boneGOByName[spineSlot.bone].transform;
resetLocalTRS(go);
int drawOrder = data.slotOrder[ spineSlot.name ];
go.transform.localPosition = new Vector3( 0, 0, (- drawOrder ) * zStep );
Slot slot = new Slot();
slot.bone = spineSlot.bone;
slot.name = spineSlot.name;
slot.color = hexStringToColor32(spineSlot.color);
slot.gameObject = go;
slot.defaultAttachmentName = spineSlot.attachment;
slotByName.Add(slot.name, slot);
}
return rootGO;
}
public static string getSlotGOName(string slotName){
return SLOT_PREFIX+" ["+slotName+"]";
}
public static void resetLocalTRS(GameObject go){
go.transform.localPosition = Vector3.zero;
go.transform.localRotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
}
public static void addAllAttahcmentsSlots(SpineData spineData, SpritesByName spriteByName, Dictionary<string, Slot> slotByName, int pixelsPerUnit, out List<Skin> skins, out AttachmentGOByNameBySlot attachmentGOByNameBySlot){
float ratio = 1.0f / (float) pixelsPerUnit;
skins = new List<Skin>();
attachmentGOByNameBySlot= new AttachmentGOByNameBySlot();
foreach(KeyValuePair<string, SpineSkinSlots>kvp in spineData.skins){
string skinName = kvp.Key;
Skin skin = new Skin();
skin.name = skinName;
List<SkinSlot> slotList = new List<SkinSlot>();
bool isDefault = skinName.Equals("default");
foreach(KeyValuePair<string, SpineSkinSlotAttachments>kvp2 in spineData.skins[skinName]){
string slotName = kvp2.Key;
GameObject slotGO = slotByName[slotName].gameObject;
Slot slot = slotByName[slotName];
string spritePath = spineData.slotPathByName[ slotName ] + "/";
SkinSlot skinSlot = new SkinSlot();
skinSlot.name = slotName;
skinSlot.gameObject = slotGO;
List<SkinSlotAttachment> attachmentList = new List<SkinSlotAttachment>();
foreach(KeyValuePair<string, SpineSkinAttachment> kvp3 in spineData.skins[skinName][slotName]){
string attachmenName = kvp3.Key;
SkinSlotAttachment attachment = new SkinSlotAttachment();
attachment.name = attachmenName;
SpineSkinAttachment spineAttachment = kvp3.Value;
// - create skined object or direct GO for default skin
Sprite sprite;
spriteByName.TryGetValue(spineAttachment.name, out sprite);
GameObject parentGO;
GameObject spriteGO;
string fixedName = attachmenName.Replace("/",SLASH_REPLACEMENT);
if (isDefault){
parentGO = slotGO;
spriteGO = new GameObject(fixedName);
spritePath += fixedName;
Attachment a = new Attachment(attachmenName, AttachmentType.SINGLE_SPRITE, spriteGO);
slot.addAttachment(a);
} else {
spriteGO = new GameObject(skinName);
Attachment a;
slot.attachmentByName.TryGetValue(attachmenName, out a);
if (a == null){
GameObject attachmentGO = new GameObject(fixedName);
attachmentGO.transform.parent = slotGO.transform;
resetLocalTRS(attachmentGO);
a = new Attachment(attachmenName, AttachmentType.SKINED_SPRITE, attachmentGO);
slot.addAttachment(a);
}
spritePath += fixedName + "/" + skinName;
parentGO = a.gameObject;
}
attachment.gameObject = spriteGO;
attachment.ObPath = spritePath;
spriteGO.transform.parent = parentGO.gameObject.transform;
// -
if (spineAttachment.type.Equals("region")){
SpriteRenderer sr = spriteGO.AddComponent<SpriteRenderer>();
sr.sprite = sprite;
spriteGO.transform.localPosition = getAttachmentPosition(spineAttachment, ratio, 0);
spriteGO.transform.localRotation = getAttachmentRotation(spineAttachment, spriteByName.rotatedSprites.Contains(sprite));
spriteGO.transform.localScale = getAttachmentScale(spineAttachment);
attachment.sprite = sr;
} else if (spineAttachment.type.Equals("boundingbox")) {
PolygonCollider2D collider = spriteGO.AddComponent<PolygonCollider2D>();
resetLocalTRS(spriteGO);
Vector2[] vertices = new Vector2[spineAttachment.vertices.Length/2];
for (int i = 0; i < spineAttachment.vertices.Length; i+=2) {
float x = (float) spineAttachment.vertices[i ] * ratio;
float y = (float) spineAttachment.vertices[i+1] * ratio;
vertices[i/2] = new Vector2(x,y);
}
collider.points = vertices;
collider.SetPath(0,vertices);
}else {
Debug.LogWarning("Attachment type " + spineAttachment.type + " is not supported yiet FIX MEEE");
}
attachmentList.Add(attachment);
}
skinSlot.attachments = attachmentList.ToArray();
slotList.Add(skinSlot);
}
skin.slots = slotList.ToArray();
skins.Add(skin);
}
}
public static SkinController addSkinController(GameObject gameObject, SpineData spineData, List<Skin> allSkins, Dictionary<string, Slot> slotByName){
SkinController sk = gameObject.AddComponent<SkinController>();
List<Skin> skins = new List<Skin>();
Skin defaultSkin = null;
foreach(Skin skin in allSkins){
if (skin.name.Equals("default")){
defaultSkin = skin;
} else {
skins.Add(skin);
}
}
sk.defaultSkin = defaultSkin;
sk.skins = skins.ToArray();
Slot[] slots = new Slot[slotByName.Count];
slotByName.Values.CopyTo(slots,0);
sk.slots = slots;
return sk;
}
public static Animator addAnimator(GameObject go){
Animator result = go.GetComponent<Animator>();
if (result == null)
result = go.AddComponent<Animator>();
return result;
}
public static void addAnimation(GameObject rootGO,
string rootDirectory,
SpineData spineData,
Dictionary<string, GameObject> boneGOByName,
Dictionary<string, Slot> slotByName,
AttachmentGOByNameBySlot attachmentGOByNameBySlot,
List<Skin> skinList,
int pixelsPerUnit,
float zStep,
bool useLegacyAnimation,
bool updateResources)
{
float ratio = 1.0f / (float)pixelsPerUnit;
foreach(KeyValuePair<string,SpineAnimation> kvp in spineData.animations){
string animationName = kvp.Key;
string animationFolder = rootDirectory+"/"+ANIMATION_FOLDER;
string assetPath = animationFolder + "/" + animationName+".anim";
SpineAnimation spineAnimation = kvp.Value;
AnimationClip animationClip = new AnimationClip();
bool updateCurve = false;
if (File.Exists(assetPath)){
AnimationClip oldClip = AssetDatabase.LoadAssetAtPath(assetPath, typeof(AnimationClip)) as AnimationClip;
if (oldClip != null){
animationClip = oldClip;
animationClip.ClearCurves();
updateCurve = true;
}
}
animationClip.legacy = useLegacyAnimation;
if (spineAnimation.bones!=null)
addBoneAnimationToClip(animationClip,spineAnimation.bones, spineData, boneGOByName, ratio);
if (spineAnimation.slots!=null)
addSlotAnimationToClip(animationClip, spineAnimation.slots, spineData, skinList, attachmentGOByNameBySlot);
if ( spineAnimation.events != null )
AddEvents( animationClip, spineAnimation.events, animationName );
if (spineAnimation.draworder!=null)
addDrawOrderAnimation( animationClip, spineAnimation.draworder, spineData, zStep, animationName, slotByName );
if (updateCurve){
EditorUtility.SetDirty(animationClip);
AssetDatabase.SaveAssets();
} else {
animationClip.frameRate = 30;
createFolderIfNoExists(rootDirectory, ANIMATION_FOLDER);
AssetDatabase.CreateAsset(animationClip, assetPath);
AssetDatabase.SaveAssets();
if (useLegacyAnimation){
AddClipToLegacyAnimationComponent(rootGO, animationClip);
} else {
AddClipToAnimatorComponent(rootGO,animationClip);
}
}
}
}
static void AddEvents( AnimationClip clip,
List< JsonData > events,
string animName )
{
List< UnityEngine.AnimationEvent > unityEvents = new List<UnityEngine.AnimationEvent>( );
foreach ( JsonData entry in events ) {
if ( !entry.IsObject )
Debug.LogError( "JSON data is wrong. Event is not an Object??!!" );
IDictionary entry_dict = entry as IDictionary;
UnityEngine.AnimationEvent ev = new UnityEngine.AnimationEvent( );
if ( entry_dict.Contains( "name" ) )
ev.functionName = ( ( string ) entry[ "name" ] );
else
Debug.LogError( "JSON data is wrong. Missing Name in event data: " + animName );
if ( entry_dict.Contains( "time" ) )
ev.time = getNumberData( entry[ "time" ], animName );
else
Debug.LogError( "JSON data is wrong. Missing Time in event data: " + animName + " EVENT_NAME: " + ev.functionName );
bool ParamAdded = false;
if ( entry_dict.Contains( "int" ) ) {
ev.intParameter = ( int ) entry[ "int" ];
ParamAdded = true;
}
if ( entry_dict.Contains( "float" ) ) {
if ( ParamAdded )
Debug.LogError( "JSON data is wrong. Unity Supports only one event parameter!!!! CLIP NAME: " + animName + " EVENT_NAME: " + entry.ToJson( ) );
ev.floatParameter = getNumberData( entry[ "float" ], animName );
ParamAdded = true;
}
if ( entry_dict.Contains( "string" ) ) {
if ( ParamAdded )
Debug.LogError( "JSON data is wrong. Unity Supports only one event parameter!!!! CLIP NAME: " + animName + " EVENT_NAME: " + entry.ToJson( ) );
ev.stringParameter = ( string ) entry[ "string" ];
}
ev.messageOptions = SendMessageOptions.RequireReceiver;
unityEvents.Add( ev );
}
AnimationUtility.SetAnimationEvents( clip, unityEvents.ToArray( ) );
}
static float getNumberData( JsonData data, string animName ) {
if ( data.IsDouble )
return ( float )( ( double )data );
if ( data.IsInt )
return ( float )( ( int )data );
Debug.LogError( "JSON data is wrong. Unrecognizable number format!!!! CLIP NAME: " + animName + " JsonData: " + data.ToJson( ) );
return 0.0f;
}
static void AddClipToLegacyAnimationComponent(GameObject rootGO, AnimationClip animationClip){
Animation animation = rootGO.GetComponent<Animation>();
if (animation == null)
animation = rootGO.AddComponent<Animation>();
animation.AddClip(animationClip, animationClip.name);
}
static void createFolderIfNoExists(string root, string folderName){
string path = root+"/"+folderName;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
public static string getFirstAttachmentName(SpineSlotAnimation spineSlotAnimation){
for (int i = 0; i < spineSlotAnimation.attachment.Count; i++) {
if (!string.IsNullOrEmpty( spineSlotAnimation.attachment[i].name))
return spineSlotAnimation.attachment[i].name;
}
return "";
}
public static void addDrawOrderAnimation( AnimationClip clip,
List<SpineDrawOrderAnimation> orderAnimation,
SpineData spineData,
float zStep,
string animName,
Dictionary<string, Slot> slotNameByName )
{
string[] BaseSlotOrder = new string[ spineData.slotOrder.Count ];
Dictionary< string, AnimationCurve > Curvs = new Dictionary<string, AnimationCurve>( );
foreach ( KeyValuePair<string, int> p in spineData.slotOrder ) {
BaseSlotOrder[ p.Value ] = p.Key;
AnimationCurve Curv = new AnimationCurve();
Keyframe keyFrame = new Keyframe( 0.0f, ( - p.Value ) * zStep );
Curv.AddKey( keyFrame );
Curvs[ p.Key ] = Curv;
}
foreach ( SpineDrawOrderAnimation orderAnim in orderAnimation ) {
string[] NewSlotOrder = null;
if ( orderAnim.offsets != null ) {
NewSlotOrder = new string[ BaseSlotOrder.Length ];
string[] BaseOrder_Copy = BaseSlotOrder.Clone( ) as string[];
for ( int i = 0; i != orderAnim.offsets.Length; i++ ) {
SpineDrawOrderAnimationSlot slot = orderAnim.offsets[ i ];
int newIdx = spineData.slotOrder[ slot.slot ] + slot.offset;
NewSlotOrder[ newIdx ] = slot.slot;
int base_idx = Array.IndexOf( BaseOrder_Copy, slot.slot );
BaseOrder_Copy[ base_idx ] = null;
}
int pos = 0;
for ( int i = 0; i != NewSlotOrder.Length; i++ ) {
if ( NewSlotOrder[ i ] == null ) {
bool found = false;
for ( ; pos != BaseOrder_Copy.Length; ) {
if ( BaseOrder_Copy[ pos ] != null ) {
found = true;
NewSlotOrder[ i ] = BaseOrder_Copy[ pos ];
pos++;
break;
} else pos++;
}
if ( !found ) Debug.LogError( "Can't create new draw order" );
}
}
} else NewSlotOrder = BaseSlotOrder;
for ( int j = 0; j != NewSlotOrder.Length; j++ ) {
float t = ( float )orderAnim.time;
float val = ( - j ) * zStep;
AnimationCurve curv = Curvs[ NewSlotOrder[ j ] ];
float priv_val = curv.Evaluate( t );
if ( t > 0.0f ) {
Keyframe keyFrameY_help = new Keyframe( t - 0.00001f, priv_val );
Keyframe keyFrameY = new Keyframe( t, val );
curv.AddKey( keyFrameY_help );
curv.AddKey( keyFrameY );
} else {
Keyframe keyFrameY = new Keyframe( t, val );
curv.AddKey( keyFrameY );
}
}
}
for ( int i = 0; i != BaseSlotOrder.Length; i++ ) {
string slotpath = spineData.slotPathByName[ BaseSlotOrder[ i ] ];
AnimationCurve curv = Curvs[ BaseSlotOrder[ i ] ];
AnimationUtility.SetEditorCurve( clip, EditorCurveBinding.FloatCurve( slotpath, typeof( Transform ), "m_LocalPosition.z" ), curv );
}
}
public static void addSlotAnimationToClip(AnimationClip clip,
Dictionary<string, SpineSlotAnimation> slotsAnimation,
SpineData spineData,
List<Skin> skinList,
AttachmentGOByNameBySlot attachmentGOByNameBySlot)
{
foreach(KeyValuePair<string, SpineSlotAnimation> kvp in slotsAnimation){
string slotName = kvp.Key;
string defaultAttachment = spineData.slotDefaultAttachments[slotName];
if (string.IsNullOrEmpty(defaultAttachment))
continue;
SpineSlotAnimation slotAnimation = kvp.Value;
if (slotAnimation.attachment != null && slotAnimation.attachment.Count > 0){
Dictionary<string, AnimationCurve> curveByName = new Dictionary<string, AnimationCurve>();
for (int i = 0; i < slotAnimation.attachment.Count; i++) {
bool nullAttachment = false;
SpineSlotAttachmentAnimation anim = slotAnimation.attachment[i];
if (string.IsNullOrEmpty( anim.name)){
anim.name=getFirstAttachmentName(slotAnimation);
nullAttachment = true;
}
if (anim.name.Equals(""))
continue;
AnimationCurve enableCurve;
if (curveByName.ContainsKey(anim.name)){
enableCurve = curveByName[anim.name];
} else {
enableCurve = new AnimationCurve();
if (anim.time > 0.0f)
enableCurve.AddKey(KeyframeUtil.GetNew(0, 0.0f, TangentMode.Stepped));
curveByName.Add(anim.name, enableCurve);
if (i==0 && !anim.name.Equals(defaultAttachment)){
AnimationCurve defSlotCurve = new AnimationCurve();
curveByName.Add(defaultAttachment, defSlotCurve);
if (anim.time !=0.0f){
defSlotCurve.AddKey(KeyframeUtil.GetNew(0, nullAttachment ? 0 : 1, TangentMode.Stepped));
defSlotCurve.AddKey(KeyframeUtil.GetNew((float)anim.time, 0, TangentMode.Stepped));
} else {
defSlotCurve.AddKey(KeyframeUtil.GetNew(0, 0, TangentMode.Stepped));
}
}
}
enableCurve.AddKey(KeyframeUtil.GetNew((float)anim.time, nullAttachment ? 0 : 1, TangentMode.Stepped));
if (i< (slotAnimation.attachment.Count - 1)){
SpineSlotAttachmentAnimation nextAnim = slotAnimation.attachment[i+1];
bool nullNextAttachment =false;
if (string.IsNullOrEmpty( nextAnim.name)){
nextAnim.name=getFirstAttachmentName(slotAnimation);
nullNextAttachment = true;
}
if (!nextAnim.name.Equals(anim.name) || nullNextAttachment)
enableCurve.AddKey(KeyframeUtil.GetNew((float)nextAnim.time, 0, TangentMode.Stepped));
}
}
foreach(KeyValuePair<string, AnimationCurve> kvp2 in curveByName){
string attachmentName = kvp2.Key;
AnimationCurve animationCurve = kvp2.Value;
string attachmentPath = spineData.slotPathByName[slotName] + "/" + attachmentName.Replace("/",SLASH_REPLACEMENT);
clip.SetCurve(attachmentPath, typeof(GameObject),"m_IsActive", animationCurve);
}
}
if (slotAnimation.color != null && slotAnimation.color.Count >0){
AnimationCurve Curv_R = new AnimationCurve( );
AnimationCurve Curv_G = new AnimationCurve( );
AnimationCurve Curv_B = new AnimationCurve( );
AnimationCurve Curv_A = new AnimationCurve( );
Keyframe startKeyFrame = new Keyframe( 0.0f, 1.0f );
Curv_R.AddKey( startKeyFrame );
Curv_G.AddKey( startKeyFrame );
Curv_B.AddKey( startKeyFrame );
Curv_A.AddKey( startKeyFrame );
JsonData[] curveData = new JsonData[ slotAnimation.color.Count ];
for( int i = 0 ; i != slotAnimation.color.Count ;i++ ) {
SpineSlotColorAnimation color = slotAnimation.color[ i ];
uint col = Convert.ToUInt32( color.color, 16 );
uint r = ( col ) >> 24;
uint g = (col & 0xff0000) >> 16;
uint b = (col & 0xff00) >> 8;
uint a = (col & 0xff);
float t = ( (float) (color.time) );
Keyframe keyFrame_R = new Keyframe( t, r / 255.0f );
Keyframe keyFrame_G = new Keyframe( t, g / 255.0f );
Keyframe keyFrame_B = new Keyframe( t, b / 255.0f );
Keyframe keyFrame_A = new Keyframe( t, a / 255.0f );
Curv_R.AddKey( keyFrame_R );
Curv_G.AddKey( keyFrame_G );
Curv_B.AddKey( keyFrame_B );
Curv_A.AddKey( keyFrame_A );
curveData[ i ] = color.curve;
}
setTangents( Curv_R, curveData );
setTangents( Curv_G, curveData );
setTangents( Curv_B, curveData );
setTangents( Curv_A, curveData );
for ( int i = 0; i != skinList.Count; i++ ) {
if ( skinList[ i ].containsSlot( slotName ) ) {
SkinSlot skinSlot = skinList[ i ][ slotName ];
for ( int j = 0; j != skinSlot.attachments.Length; j++ ) {
SpriteRenderer sprite = skinSlot.attachments[ j ].sprite;
if ( sprite != null ) {
string spritePath = skinSlot.attachments[ j ].ObPath;
AnimationUtility.SetEditorCurve( clip, EditorCurveBinding.FloatCurve( spritePath, typeof( SpriteRenderer ), "m_Color.r" ), Curv_R );
AnimationUtility.SetEditorCurve( clip, EditorCurveBinding.FloatCurve( spritePath, typeof( SpriteRenderer ), "m_Color.g" ), Curv_G );
AnimationUtility.SetEditorCurve( clip, EditorCurveBinding.FloatCurve( spritePath, typeof( SpriteRenderer ), "m_Color.b" ), Curv_B );
AnimationUtility.SetEditorCurve( clip, EditorCurveBinding.FloatCurve( spritePath, typeof( SpriteRenderer ), "m_Color.a" ), Curv_A );
}
}
}
}
Debug.LogWarning("slot color animation is not supported yet");
}
}
}
public static void setTangents(AnimationCurve curve, JsonData[] curveData){
bool showWarning = true;
for (int i = 0; i < curve.keys.Length; i++) {
int nextI = i + 1;
if (nextI < curve.keys.Length){
if (curveData[i] == null ){
//Linear
setLinearInterval(curve, i, nextI);
} else {
if (curveData[i].IsArray){
if (showWarning){
Debug.LogWarning("be carefull, smooth bezier animation is in beta state, check result animation manually");
showWarning = false;
}
setCustomTangents(curve, i, nextI, curveData[i]);
} else {
if (((string)curveData[i]).Equals("stepped")){
setSteppedInterval(curve, i, nextI);
} else {
Debug.LogError("unsupported animation type "+(string)curveData[i]);
}
}
}
}
}
}
static float parseFloat(JsonData jsonData){
if (jsonData.IsDouble)
return (float)(double)jsonData;
else if (jsonData.IsInt)
return (float)(int)jsonData;
Debug.LogError("can't parse to double ["+jsonData+"]");
return 0.0f;
}
// p0, p3 - start, end points
// p1, p2 - conrol points
// t - value on x [0,1]
public static Vector2 getBezierPoint(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float t){
float y = (1 - t) * (1 - t) * (1 - t) * p0.y +
3 * t * (1 - t) * (1 - t) * p1.y +
3 * t * t * (1 - t) * p2.y +
t * t * t * p3.y;
return new Vector2(p0.x + t * (p3.x - p0.x) ,y);
}
// a - start point
// b - on t= 1/3
// c - on t = 2/3
// d - end point
// c1,c2 control points of bezier.
public static void calcControlPoints(Vector2 a, Vector2 b, Vector2 c, Vector2 d, out Vector2 c1, out Vector2 c2){
c1 = (-5 * a + 18 * b - 9 * c + 2 * d)/6;
c2 = ( 2 * a - 9 * b + 18 * c - 5 * d)/6;
}
public static void setCustomTangents(AnimationCurve curve, int i, int nextI, JsonData tangentArray){
float diffValue = curve[nextI].value - curve[i].value;
float diffTime = curve[nextI].time - curve[i].time;
if (diffValue == 0)
return;
float cx1 = parseFloat(tangentArray[0]);
float cy1 = parseFloat(tangentArray[1]);
float cx2 = parseFloat(tangentArray[2]);
float cy2 = parseFloat(tangentArray[3]);
Vector2 p0 = new Vector2(0 , curve[i].value);
Vector2 p3 = new Vector2(diffTime , curve[nextI].value);
Vector2 cOrig1 = new Vector2(diffTime * cx1, curve[i].value);
cOrig1.y += diffValue > 0 ? diffValue * cy1 : -1.0f * Mathf.Abs(diffValue * cy1);
Vector2 cOrig2 = new Vector2(diffTime * cx2, curve[i].value);
cOrig2.y += diffValue > 0 ? diffValue * cy2 : -1.0f * Mathf.Abs(diffValue * cy2);
Vector2 p1 = getBezierPoint(p0, cOrig1, cOrig2, p3, 1.0f / 3.0f);
Vector2 p2 = getBezierPoint(p0, cOrig1, cOrig2, p3, 2.0f / 3.0f);
Vector2 c1tg, c2tg, c1, c2;
calcControlPoints(p0,p1,p2,p3, out c1, out c2);
c1tg = c1 - p0;
c2tg = c2 - p3;
float outTangent = c1tg.y / c1tg.x;
float inTangent = c2tg.y / c2tg.x;
object thisKeyframeBoxed = curve[i];
object nextKeyframeBoxed = curve[nextI];
if (!KeyframeUtil.isKeyBroken(thisKeyframeBoxed))
KeyframeUtil.SetKeyBroken(thisKeyframeBoxed, true);
KeyframeUtil.SetKeyTangentMode(thisKeyframeBoxed, 1, TangentMode.Editable);
if (!KeyframeUtil.isKeyBroken(nextKeyframeBoxed))
KeyframeUtil.SetKeyBroken(nextKeyframeBoxed, true);
KeyframeUtil.SetKeyTangentMode(nextKeyframeBoxed, 0, TangentMode.Editable);
Keyframe thisKeyframe = (Keyframe)thisKeyframeBoxed;
Keyframe nextKeyframe = (Keyframe)nextKeyframeBoxed;
thisKeyframe.outTangent = outTangent;
nextKeyframe.inTangent = inTangent;
curve.MoveKey(i, thisKeyframe);
curve.MoveKey(nextI, nextKeyframe);
//* test method
bool ok = true;
float startTime = thisKeyframe.time;
float epsilon = 0.001f;
for (float j=0; j < 25f; j++) {
float t = j/25.0f;
Vector2 t1 = getBezierPoint(p0, cOrig1, cOrig2, p3, t);
Vector2 t2 = getBezierPoint(p0, c1, c2, p3, t);
float curveValue = curve.Evaluate(startTime + diffTime * t);
if (!NearlyEqual(t1.y, t2.y, epsilon)
|| !NearlyEqual(t2.y, curveValue, epsilon)){
Debug.LogError("time = "+ t + " t1 = ["+t1.y.ToString("N8")+"] t2 = ["+t2.y.ToString("N8")+"] curve = ["+curveValue.ToString("N8")+"]");
ok = false;
}
}
if (!ok)
Debug.LogWarning("something wrong with bezier points");
//*/
}
public static bool NearlyEqual(float a, float b, float epsilon)
{
float absA = Math.Abs(a);
float absB = Math.Abs(b);
float diff = Math.Abs(a - b);
if (a == b)
{ // shortcut, handles infinities
return true;
}
else if (a == 0 || b == 0 || diff < Double.MinValue)
{
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Double.MinValue);
}
else
{ // use relative error
return diff / (absA + absB) < epsilon;
}
}
public static void setSteppedInterval(AnimationCurve curve, int i, int nextI){
if (curve.keys[i].value == curve.keys[nextI].value){
return;
}
object thisKeyframeBoxed = curve[i];
object nextKeyframeBoxed = curve[nextI];
if (!KeyframeUtil.isKeyBroken(thisKeyframeBoxed))
KeyframeUtil.SetKeyBroken(thisKeyframeBoxed, true);
if (!KeyframeUtil.isKeyBroken(nextKeyframeBoxed))
KeyframeUtil.SetKeyBroken(nextKeyframeBoxed, true);
KeyframeUtil.SetKeyTangentMode(thisKeyframeBoxed, 1, TangentMode.Stepped);
KeyframeUtil.SetKeyTangentMode(nextKeyframeBoxed, 0, TangentMode.Stepped);
Keyframe thisKeyframe = (Keyframe)thisKeyframeBoxed;
Keyframe nextKeyframe = (Keyframe)nextKeyframeBoxed;
thisKeyframe.outTangent = float.PositiveInfinity;
nextKeyframe.inTangent = float.PositiveInfinity;
curve.MoveKey(i, thisKeyframe);
curve.MoveKey(nextI, nextKeyframe);
}
public static void setLinearInterval(AnimationCurve curve, int i, int nextI){
Keyframe thisKeyframe = curve[i];
Keyframe nextKeyframe = curve[nextI];
thisKeyframe.outTangent = CurveExtension.CalculateLinearTangent(curve, i, nextI);
nextKeyframe.inTangent = CurveExtension.CalculateLinearTangent(curve, nextI, i);
KeyframeUtil.SetKeyBroken((object)thisKeyframe, true);
KeyframeUtil.SetKeyBroken((object)nextKeyframe, true);
KeyframeUtil.SetKeyTangentMode((object)thisKeyframe, 1, TangentMode.Linear);
KeyframeUtil.SetKeyTangentMode((object)nextKeyframe, 0, TangentMode.Linear);
curve.MoveKey(i, thisKeyframe);
curve.MoveKey(nextI, nextKeyframe);
}
public static void addBoneAnimationToClip(AnimationClip clip, Dictionary<string, SpineBoneAnimation> bonesAnimation,
SpineData spineData, Dictionary<string, GameObject> boneGOByName, float ratio){
foreach(KeyValuePair<string,SpineBoneAnimation> kvp in bonesAnimation){
string boneName = kvp.Key;
GameObject boneGO = boneGOByName[boneName];
SpineBoneAnimation boneAnimation = kvp.Value;
string bonePath = spineData.bonePathByName[boneName];
if (boneAnimation.translate != null && boneAnimation.translate.Count > 0){
AnimationCurve curveX = new AnimationCurve();
AnimationCurve curveY = new AnimationCurve();
JsonData[] curveData = new JsonData[boneAnimation.translate.Count];
for (int i = 0; i < boneAnimation.translate.Count; i++) {
Keyframe keyFrameX = new Keyframe((float)boneAnimation.translate[i].time, boneGO.transform.localPosition.x + (float)boneAnimation.translate[i].x * ratio);
Keyframe keyFrameY = new Keyframe((float)boneAnimation.translate[i].time, boneGO.transform.localPosition.y + (float)boneAnimation.translate[i].y * ratio);
curveX.AddKey(keyFrameX);
curveY.AddKey(keyFrameY);
curveData[i] = boneAnimation.translate[i].curve;
}
setTangents(curveX, curveData);
setTangents(curveY, curveData);
AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(bonePath,typeof(Transform),"m_LocalPosition.x") ,curveX);
AnimationUtility.SetEditorCurve(clip, EditorCurveBinding.FloatCurve(bonePath,typeof(Transform),"m_LocalPosition.y") ,curveY);
}
if (boneAnimation.rotate != null && boneAnimation.rotate.Count > 0){
AnimationCurve localRotationX = new AnimationCurve();
AnimationCurve localRotationY = new AnimationCurve();
AnimationCurve localRotationZ = new AnimationCurve();
AnimationCurve localRotationW = new AnimationCurve();
JsonData[] curveData = new JsonData[boneAnimation.rotate.Count];
Quaternion baseRotation = Quaternion.identity;
for (int i = 0; i < boneAnimation.rotate.Count; i++) {
float origAngle = (float)boneAnimation.rotate[i].angle;
if (origAngle > 0)
origAngle = origAngle > 180 ? origAngle - 360 : origAngle;
else
origAngle = origAngle < -180 ? origAngle + 360 : origAngle;
float newZ = boneGO.transform.localRotation.eulerAngles.z + origAngle;
Quaternion angle = Quaternion.Euler(0,0,newZ);
float time = (float)boneAnimation.rotate[i].time;
curveData[i] = boneAnimation.rotate[i].curve;
localRotationX.AddKey(new Keyframe(time, angle.x));
localRotationY.AddKey(new Keyframe(time, angle.y));
localRotationZ.AddKey(new Keyframe(time, angle.z));
localRotationW.AddKey(new Keyframe(time, angle.w));
}
fixAngleCurve (localRotationX , curveData, baseRotation.x);
fixAngleCurve (localRotationY , curveData, baseRotation.y);
fixAngleCurve (localRotationZ , curveData, baseRotation.z);
fixAngleCurve (localRotationW , curveData, baseRotation.w);
AnimationUtility.SetEditorCurve(clip,EditorCurveBinding.FloatCurve(bonePath,typeof(Transform),"m_LocalRotation.x"), localRotationX);
AnimationUtility.SetEditorCurve(clip,EditorCurveBinding.FloatCurve(bonePath,typeof(Transform),"m_LocalRotation.y"), localRotationY);
AnimationUtility.SetEditorCurve(clip,EditorCurveBinding.FloatCurve(bonePath,typeof(Transform),"m_LocalRotation.z"), localRotationZ);
AnimationUtility.SetEditorCurve(clip,EditorCurveBinding.FloatCurve(bonePath,typeof(Transform),"m_LocalRotation.w"), localRotationW);
}
if (boneAnimation.scale != null && boneAnimation.scale.Count > 0){
AnimationCurve scaleX = new AnimationCurve();
AnimationCurve scaleY = new AnimationCurve();
AnimationCurve scaleZ = new AnimationCurve();
JsonData[] curveData = new JsonData[boneAnimation.scale.Count];
for (int i = 0; i < boneAnimation.scale.Count; i++) {
Keyframe keyFrameX = new Keyframe((float)boneAnimation.scale[i].time, boneGO.transform.localScale.x * (float)boneAnimation.scale[i].x);
Keyframe keyFrameY = new Keyframe((float)boneAnimation.scale[i].time, boneGO.transform.localScale.y * (float)boneAnimation.scale[i].y);
Keyframe keyFrameZ = new Keyframe((float)boneAnimation.scale[i].time, 1);
curveData[i] = boneAnimation.scale[i].curve;
scaleX.AddKey(keyFrameX);
scaleY.AddKey(keyFrameY);
scaleZ.AddKey(keyFrameZ);
}
setTangents(scaleX,curveData);
setTangents(scaleY,curveData);
clip.SetCurve(bonePath, typeof(Transform),"localScale.x",scaleX);
clip.SetCurve(bonePath, typeof(Transform),"localScale.y",scaleY);
clip.SetCurve(bonePath, typeof(Transform),"localScale.z",scaleZ);
}
}
}
static void fixAngleCurve(AnimationCurve animationCurve, JsonData[] curveData, float defSingleStepValue){
fixSingleStep(animationCurve, defSingleStepValue);
fixAngles (animationCurve, curveData);
setTangents (animationCurve, curveData);
}
static void fixSingleStep (AnimationCurve animationCurve, float defSingleStepValue)
{
if (animationCurve.keys.Length == 1 && animationCurve.keys[0].time != 0.0f){
Keyframe key = animationCurve.keys[0];
key.time = 0.0f;
key.value = defSingleStepValue;
animationCurve.AddKey(key);
}
}
static void fixAngles(AnimationCurve curve, JsonData[] curveData){
if (curve.keys.Length <3)
return;
float currValue, previousValue;
for (int previousI=0, i = 1; i < curve.keys.Length; previousI= i++) {
if (curveData[previousI] != null && curveData[previousI].IsString && ((string)curveData[previousI]).Equals("stepped"))
continue;
currValue = curve.keys[i].value;
previousValue = curve.keys[previousI].value;
while ((currValue - previousValue) > 180 ){
currValue -= 360;
}
while ((currValue - previousValue) < -180){
currValue += 360;
}
if (curve.keys[i].value != currValue){
curve.MoveKey(i, new Keyframe(curve.keys[i].time , currValue));
}
}
}
public static AnimationClip AddClipToAnimatorComponent(GameObject animatedObject, AnimationClip newClip)
{
Animator animator = animatedObject.GetComponent<Animator>();
if ( animator == null)
animator = animatedObject.AddComponent<Animator>();
UnityEditor.Animations.AnimatorController animatorController = UnityInternalMethods.GetEffectiveAnimatorController(animator);
if (animatorController == null)
{
string path = Path.GetDirectoryName( AssetDatabase.GetAssetPath(newClip)) +"/"+animatedObject.name+".controller";
UnityEditor.Animations.AnimatorController controllerForClip = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPathWithClip(path, newClip);
UnityEditor.Animations.AnimatorController.SetAnimatorController(animator, controllerForClip);
if (controllerForClip != null)
return newClip;
else
return null;
}
else
{
animatorController.AddMotion((Motion)newClip);
return newClip;
}
}
public static Quaternion getAttachmentRotation(SpineSkinAttachment spineSkinAttachment, bool rotated = false){
if (rotated)
return Quaternion.Euler(0.0f, 0.0f, (float)spineSkinAttachment.rotation - 90.0f);
else
return Quaternion.Euler(0.0f, 0.0f, (float)spineSkinAttachment.rotation);
}
public static Vector3 getAttachmentPosition(SpineSkinAttachment spineSkinAttachment, float ratio, float z){
return new Vector3((float)spineSkinAttachment.x * ratio, (float)spineSkinAttachment.y * ratio, z);
}
public static Vector3 getAttachmentScale(SpineSkinAttachment spineSkinAttachment){
return new Vector3((float)spineSkinAttachment.scaleX, (float)spineSkinAttachment.scaleY, 1.0f);
}
public static Color32? hexStringToColor32(string hex){
if (hex == null)
return null;
int rgba = int.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return new Color32((byte)((rgba & 0xff000000)>> 0x18),
(byte)((rgba & 0xff0000)>> 0x10),
(byte)((rgba & 0xff00) >> 8),
(byte)(rgba & 0xff));
}
}
}
| |
/*
* 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.Support;
using DocIdSet = Lucene.Net.Search.DocIdSet;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
namespace Lucene.Net.Util
{
/// <summary>An "open" BitSet implementation that allows direct access to the array of words
/// storing the bits.
/// <p/>
/// Unlike java.util.bitset, the fact that bits are packed into an array of longs
/// is part of the interface. This allows efficient implementation of other algorithms
/// by someone other than the author. It also allows one to efficiently implement
/// alternate serialization or interchange formats.
/// <p/>
/// <c>OpenBitSet</c> is faster than <c>java.util.BitSet</c> in most operations
/// and *much* faster at calculating cardinality of sets and results of set operations.
/// It can also handle sets of larger cardinality (up to 64 * 2**32-1)
/// <p/>
/// The goals of <c>OpenBitSet</c> are the fastest implementation possible, and
/// maximum code reuse. Extra safety and encapsulation
/// may always be built on top, but if that's built in, the cost can never be removed (and
/// hence people re-implement their own version in order to get better performance).
/// If you want a "safe", totally encapsulated (and slower and limited) BitSet
/// class, use <c>java.util.BitSet</c>.
/// <p/>
/// <h3>Performance Results</h3>
///
/// Test system: Pentium 4, Sun Java 1.5_06 -server -Xbatch -Xmx64M
/// <br/>BitSet size = 1,000,000
/// <br/>Results are java.util.BitSet time divided by OpenBitSet time.
/// <table border="1">
/// <tr>
/// <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
/// </tr>
/// <tr>
/// <th>50% full</th> <td>3.36</td> <td>3.96</td> <td>1.44</td> <td>1.46</td> <td>1.99</td> <td>1.58</td>
/// </tr>
/// <tr>
/// <th>1% full</th> <td>3.31</td> <td>3.90</td> <td> </td> <td>1.04</td> <td> </td> <td>0.99</td>
/// </tr>
/// </table>
/// <br/>
/// Test system: AMD Opteron, 64 bit linux, Sun Java 1.5_06 -server -Xbatch -Xmx64M
/// <br/>BitSet size = 1,000,000
/// <br/>Results are java.util.BitSet time divided by OpenBitSet time.
/// <table border="1">
/// <tr>
/// <th></th> <th>cardinality</th> <th>intersect_count</th> <th>union</th> <th>nextSetBit</th> <th>get</th> <th>iterator</th>
/// </tr>
/// <tr>
/// <th>50% full</th> <td>2.50</td> <td>3.50</td> <td>1.00</td> <td>1.03</td> <td>1.12</td> <td>1.25</td>
/// </tr>
/// <tr>
/// <th>1% full</th> <td>2.51</td> <td>3.49</td> <td> </td> <td>1.00</td> <td> </td> <td>1.02</td>
/// </tr>
/// </table>
/// </summary>
/// <version> $Id$
/// </version>
[Serializable]
public class OpenBitSet:DocIdSet, System.ICloneable
{
protected internal long[] internalbits;
protected internal int wlen; // number of words (elements) used in the array
/// <summary>Constructs an OpenBitSet large enough to hold numBits.
///
/// </summary>
/// <param name="numBits">
/// </param>
public OpenBitSet(long numBits)
{
internalbits = new long[Bits2words(numBits)];
wlen = internalbits.Length;
}
public OpenBitSet():this(64)
{
}
/// <summary>Constructs an OpenBitSet from an existing long[].
/// <br/>
/// The first 64 bits are in long[0],
/// with bit index 0 at the least significant bit, and bit index 63 at the most significant.
/// Given a bit index,
/// the word containing it is long[index/64], and it is at bit number index%64 within that word.
/// <p/>
/// numWords are the number of elements in the array that contain
/// set bits (non-zero longs).
/// numWords should be <= bits.length, and
/// any existing words in the array at position >= numWords should be zero.
///
/// </summary>
public OpenBitSet(long[] bits, int numWords)
{
this.internalbits = bits;
this.wlen = numWords;
}
public override DocIdSetIterator Iterator()
{
return new OpenBitSetIterator(internalbits, wlen);
}
/// <summary>This DocIdSet implementation is cacheable. </summary>
public override bool IsCacheable
{
get { return true; }
}
/// <summary>Returns the current capacity in bits (1 greater than the index of the last bit) </summary>
public virtual long Capacity()
{
return internalbits.Length << 6;
}
/// <summary> Returns the current capacity of this set. Included for
/// compatibility. This is *not* equal to <see cref="Cardinality" />
/// </summary>
public virtual long Size()
{
return Capacity();
}
/// <summary>Returns true if there are no set bits </summary>
public virtual bool IsEmpty()
{
return Cardinality() == 0;
}
/// <summary>Expert: Gets or sets the long[] storing the bits </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public virtual long[] Bits
{
set { this.internalbits = value; }
get { return internalbits; }
}
/// <summary>Expert: gets or sets the number of longs in the array that are in use </summary>
public virtual int NumWords
{
get { return wlen; }
set { this.wlen = value; }
}
/// <summary>Returns true or false for the specified bit index. </summary>
public virtual bool Get(int index)
{
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
if (i >= internalbits.Length)
return false;
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (internalbits[i] & bitmask) != 0;
}
/// <summary>Returns true or false for the specified bit index.
/// The index should be less than the OpenBitSet size
/// </summary>
public virtual bool FastGet(int index)
{
int i = index >> 6; // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (internalbits[i] & bitmask) != 0;
}
/// <summary>Returns true or false for the specified bit index</summary>
public virtual bool Get(long index)
{
int i = (int) (index >> 6); // div 64
if (i >= internalbits.Length)
return false;
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (internalbits[i] & bitmask) != 0;
}
/// <summary>Returns true or false for the specified bit index.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool FastGet(long index)
{
int i = (int) (index >> 6); // div 64
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
return (internalbits[i] & bitmask) != 0;
}
/*
// alternate implementation of get()
public boolean get1(int index) {
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((bits[i]>>>bit) & 0x01) != 0;
// this does a long shift and a bittest (on x86) vs
// a long shift, and a long AND, (the test for zero is prob a no-op)
// testing on a P4 indicates this is slower than (bits[i] & bitmask) != 0;
}
*/
/// <summary>returns 1 if the bit is set, 0 if not.
/// The index should be less than the OpenBitSet size
/// </summary>
public virtual int GetBit(int index)
{
int i = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
return ((int )((ulong) (internalbits[i]) >> bit)) & 0x01;
}
/*
public boolean get2(int index) {
int word = index >> 6; // div 64
int bit = index & 0x0000003f; // mod 64
return (bits[word] << bit) < 0; // hmmm, this would work if bit order were reversed
// we could right shift and check for parity bit, if it was available to us.
}
*/
/// <summary>sets a bit, expanding the set size if necessary </summary>
public virtual void Set(long index)
{
int wordNum = ExpandingWordNum(index);
int bit = (int) index & 0x3f;
long bitmask = 1L << bit;
internalbits[wordNum] |= bitmask;
}
/// <summary>Sets the bit at the specified index.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastSet(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] |= bitmask;
}
/// <summary>Sets the bit at the specified index.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastSet(long index)
{
int wordNum = (int) (index >> 6);
int bit = (int) index & 0x3f;
long bitmask = 1L << bit;
internalbits[wordNum] |= bitmask;
}
/// <summary>Sets a range of bits, expanding the set size if necessary
///
/// </summary>
/// <param name="startIndex">lower index
/// </param>
/// <param name="endIndex">one-past the last bit to set
/// </param>
public virtual void Set(long startIndex, long endIndex)
{
if (endIndex <= startIndex)
return ;
int startWord = (int) (startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ExpandingWordNum(endIndex - 1);
long startmask = - 1L << (int) startIndex;
long endmask = (long) (0xffffffffffffffffUL >> (int) - endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
internalbits[startWord] |= (startmask & endmask);
return ;
}
internalbits[startWord] |= startmask;
for (int i = startWord + 1; i < endWord; i++)
internalbits[i] = -1L;
internalbits[endWord] |= endmask;
}
protected internal virtual int ExpandingWordNum(long index)
{
int wordNum = (int) (index >> 6);
if (wordNum >= wlen)
{
EnsureCapacity(index + 1);
wlen = wordNum + 1;
}
return wordNum;
}
/// <summary>clears a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastClear(int index)
{
int wordNum = index >> 6;
int bit = index & 0x03f;
long bitmask = 1L << bit;
internalbits[wordNum] &= ~ bitmask;
// hmmm, it takes one more instruction to clear than it does to set... any
// way to work around this? If there were only 63 bits per word, we could
// use a right shift of 10111111...111 in binary to position the 0 in the
// correct place (using sign extension).
// Could also use Long.rotateRight() or rotateLeft() *if* they were converted
// by the JVM into a native instruction.
// bits[word] &= Long.rotateLeft(0xfffffffe,bit);
}
/// <summary>clears a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastClear(long index)
{
int wordNum = (int) (index >> 6); // div 64
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] &= ~ bitmask;
}
/// <summary>clears a bit, allowing access beyond the current set size without changing the size.</summary>
public virtual void Clear(long index)
{
int wordNum = (int) (index >> 6); // div 64
if (wordNum >= wlen)
return ;
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] &= ~ bitmask;
}
/// <summary>Clears a range of bits. Clearing past the end does not change the size of the set.
///
/// </summary>
/// <param name="startIndex">lower index
/// </param>
/// <param name="endIndex">one-past the last bit to clear
/// </param>
public virtual void Clear(int startIndex, int endIndex)
{
if (endIndex <= startIndex)
return ;
int startWord = (startIndex >> 6);
if (startWord >= wlen)
return ;
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ((endIndex - 1) >> 6);
long startmask = - 1L << startIndex;
long endmask = (long) (0xffffffffffffffffUL >> - endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~ startmask;
endmask = ~ endmask;
if (startWord == endWord)
{
internalbits[startWord] &= (startmask | endmask);
return ;
}
internalbits[startWord] &= startmask;
int middle = System.Math.Min(wlen, endWord);
for (int i = startWord + 1; i < middle; i++)
internalbits[i] = 0L;
if (endWord < wlen)
{
internalbits[endWord] &= endmask;
}
}
/// <summary>Clears a range of bits. Clearing past the end does not change the size of the set.
///
/// </summary>
/// <param name="startIndex">lower index
/// </param>
/// <param name="endIndex">one-past the last bit to clear
/// </param>
public virtual void Clear(long startIndex, long endIndex)
{
if (endIndex <= startIndex)
return ;
int startWord = (int) (startIndex >> 6);
if (startWord >= wlen)
return ;
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = (int) ((endIndex - 1) >> 6);
long startmask = - 1L << (int) startIndex;
long endmask = (long) (0xffffffffffffffffUL >> (int) - endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
// invert masks since we are clearing
startmask = ~ startmask;
endmask = ~ endmask;
if (startWord == endWord)
{
internalbits[startWord] &= (startmask | endmask);
return ;
}
internalbits[startWord] &= startmask;
int middle = System.Math.Min(wlen, endWord);
for (int i = startWord + 1; i < middle; i++)
internalbits[i] = 0L;
if (endWord < wlen)
{
internalbits[endWord] &= endmask;
}
}
/// <summary>Sets a bit and returns the previous value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool GetAndSet(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
bool val = (internalbits[wordNum] & bitmask) != 0;
internalbits[wordNum] |= bitmask;
return val;
}
/// <summary>Sets a bit and returns the previous value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool GetAndSet(long index)
{
int wordNum = (int) (index >> 6); // div 64
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
bool val = (internalbits[wordNum] & bitmask) != 0;
internalbits[wordNum] |= bitmask;
return val;
}
/// <summary>flips a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastFlip(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] ^= bitmask;
}
/// <summary>flips a bit.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual void FastFlip(long index)
{
int wordNum = (int) (index >> 6); // div 64
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] ^= bitmask;
}
/// <summary>flips a bit, expanding the set size if necessary </summary>
public virtual void Flip(long index)
{
int wordNum = ExpandingWordNum(index);
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] ^= bitmask;
}
/// <summary>flips a bit and returns the resulting bit value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool FlipAndGet(int index)
{
int wordNum = index >> 6; // div 64
int bit = index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] ^= bitmask;
return (internalbits[wordNum] & bitmask) != 0;
}
/// <summary>flips a bit and returns the resulting bit value.
/// The index should be less than the OpenBitSet size.
/// </summary>
public virtual bool FlipAndGet(long index)
{
int wordNum = (int) (index >> 6); // div 64
int bit = (int) index & 0x3f; // mod 64
long bitmask = 1L << bit;
internalbits[wordNum] ^= bitmask;
return (internalbits[wordNum] & bitmask) != 0;
}
/// <summary>Flips a range of bits, expanding the set size if necessary
///
/// </summary>
/// <param name="startIndex">lower index
/// </param>
/// <param name="endIndex">one-past the last bit to flip
/// </param>
public virtual void Flip(long startIndex, long endIndex)
{
if (endIndex <= startIndex)
return ;
int startWord = (int) (startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = ExpandingWordNum(endIndex - 1);
/* Grrr, java shifting wraps around so -1L>>>64 == -1
* for that reason, make sure not to use endmask if the bits to flip will
* be zero in the last word (redefine endWord to be the last changed...)
long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000
long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111
***/
long startmask = - 1L << (int) startIndex;
long endmask = (long) (0xffffffffffffffffUL >> (int) - endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
internalbits[startWord] ^= (startmask & endmask);
return ;
}
internalbits[startWord] ^= startmask;
for (int i = startWord + 1; i < endWord; i++)
{
internalbits[i] = ~ internalbits[i];
}
internalbits[endWord] ^= endmask;
}
/*
public static int pop(long v0, long v1, long v2, long v3) {
// derived from pop_array by setting last four elems to 0.
// exchanges one pop() call for 10 elementary operations
// saving about 7 instructions... is there a better way?
long twosA=v0 & v1;
long ones=v0^v1;
long u2=ones^v2;
long twosB =(ones&v2)|(u2&v3);
ones=u2^v3;
long fours=(twosA&twosB);
long twos=twosA^twosB;
return (pop(fours)<<2)
+ (pop(twos)<<1)
+ pop(ones);
}
*/
/// <returns> the number of set bits
/// </returns>
public virtual long Cardinality()
{
return BitUtil.Pop_array(internalbits, 0, wlen);
}
/// <summary>Returns the popcount or cardinality of the intersection of the two sets.
/// Neither set is modified.
/// </summary>
public static long IntersectionCount(OpenBitSet a, OpenBitSet b)
{
return BitUtil.Pop_intersect(a.internalbits, b.internalbits, 0, System.Math.Min(a.wlen, b.wlen));
}
/// <summary>Returns the popcount or cardinality of the union of the two sets.
/// Neither set is modified.
/// </summary>
public static long UnionCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.Pop_union(a.internalbits, b.internalbits, 0, System.Math.Min(a.wlen, b.wlen));
if (a.wlen < b.wlen)
{
tot += BitUtil.Pop_array(b.internalbits, a.wlen, b.wlen - a.wlen);
}
else if (a.wlen > b.wlen)
{
tot += BitUtil.Pop_array(a.internalbits, b.wlen, a.wlen - b.wlen);
}
return tot;
}
/// <summary>Returns the popcount or cardinality of "a and not b"
/// or "intersection(a, not(b))".
/// Neither set is modified.
/// </summary>
public static long AndNotCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.Pop_andnot(a.internalbits, b.internalbits, 0, System.Math.Min(a.wlen, b.wlen));
if (a.wlen > b.wlen)
{
tot += BitUtil.Pop_array(a.internalbits, b.wlen, a.wlen - b.wlen);
}
return tot;
}
/// <summary>Returns the popcount or cardinality of the exclusive-or of the two sets.
/// Neither set is modified.
/// </summary>
public static long XorCount(OpenBitSet a, OpenBitSet b)
{
long tot = BitUtil.Pop_xor(a.internalbits, b.internalbits, 0, System.Math.Min(a.wlen, b.wlen));
if (a.wlen < b.wlen)
{
tot += BitUtil.Pop_array(b.internalbits, a.wlen, b.wlen - a.wlen);
}
else if (a.wlen > b.wlen)
{
tot += BitUtil.Pop_array(a.internalbits, b.wlen, a.wlen - b.wlen);
}
return tot;
}
/// <summary>Returns the index of the first set bit starting at the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public virtual int NextSetBit(int index)
{
int i = index >> 6;
if (i >= wlen)
return - 1;
int subIndex = index & 0x3f; // index within the word
long word = internalbits[i] >> subIndex; // skip all the bits to the right of index
if (word != 0)
{
return (i << 6) + subIndex + BitUtil.Ntz(word);
}
while (++i < wlen)
{
word = internalbits[i];
if (word != 0)
return (i << 6) + BitUtil.Ntz(word);
}
return - 1;
}
/// <summary>Returns the index of the first set bit starting at the index specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public virtual long NextSetBit(long index)
{
int i = (int) (index >> 6);
if (i >= wlen)
return - 1;
int subIndex = (int) index & 0x3f; // index within the word
long word = (long) ((ulong) internalbits[i] >> subIndex); // skip all the bits to the right of index
if (word != 0)
{
return (((long) i) << 6) + (subIndex + BitUtil.Ntz(word));
}
while (++i < wlen)
{
word = internalbits[i];
if (word != 0)
return (((long) i) << 6) + BitUtil.Ntz(word);
}
return - 1;
}
public virtual System.Object Clone()
{
try
{
OpenBitSet obs = new OpenBitSet((long[]) internalbits.Clone(), wlen);
//obs.bits = new long[obs.bits.Length];
//obs.bits.CopyTo(obs.bits, 0); // hopefully an array clone is as fast(er) than arraycopy
return obs;
}
catch (System.Exception e)
{
throw new System.SystemException(e.Message, e);
}
}
/// <summary>this = this AND other </summary>
public virtual void Intersect(OpenBitSet other)
{
int newLen = System.Math.Min(this.wlen, other.wlen);
long[] thisArr = this.internalbits;
long[] otherArr = other.internalbits;
// testing against zero can be more efficient
int pos = newLen;
while (--pos >= 0)
{
thisArr[pos] &= otherArr[pos];
}
if (this.wlen > newLen)
{
// fill zeros from the new shorter length to the old length
for (int i = newLen; i < this.wlen; i++)
internalbits[i] = 0L;
}
this.wlen = newLen;
}
/// <summary>this = this OR other </summary>
public virtual void Union(OpenBitSet other)
{
int newLen = System.Math.Max(wlen, other.wlen);
EnsureCapacityWords(newLen);
long[] thisArr = this.internalbits;
long[] otherArr = other.internalbits;
int pos = System.Math.Min(wlen, other.wlen);
while (--pos >= 0)
{
thisArr[pos] |= otherArr[pos];
}
if (this.wlen < newLen)
{
Array.Copy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
}
this.wlen = newLen;
}
/// <summary>Remove all elements set in other. this = this AND_NOT other </summary>
public virtual void Remove(OpenBitSet other)
{
int idx = System.Math.Min(wlen, other.wlen);
long[] thisArr = this.internalbits;
long[] otherArr = other.internalbits;
while (--idx >= 0)
{
thisArr[idx] &= ~ otherArr[idx];
}
}
/// <summary>this = this XOR other </summary>
public virtual void Xor(OpenBitSet other)
{
int newLen = System.Math.Max(wlen, other.wlen);
EnsureCapacityWords(newLen);
long[] thisArr = this.internalbits;
long[] otherArr = other.internalbits;
int pos = System.Math.Min(wlen, other.wlen);
while (--pos >= 0)
{
thisArr[pos] ^= otherArr[pos];
}
if (this.wlen < newLen)
{
Array.Copy(otherArr, this.wlen, thisArr, this.wlen, newLen - this.wlen);
}
this.wlen = newLen;
}
// some BitSet compatability methods
//* see <see cref="intersect" /> */
public virtual void And(OpenBitSet other)
{
Intersect(other);
}
//* see <see cref="union" /> */
public virtual void Or(OpenBitSet other)
{
Union(other);
}
//* see <see cref="andNot" /> */
public virtual void AndNot(OpenBitSet other)
{
Remove(other);
}
/// <summary>returns true if the sets have any elements in common </summary>
public virtual bool Intersects(OpenBitSet other)
{
int pos = System.Math.Min(this.wlen, other.wlen);
long[] thisArr = this.internalbits;
long[] otherArr = other.internalbits;
while (--pos >= 0)
{
if ((thisArr[pos] & otherArr[pos]) != 0)
return true;
}
return false;
}
/// <summary>Expand the long[] with the size given as a number of words (64 bit longs).
/// getNumWords() is unchanged by this call.
/// </summary>
public virtual void EnsureCapacityWords(int numWords)
{
if (internalbits.Length < numWords)
{
internalbits = ArrayUtil.Grow(internalbits, numWords);
}
}
/// <summary>Ensure that the long[] is big enough to hold numBits, expanding it if necessary.
/// getNumWords() is unchanged by this call.
/// </summary>
public virtual void EnsureCapacity(long numBits)
{
EnsureCapacityWords(Bits2words(numBits));
}
/// <summary>Lowers numWords, the number of words in use,
/// by checking for trailing zero words.
/// </summary>
public virtual void TrimTrailingZeros()
{
int idx = wlen - 1;
while (idx >= 0 && internalbits[idx] == 0)
idx--;
wlen = idx + 1;
}
/// <summary>returns the number of 64 bit words it would take to hold numBits </summary>
public static int Bits2words(long numBits)
{
return (int) ((((numBits - 1) >> 6)) + 1);
}
/// <summary>returns true if both sets have the same bits set </summary>
public override bool Equals(System.Object o)
{
if (this == o)
return true;
if (!(o is OpenBitSet))
return false;
OpenBitSet a;
OpenBitSet b = (OpenBitSet) o;
// make a the larger set.
if (b.wlen > this.wlen)
{
a = b; b = this;
}
else
{
a = this;
}
// check for any set bits out of the range of b
for (int i = a.wlen - 1; i >= b.wlen; i--)
{
if (a.internalbits[i] != 0)
return false;
}
for (int i = b.wlen - 1; i >= 0; i--)
{
if (a.internalbits[i] != b.internalbits[i])
return false;
}
return true;
}
public override int GetHashCode()
{
// Start with a zero hash and use a mix that results in zero if the input is zero.
// This effectively truncates trailing zeros without an explicit check.
long h = 0;
for (int i = internalbits.Length; --i >= 0; )
{
h ^= internalbits[i];
h = (h << 1) | (Number.URShift(h, 63)); // rotate left
}
// fold leftmost bits into right and add a constant to prevent
// empty sets from returning 0, which is too common.
return (int)(((h >> 32) ^ h) + 0x98761234);
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
//#define ConfigTrace
using Microsoft.VisualStudio.Shell.Interop;
using MSBuildConstruction = Microsoft.Build.Construction;
using MSBuildExecution = Microsoft.Build.Execution;
namespace Microsoft.VisualStudioTools.Project
{
[ComVisible(true)]
internal abstract class ProjectConfig :
IVsCfg,
IVsProjectCfg,
IVsProjectCfg2,
IVsProjectFlavorCfg,
IVsDebuggableProjectCfg,
ISpecifyPropertyPages,
IVsSpecifyProjectDesignerPages,
IVsCfgBrowseObject
{
internal const string Debug = "Debug";
internal const string AnyCPU = "AnyCPU";
private ProjectNode project;
private string configName;
private MSBuildExecution.ProjectInstance currentConfig;
private IVsProjectFlavorCfg flavoredCfg;
private List<OutputGroup> outputGroups;
private BuildableProjectConfig buildableCfg;
#region properties
internal ProjectNode ProjectMgr
{
get
{
return this.project;
}
}
public string ConfigName
{
get
{
return this.configName;
}
set
{
this.configName = value;
}
}
protected IList<OutputGroup> OutputGroups
{
get
{
if (null == this.outputGroups)
{
// Initialize output groups
this.outputGroups = new List<OutputGroup>();
// Get the list of group names from the project.
// The main reason we get it from the project is to make it easier for someone to modify
// it by simply overriding that method and providing the correct MSBuild target(s).
IList<KeyValuePair<string, string>> groupNames = project.GetOutputGroupNames();
if (groupNames != null)
{
// Populate the output array
foreach (KeyValuePair<string, string> group in groupNames)
{
OutputGroup outputGroup = CreateOutputGroup(project, group);
this.outputGroups.Add(outputGroup);
}
}
}
return this.outputGroups;
}
}
#endregion
#region ctors
internal ProjectConfig(ProjectNode project, string configuration)
{
this.project = project;
this.configName = configuration;
var flavoredCfgProvider = ProjectMgr.GetOuterInterface<IVsProjectFlavorCfgProvider>();
Utilities.ArgumentNotNull("flavoredCfgProvider", flavoredCfgProvider);
ErrorHandler.ThrowOnFailure(flavoredCfgProvider.CreateProjectFlavorCfg(this, out flavoredCfg));
Utilities.ArgumentNotNull("flavoredCfg", flavoredCfg);
// if the flavored object support XML fragment, initialize it
IPersistXMLFragment persistXML = flavoredCfg as IPersistXMLFragment;
if (null != persistXML)
{
this.project.LoadXmlFragment(persistXML, configName);
}
}
#endregion
#region methods
internal virtual OutputGroup CreateOutputGroup(ProjectNode project, KeyValuePair<string, string> group)
{
OutputGroup outputGroup = new OutputGroup(group.Key, group.Value, project, this);
return outputGroup;
}
public void PrepareBuild(bool clean) {
project.PrepareBuild(this.configName, clean);
}
public virtual string GetConfigurationProperty(string propertyName, bool resetCache)
{
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
public virtual void SetConfigurationProperty(string propertyName, string propertyValue)
{
if (!this.project.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
string condition = String.Format(CultureInfo.InvariantCulture, ConfigProvider.configString, this.ConfigName);
SetPropertyUnderCondition(propertyName, propertyValue, condition);
// property cache will need to be updated
this.currentConfig = null;
this.project.SetProjectFileDirty(true);
return;
}
/// <summary>
/// Emulates the behavior of SetProperty(name, value, condition) on the old MSBuild object model.
/// This finds a property group with the specified condition (or creates one if necessary) then sets the property in there.
/// </summary>
private void SetPropertyUnderCondition(string propertyName, string propertyValue, string condition)
{
string conditionTrimmed = (condition == null) ? String.Empty : condition.Trim();
if (conditionTrimmed.Length == 0)
{
this.project.BuildProject.SetProperty(propertyName, propertyValue);
return;
}
// New OM doesn't have a convenient equivalent for setting a property with a particular property group condition.
// So do it ourselves.
MSBuildConstruction.ProjectPropertyGroupElement newGroup = null;
foreach (MSBuildConstruction.ProjectPropertyGroupElement group in this.project.BuildProject.Xml.PropertyGroups)
{
if (String.Equals(group.Condition.Trim(), conditionTrimmed, StringComparison.OrdinalIgnoreCase))
{
newGroup = group;
break;
}
}
if (newGroup == null)
{
newGroup = this.project.BuildProject.Xml.AddPropertyGroup(); // Adds after last existing PG, else at start of project
newGroup.Condition = condition;
}
foreach (MSBuildConstruction.ProjectPropertyElement property in newGroup.PropertiesReversed) // If there's dupes, pick the last one so we win
{
if (String.Equals(property.Name, propertyName, StringComparison.OrdinalIgnoreCase) && property.Condition.Length == 0)
{
property.Value = propertyValue;
return;
}
}
newGroup.AddProperty(propertyName, propertyValue);
}
/// <summary>
/// If flavored, and if the flavor config can be dirty, ask it if it is dirty
/// </summary>
/// <param name="storageType">Project file or user file</param>
/// <returns>0 = not dirty</returns>
internal int IsFlavorDirty(_PersistStorageType storageType)
{
int isDirty = 0;
if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
ErrorHandler.ThrowOnFailure(((IPersistXMLFragment)this.flavoredCfg).IsFragmentDirty((uint)storageType, out isDirty));
}
return isDirty;
}
/// <summary>
/// If flavored, ask the flavor if it wants to provide an XML fragment
/// </summary>
/// <param name="flavor">Guid of the flavor</param>
/// <param name="storageType">Project file or user file</param>
/// <param name="fragment">Fragment that the flavor wants to save</param>
/// <returns>HRESULT</returns>
internal int GetXmlFragment(Guid flavor, _PersistStorageType storageType, out string fragment)
{
fragment = null;
int hr = VSConstants.S_OK;
if (this.flavoredCfg != null && this.flavoredCfg is IPersistXMLFragment)
{
Guid flavorGuid = flavor;
hr = ((IPersistXMLFragment)this.flavoredCfg).Save(ref flavorGuid, (uint)storageType, out fragment, 1);
}
return hr;
}
#endregion
#region IVsSpecifyPropertyPages
public void GetPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration dependent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns>VSConstants.S_OK</returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages)
{
this.GetCfgPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsCfg methods
/// <summary>
/// The display name is a two part item
/// first part is the config name, 2nd part is the platform name
/// </summary>
public virtual int get_DisplayName(out string name)
{
name = DisplayName;
return VSConstants.S_OK;
}
private string DisplayName
{
get
{
string name;
string[] platform = new string[1];
uint[] actual = new uint[1];
name = this.configName;
// currently, we only support one platform, so just add it..
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(project.GetCfgProvider(out provider));
ErrorHandler.ThrowOnFailure(((IVsCfgProvider2)provider).GetPlatformNames(1, platform, actual));
if (!string.IsNullOrEmpty(platform[0]))
{
name += "|" + platform[0];
}
return name;
}
}
public virtual int get_IsDebugOnly(out int fDebug)
{
fDebug = 0;
if (this.configName == "Debug")
{
fDebug = 1;
}
return VSConstants.S_OK;
}
public virtual int get_IsReleaseOnly(out int fRelease)
{
fRelease = 0;
if (this.configName == "Release")
{
fRelease = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsProjectCfg methods
public virtual int EnumOutputs(out IVsEnumOutputs eo)
{
eo = null;
return VSConstants.E_NOTIMPL;
}
public virtual int get_BuildableProjectCfg(out IVsBuildableProjectCfg pb)
{
if (buildableCfg == null) {
buildableCfg = new BuildableProjectConfig(this);
}
pb = buildableCfg;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CanonicalName(out string name)
{
name = configName;
return VSConstants.S_OK;
}
public virtual int get_IsPackaged(out int pkgd)
{
pkgd = 0;
return VSConstants.S_OK;
}
public virtual int get_IsSpecifyingOutputSupported(out int f)
{
f = 1;
return VSConstants.S_OK;
}
public virtual int get_Platform(out Guid platform)
{
platform = Guid.Empty;
return VSConstants.E_NOTIMPL;
}
public virtual int get_ProjectCfgProvider(out IVsProjectCfgProvider p)
{
p = null;
IVsCfgProvider cfgProvider = null;
this.project.GetCfgProvider(out cfgProvider);
if (cfgProvider != null)
{
p = cfgProvider as IVsProjectCfgProvider;
}
return (null == p) ? VSConstants.E_NOTIMPL : VSConstants.S_OK;
}
public virtual int get_RootURL(out string root)
{
root = null;
return VSConstants.S_OK;
}
public virtual int get_TargetCodePage(out uint target)
{
target = (uint)System.Text.Encoding.Default.CodePage;
return VSConstants.S_OK;
}
public virtual int get_UpdateSequenceNumber(ULARGE_INTEGER[] li)
{
Utilities.ArgumentNotNull("li", li);
li[0] = new ULARGE_INTEGER();
li[0].QuadPart = 0;
return VSConstants.S_OK;
}
public virtual int OpenOutput(string name, out IVsOutput output)
{
output = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectCfg2 Members
public virtual int OpenOutputGroup(string szCanonicalName, out IVsOutputGroup ppIVsOutputGroup)
{
ppIVsOutputGroup = null;
// Search through our list of groups to find the one they are looking forgroupName
foreach (OutputGroup group in OutputGroups)
{
string groupName;
group.get_CanonicalName(out groupName);
if (String.Compare(groupName, szCanonicalName, StringComparison.OrdinalIgnoreCase) == 0)
{
ppIVsOutputGroup = group;
break;
}
}
return (ppIVsOutputGroup != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
}
public virtual int OutputsRequireAppRoot(out int pfRequiresAppRoot)
{
pfRequiresAppRoot = 0;
return VSConstants.E_NOTIMPL;
}
public virtual int get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
// Delegate to the flavored configuration (to enable a flavor to take control)
// Since we can be asked for Configuration we don't support, avoid throwing and return the HRESULT directly
int hr = flavoredCfg.get_CfgType(ref iidCfg, out ppCfg);
return hr;
}
public virtual int get_IsPrivate(out int pfPrivate)
{
pfPrivate = 0;
return VSConstants.S_OK;
}
public virtual int get_OutputGroups(uint celt, IVsOutputGroup[] rgpcfg, uint[] pcActual)
{
// Are they only asking for the number of groups?
if (celt == 0)
{
if ((null == pcActual) || (0 == pcActual.Length))
{
throw new ArgumentNullException("pcActual");
}
pcActual[0] = (uint)OutputGroups.Count;
return VSConstants.S_OK;
}
// Check that the array of output groups is not null
if ((null == rgpcfg) || (rgpcfg.Length == 0))
{
throw new ArgumentNullException("rgpcfg");
}
// Fill the array with our output groups
uint count = 0;
foreach (OutputGroup group in OutputGroups)
{
if (rgpcfg.Length > count && celt > count && group != null)
{
rgpcfg[count] = group;
++count;
}
}
if (pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_VirtualRoot(out string pbstrVRoot)
{
pbstrVRoot = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsDebuggableProjectCfg methods
/// <summary>
/// Called by the vs shell to start debugging (managed or unmanaged).
/// Override this method to support other debug engines.
/// </summary>
/// <param name="grfLaunch">A flag that determines the conditions under which to start the debugger. For valid grfLaunch values, see __VSDBGLAUNCHFLAGS</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code</returns>
public abstract int DebugLaunch(uint grfLaunch);
/// <summary>
/// Determines whether the debugger can be launched, given the state of the launch flags.
/// </summary>
/// <param name="flags">Flags that determine the conditions under which to launch the debugger.
/// For valid grfLaunch values, see __VSDBGLAUNCHFLAGS or __VSDBGLAUNCHFLAGS2.</param>
/// <param name="fCanLaunch">true if the debugger can be launched, otherwise false</param>
/// <returns>S_OK if the method succeeds, otherwise an error code</returns>
public virtual int QueryDebugLaunch(uint flags, out int fCanLaunch)
{
string assembly = this.project.GetAssemblyName(this.ConfigName);
fCanLaunch = (assembly != null && assembly.ToUpperInvariant().EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) ? 1 : 0;
if (fCanLaunch == 0)
{
string property = GetConfigurationProperty("StartProgram", true);
fCanLaunch = (property != null && property.Length > 0) ? 1 : 0;
}
return VSConstants.S_OK;
}
#endregion
#region IVsCfgBrowseObject
/// <summary>
/// Maps back to the configuration corresponding to the browse object.
/// </summary>
/// <param name="cfg">The IVsCfg object represented by the browse object</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetCfg(out IVsCfg cfg)
{
cfg = this;
return VSConstants.S_OK;
}
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
{
Utilities.CheckNotNull(this.project);
Utilities.CheckNotNull(this.project.NodeProperties);
return this.project.NodeProperties.GetProjectItem(out hier, out itemid);
}
#endregion
#region helper methods
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache)
{
if (resetCache || this.currentConfig == null)
{
// Get properties for current configuration from project file and cache it
this.project.SetConfiguration(this.ConfigName);
this.project.BuildProject.ReevaluateIfNecessary();
// Create a snapshot of the evaluated project in its current state
this.currentConfig = this.project.BuildProject.CreateProjectInstance();
// Restore configuration
project.SetCurrentConfiguration();
}
if (this.currentConfig == null)
throw new Exception("Failed to retrieve properties");
// return property asked for
return this.currentConfig.GetProperty(propertyName);
}
/// <summary>
/// Retrieves the configuration dependent property pages.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCfgPropertyPages(CAUUID[] pages)
{
// We do not check whether the supportsProjectDesigner is set to true on the ProjectNode.
// We rely that the caller knows what to call on us.
Utilities.ArgumentNotNull("pages", pages);
if (pages.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
}
// Retrive the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = project.GetOuterInterface<IVsHierarchy>();
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out variant), new int[] { VSConstants.DISP_E_MEMBERNOTFOUND, VSConstants.E_NOTIMPL });
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if (guids == null || guids.Length == 0)
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
else
{
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
#endregion
#region IVsProjectFlavorCfg Members
/// <summary>
/// This is called to let the flavored config let go
/// of any reference it may still be holding to the base config
/// </summary>
/// <returns></returns>
int IVsProjectFlavorCfg.Close()
{
// This is used to release the reference the flavored config is holding
// on the base config, but in our scenario these 2 are the same object
// so we have nothing to do here.
return VSConstants.S_OK;
}
/// <summary>
/// Actual implementation of get_CfgType.
/// When not flavored or when the flavor delegate to use
/// we end up creating the requested config if we support it.
/// </summary>
/// <param name="iidCfg">IID representing the type of config object we should create</param>
/// <param name="ppCfg">Config object that the method created</param>
/// <returns>HRESULT</returns>
int IVsProjectFlavorCfg.get_CfgType(ref Guid iidCfg, out IntPtr ppCfg)
{
ppCfg = IntPtr.Zero;
// See if this is an interface we support
if (iidCfg == typeof(IVsDebuggableProjectCfg).GUID)
{
ppCfg = Marshal.GetComInterfaceForObject(this, typeof(IVsDebuggableProjectCfg));
} else if (iidCfg == typeof(IVsBuildableProjectCfg).GUID) {
IVsBuildableProjectCfg buildableConfig;
this.get_BuildableProjectCfg(out buildableConfig);
ppCfg = Marshal.GetComInterfaceForObject(buildableConfig, typeof(IVsBuildableProjectCfg));
}
// If not supported
if (ppCfg == IntPtr.Zero)
return VSConstants.E_NOINTERFACE;
return VSConstants.S_OK;
}
#endregion
}
[ComVisible(true)]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Buildable")]
internal class BuildableProjectConfig : IVsBuildableProjectCfg {
#region fields
ProjectConfig config = null;
EventSinkCollection callbacks = new EventSinkCollection();
#endregion
#region ctors
public BuildableProjectConfig(ProjectConfig config) {
this.config = config;
}
#endregion
#region IVsBuildableProjectCfg methods
public virtual int AdviseBuildStatusCallback(IVsBuildStatusCallback callback, out uint cookie) {
cookie = callbacks.Add(callback);
return VSConstants.S_OK;
}
public virtual int get_ProjectCfg(out IVsProjectCfg p) {
p = config;
return VSConstants.S_OK;
}
public virtual int QueryStartBuild(uint options, int[] supported, int[] ready) {
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartClean(uint options, int[] supported, int[] ready) {
config.PrepareBuild(false);
if (supported != null && supported.Length > 0)
supported[0] = 1;
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStartUpToDateCheck(uint options, int[] supported, int[] ready) {
config.PrepareBuild(false);
if (supported != null && supported.Length > 0)
supported[0] = 0; // TODO:
if (ready != null && ready.Length > 0)
ready[0] = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int QueryStatus(out int done) {
done = (this.config.ProjectMgr.BuildInProgress) ? 0 : 1;
return VSConstants.S_OK;
}
public virtual int StartBuild(IVsOutputWindowPane pane, uint options) {
config.PrepareBuild(false);
// Current version of MSBuild wish to be called in an STA
uint flags = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_REBUILD;
// If we are not asked for a rebuild, then we build the default target (by passing null)
this.Build(options, pane, ((options & flags) != 0) ? MsBuildTarget.Rebuild : null);
return VSConstants.S_OK;
}
public virtual int StartClean(IVsOutputWindowPane pane, uint options) {
config.PrepareBuild(true);
// Current version of MSBuild wish to be called in an STA
this.Build(options, pane, MsBuildTarget.Clean);
return VSConstants.S_OK;
}
public virtual int StartUpToDateCheck(IVsOutputWindowPane pane, uint options) {
return VSConstants.E_NOTIMPL;
}
public virtual int Stop(int fsync) {
return VSConstants.S_OK;
}
public virtual int UnadviseBuildStatusCallback(uint cookie) {
callbacks.RemoveAt(cookie);
return VSConstants.S_OK;
}
public virtual int Wait(uint ms, int fTickWhenMessageQNotEmpty) {
return VSConstants.E_NOTIMPL;
}
#endregion
#region helpers
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool NotifyBuildBegin() {
int shouldContinue = 1;
foreach (IVsBuildStatusCallback cb in callbacks) {
try {
ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
if (shouldContinue == 0) {
return false;
}
} catch (Exception e) {
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
}
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyBuildEnd(MSBuildResult result, string buildTarget) {
int success = ((result == MSBuildResult.Successful) ? 1 : 0);
foreach (IVsBuildStatusCallback cb in callbacks) {
try {
ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
} catch (Exception e) {
// If those who ask for status have bugs in their code it should not prevent the build/notification from happening
Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
} finally {
// We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
bool shouldRepaintReferences = (buildTarget == null || buildTarget == MsBuildTarget.Build || buildTarget == MsBuildTarget.Rebuild);
// Now repaint references if that is needed.
// We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
// One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
// but msbuild can actually resolve it.
// Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
if (shouldRepaintReferences && (result == MSBuildResult.Successful)) {
this.RefreshReferences();
}
}
}
}
private void Build(uint options, IVsOutputWindowPane output, string target) {
if (!this.NotifyBuildBegin()) {
return;
}
try {
config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
} catch (Exception e) {
Trace.WriteLine("Exception : " + e.Message);
ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
this.NotifyBuildEnd(MSBuildResult.Failed, target);
throw;
} finally {
ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
}
}
/// <summary>
/// Refreshes references and redraws them correctly.
/// </summary>
private void RefreshReferences() {
// Refresh the reference container node for assemblies that could be resolved.
IReferenceContainer referenceContainer = this.config.ProjectMgr.GetReferenceContainer();
if (referenceContainer != null) {
foreach (ReferenceNode referenceNode in referenceContainer.EnumReferences()) {
referenceNode.RefreshReference();
}
}
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Testing;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Tests.Visual.UserInterface
{
public class TestSceneRearrangeableListContainer : ManualInputManagerTestScene
{
private TestRearrangeableList list;
private Container listContainer;
[SetUp]
public void Setup() => Schedule(() =>
{
Child = listContainer = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500, 300),
Child = list = new TestRearrangeableList { RelativeSizeAxes = Axes.Both }
};
});
[Test]
public void TestAddItem()
{
for (int i = 0; i < 5; i++)
{
int localI = i;
addItems(1);
AddAssert($"last item is \"{i}\"", () => list.ChildrenOfType<RearrangeableListItem<int>>().Last().Model == localI);
}
}
[Test]
public void TestBindBeforeLoad()
{
AddStep("create list", () => list = new TestRearrangeableList { RelativeSizeAxes = Axes.Both });
AddStep("bind list to items", () => list.Items.BindTo(new BindableList<int>(new[] { 1, 2, 3 })));
AddStep("add list to hierarchy", () => listContainer.Add(list));
}
[Test]
public void TestAddDuplicateItemsFails()
{
const int item = 1;
AddStep("add item 1", () => list.Items.Add(item));
AddAssert("add same item throws", () =>
{
try
{
list.Items.Add(item);
return false;
}
catch (InvalidOperationException)
{
return true;
}
});
}
[Test]
public void TestRemoveItem()
{
addItems(5);
for (int i = 0; i < 5; i++)
{
int localI = i;
AddStep($"remove item \"{i}\"", () => list.Items.Remove(localI));
AddAssert($"first item is not \"{i}\"", () => list.ChildrenOfType<RearrangeableListItem<int>>().FirstOrDefault()?.Model != localI);
}
}
[Test]
public void TestClearItems()
{
addItems(5);
AddStep("clear items", () => list.Items.Clear());
AddAssert("no items contained", () => !list.ChildrenOfType<RearrangeableListItem<string>>().Any());
}
[Test]
public void TestRearrangeByDrag()
{
addItems(5);
addDragSteps(1, 4, new[] { 0, 2, 3, 4, 1 });
addDragSteps(1, 3, new[] { 0, 2, 1, 3, 4 });
addDragSteps(0, 3, new[] { 2, 1, 3, 0, 4 });
addDragSteps(3, 4, new[] { 2, 1, 0, 4, 3 });
addDragSteps(4, 2, new[] { 4, 2, 1, 0, 3 });
addDragSteps(2, 4, new[] { 2, 4, 1, 0, 3 });
}
[Test]
public void TestRearrangeByDragWithHiddenItems()
{
addItems(6);
AddStep("hide item zero", () => list.ListContainer.First(i => i.Model == 0).Hide());
addDragSteps(2, 5, new[] { 0, 1, 3, 4, 5, 2 });
addDragSteps(2, 4, new[] { 0, 1, 3, 2, 4, 5 });
addDragSteps(1, 4, new[] { 0, 3, 2, 4, 1, 5 });
addDragSteps(4, 5, new[] { 0, 3, 2, 1, 5, 4 });
addDragSteps(5, 3, new[] { 0, 5, 3, 2, 1, 4 });
addDragSteps(3, 5, new[] { 0, 3, 5, 2, 1, 4 });
}
[Test]
public void TestRearrangeByDragAfterRemoval()
{
addItems(5);
addDragSteps(0, 4, new[] { 1, 2, 3, 4, 0 });
addDragSteps(1, 4, new[] { 2, 3, 4, 1, 0 });
addDragSteps(2, 4, new[] { 3, 4, 2, 1, 0 });
addDragSteps(3, 4, new[] { 4, 3, 2, 1, 0 });
AddStep("remove 3 and 2", () =>
{
list.Items.Remove(3);
list.Items.Remove(2);
});
addDragSteps(4, 0, new[] { 1, 0, 4 });
addDragSteps(0, 1, new[] { 0, 1, 4 });
addDragSteps(4, 0, new[] { 4, 0, 1 });
}
[Test]
public void TestRemoveAfterDragScrollThenTryRearrange()
{
addItems(5);
// Scroll
AddStep("move mouse to first item", () => InputManager.MoveMouseTo(getItem(0)));
AddStep("begin a drag", () => InputManager.PressButton(MouseButton.Left));
AddStep("move the mouse", () => InputManager.MoveMouseTo(getItem(0), new Vector2(0, 30)));
AddStep("end the drag", () => InputManager.ReleaseButton(MouseButton.Left));
AddStep("remove all but one item", () =>
{
for (int i = 0; i < 4; i++)
list.Items.Remove(getItem(i).Model);
});
// Drag
AddStep("move mouse to first dragger", () => InputManager.MoveMouseTo(getDragger(4)));
AddStep("begin a drag", () => InputManager.PressButton(MouseButton.Left));
AddStep("move the mouse", () => InputManager.MoveMouseTo(getDragger(4), new Vector2(0, 30)));
AddStep("end the drag", () => InputManager.ReleaseButton(MouseButton.Left));
}
[Test]
public void TestScrolledWhenDraggedToBoundaries()
{
addItems(100);
AddStep("scroll to item 50", () => list.ScrollTo(50));
float scrollPosition = 0;
AddStep("get scroll position", () => scrollPosition = list.ScrollPosition);
AddStep("move to 52", () =>
{
InputManager.MoveMouseTo(getDragger(52));
InputManager.PressButton(MouseButton.Left);
});
AddStep("drag to 0", () => InputManager.MoveMouseTo(getDragger(0), new Vector2(0, -1)));
AddUntilStep("scrolling up", () => list.ScrollPosition < scrollPosition);
AddUntilStep("52 is the first item", () => list.Items.First() == 52);
AddStep("drag to 99", () => InputManager.MoveMouseTo(getDragger(99), new Vector2(0, 1)));
AddUntilStep("scrolling down", () => list.ScrollPosition > scrollPosition);
AddUntilStep("52 is the last item", () => list.Items.Last() == 52);
}
[Test]
public void TestRearrangeWhileAddingItems()
{
addItems(2);
AddStep("grab item 0", () =>
{
InputManager.MoveMouseTo(getDragger(0));
InputManager.PressButton(MouseButton.Left);
});
AddStep("move to bottom", () => InputManager.MoveMouseTo(list.ToScreenSpace(list.LayoutRectangle.BottomLeft) + new Vector2(0, 10)));
addItems(10);
AddUntilStep("0 is the last item", () => list.Items.Last() == 0);
}
[Test]
public void TestRearrangeWhileRemovingItems()
{
addItems(50);
AddStep("grab item 0", () =>
{
InputManager.MoveMouseTo(getDragger(0));
InputManager.PressButton(MouseButton.Left);
});
AddStep("move to bottom", () => InputManager.MoveMouseTo(list.ToScreenSpace(list.LayoutRectangle.BottomLeft) + new Vector2(0, 20)));
int lastItem = 49;
AddRepeatStep("remove item", () =>
{
list.Items.Remove(lastItem--);
}, 25);
AddUntilStep("0 is the last item", () => list.Items.Last() == 0);
AddRepeatStep("remove item", () =>
{
list.Items.Remove(lastItem--);
}, 25);
AddStep("release button", () => InputManager.ReleaseButton(MouseButton.Left));
}
[Test]
public void TestNotScrolledToTopOnRemove()
{
addItems(100);
float scrollPosition = 0;
AddStep("scroll to item 50", () =>
{
list.ScrollTo(50);
scrollPosition = list.ScrollPosition;
});
AddStep("remove item 50", () => list.Items.Remove(50));
AddAssert("scroll hasn't changed", () => list.ScrollPosition == scrollPosition);
}
[Test]
public void TestRemoveDuringLoadAndReAdd()
{
TestDelayedLoadRearrangeableList delayedList = null;
AddStep("create list", () => Child = delayedList = new TestDelayedLoadRearrangeableList());
AddStep("add item 1", () => delayedList.Items.Add(1));
AddStep("remove item 1", () => delayedList.Items.Remove(1));
AddStep("add item 1", () => delayedList.Items.Add(1));
AddStep("allow load", () => delayedList.AllowLoad.Release(100));
AddUntilStep("only one item", () => delayedList.ChildrenOfType<BasicRearrangeableListItem<int>>().Count() == 1);
}
private void addDragSteps(int from, int to, int[] expectedSequence)
{
AddStep($"move to {from}", () =>
{
InputManager.MoveMouseTo(getDragger(from));
InputManager.PressButton(MouseButton.Left);
});
AddStep($"drag to {to}", () =>
{
var fromDragger = getDragger(from);
var toDragger = getDragger(to);
InputManager.MoveMouseTo(getDragger(to), fromDragger.ScreenSpaceDrawQuad.TopLeft.Y < toDragger.ScreenSpaceDrawQuad.TopLeft.Y ? new Vector2(0, 1) : new Vector2(0, -1));
});
assertSequence(expectedSequence);
AddStep("release button", () => InputManager.ReleaseButton(MouseButton.Left));
}
private void assertSequence(params int[] sequence)
{
AddAssert($"sequence is {string.Join(", ", sequence)}",
() => list.Items.SequenceEqual(sequence.Select(value => value)));
}
private void addItems(int count)
{
AddStep($"add {count} item(s)", () =>
{
int startId = list.Items.Count == 0 ? 0 : list.Items.Max() + 1;
for (int i = 0; i < count; i++)
list.Items.Add(startId + i);
});
AddUntilStep("wait for items to load", () => list.ItemMap.Values.All(i => i.IsLoaded));
}
private RearrangeableListItem<int> getItem(int index)
=> list.ChildrenOfType<RearrangeableListItem<int>>().First(i => i.Model == index);
private BasicRearrangeableListItem<int>.Button getDragger(int index)
=> list.ChildrenOfType<BasicRearrangeableListItem<int>>().First(i => i.Model == index)
.ChildrenOfType<BasicRearrangeableListItem<int>.Button>().First();
private class TestRearrangeableList : BasicRearrangeableListContainer<int>
{
public float ScrollPosition => ScrollContainer.Current;
public new IReadOnlyDictionary<int, RearrangeableListItem<int>> ItemMap => base.ItemMap;
public new FillFlowContainer<RearrangeableListItem<int>> ListContainer => base.ListContainer;
public void ScrollTo(int item)
=> ScrollContainer.ScrollTo(this.ChildrenOfType<BasicRearrangeableListItem<int>>().First(i => i.Model == item), false);
}
private class TestDelayedLoadRearrangeableList : BasicRearrangeableListContainer<int>
{
public readonly SemaphoreSlim AllowLoad = new SemaphoreSlim(0, 100);
protected override BasicRearrangeableListItem<int> CreateBasicItem(int item) => new TestRearrangeableListItem(item, AllowLoad);
private class TestRearrangeableListItem : BasicRearrangeableListItem<int>
{
private readonly SemaphoreSlim allowLoad;
public TestRearrangeableListItem(int item, SemaphoreSlim allowLoad)
: base(item, false)
{
this.allowLoad = allowLoad;
}
[BackgroundDependencyLoader]
private void load()
{
if (!allowLoad.Wait(TimeSpan.FromSeconds(10)))
throw new TimeoutException();
}
}
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/localized_text.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Type {
/// <summary>Holder for reflection information generated from google/type/localized_text.proto</summary>
public static partial class LocalizedTextReflection {
#region Descriptor
/// <summary>File descriptor for google/type/localized_text.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static LocalizedTextReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiBnb29nbGUvdHlwZS9sb2NhbGl6ZWRfdGV4dC5wcm90bxILZ29vZ2xlLnR5",
"cGUiNAoNTG9jYWxpemVkVGV4dBIMCgR0ZXh0GAEgASgJEhUKDWxhbmd1YWdl",
"X2NvZGUYAiABKAlCegoPY29tLmdvb2dsZS50eXBlQhJMb2NhbGl6ZWRUZXh0",
"UHJvdG9QAVpIZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBp",
"cy90eXBlL2xvY2FsaXplZF90ZXh0O2xvY2FsaXplZF90ZXh0+AEBogIDR1RQ",
"YgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.LocalizedText), global::Google.Type.LocalizedText.Parser, new[]{ "Text", "LanguageCode" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Localized variant of a text in a particular language.
/// </summary>
public sealed partial class LocalizedText : pb::IMessage<LocalizedText>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<LocalizedText> _parser = new pb::MessageParser<LocalizedText>(() => new LocalizedText());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<LocalizedText> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.LocalizedTextReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LocalizedText() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LocalizedText(LocalizedText other) : this() {
text_ = other.text_;
languageCode_ = other.languageCode_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public LocalizedText Clone() {
return new LocalizedText(this);
}
/// <summary>Field number for the "text" field.</summary>
public const int TextFieldNumber = 1;
private string text_ = "";
/// <summary>
/// Localized string in the language corresponding to `language_code' below.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Text {
get { return text_; }
set {
text_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "language_code" field.</summary>
public const int LanguageCodeFieldNumber = 2;
private string languageCode_ = "";
/// <summary>
/// The text's BCP-47 language code, such as "en-US" or "sr-Latn".
///
/// For more information, see
/// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string LanguageCode {
get { return languageCode_; }
set {
languageCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as LocalizedText);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(LocalizedText other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Text != other.Text) return false;
if (LanguageCode != other.LanguageCode) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Text.Length != 0) hash ^= Text.GetHashCode();
if (LanguageCode.Length != 0) hash ^= LanguageCode.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Text.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Text);
}
if (LanguageCode.Length != 0) {
output.WriteRawTag(18);
output.WriteString(LanguageCode);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Text.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Text);
}
if (LanguageCode.Length != 0) {
output.WriteRawTag(18);
output.WriteString(LanguageCode);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Text.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Text);
}
if (LanguageCode.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(LanguageCode);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(LocalizedText other) {
if (other == null) {
return;
}
if (other.Text.Length != 0) {
Text = other.Text;
}
if (other.LanguageCode.Length != 0) {
LanguageCode = other.LanguageCode;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Text = input.ReadString();
break;
}
case 18: {
LanguageCode = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Text = input.ReadString();
break;
}
case 18: {
LanguageCode = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
//
// 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.
//
namespace NLog
{
using System;
using System.ComponentModel;
using JetBrains.Annotations;
/// <summary>
/// Logger with only generic methods (passing 'LogLevel' to methods) and core properties.
/// </summary>
public partial interface ILoggerBase
{
/// <summary>
/// Occurs when logger configuration changes.
/// </summary>
event EventHandler<EventArgs> LoggerReconfigured;
/// <summary>
/// Gets the name of the logger.
/// </summary>
string Name
{
get;
}
/// <summary>
/// Gets the factory that created this logger.
/// </summary>
LogFactory Factory
{
get;
}
/// <summary>
/// Gets a value indicating whether logging is enabled for the specified level.
/// </summary>
/// <param name="level">Log level to be checked.</param>
/// <returns>A value of <see langword="true" /> if logging is enabled for the specified level, otherwise it returns <see langword="false" />.</returns>
bool IsEnabled(LogLevel level);
#region Log() overloads
/// <summary>
/// Writes the specified diagnostic message.
/// </summary>
/// <param name="logEvent">Log event.</param>
void Log(LogEventInfo logEvent);
/// <summary>
/// Writes the specified diagnostic message.
/// </summary>
/// <param name="wrapperType">The name of the type that wraps Logger.</param>
/// <param name="logEvent">Log event.</param>
void Log(Type wrapperType, LogEventInfo logEvent);
/// <overloads>
/// Writes the diagnostic message at the specified level using the specified format provider and format parameters.
/// </overloads>
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <typeparam name="T">Type of the value.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="value">The value to be written.</param>
void Log<T>(LogLevel level, T value);
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <typeparam name="T">Type of the value.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="value">The value to be written.</param>
void Log<T>(LogLevel level, IFormatProvider formatProvider, T value);
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param>
void Log(LogLevel level, LogMessageGenerator messageFunc);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="exception">An exception to be logged.</param>
/// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")]
[EditorBrowsable(EditorBrowsableState.Never)]
void LogException(LogLevel level, [Localizable(false)] string message, Exception exception);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="args">Arguments to format.</param>
/// <param name="exception">An exception to be logged.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, Exception exception, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="args">Arguments to format.</param>
/// <param name="exception">An exception to be logged.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, Exception exception, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters and formatting them with the supplied format provider.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="args">Arguments to format.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">Log message.</param>
void Log(LogLevel level, [Localizable(false)] string message);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing format items.</param>
/// <param name="args">Arguments to format.</param>
[MessageTemplateFormatMethod("message")]
void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, params object[] args);
/// <summary>
/// Writes the diagnostic message and exception at the specified level.
/// </summary>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> to be written.</param>
/// <param name="exception">An exception to be logged.</param>
/// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete before v4.3.11")]
[EditorBrowsable(EditorBrowsableState.Never)]
void Log(LogLevel level, [Localizable(false)] string message, Exception exception);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameter and formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument">The type of the argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameter.
/// </summary>
/// <typeparam name="TArgument">The type of the argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument">The argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument argument);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified arguments formatting it with the supplied format provider.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <typeparam name="TArgument3">The type of the third argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
/// <param name="argument3">The third argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3);
/// <summary>
/// Writes the diagnostic message at the specified level using the specified parameters.
/// </summary>
/// <typeparam name="TArgument1">The type of the first argument.</typeparam>
/// <typeparam name="TArgument2">The type of the second argument.</typeparam>
/// <typeparam name="TArgument3">The type of the third argument.</typeparam>
/// <param name="level">The log level.</param>
/// <param name="message">A <see langword="string" /> containing one format item.</param>
/// <param name="argument1">The first argument to format.</param>
/// <param name="argument2">The second argument to format.</param>
/// <param name="argument3">The third argument to format.</param>
[MessageTemplateFormatMethod("message")]
void Log<TArgument1, TArgument2, TArgument3>(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1 argument1, TArgument2 argument2, TArgument3 argument3);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SendPacketsAsync
{
private readonly ITestOutputHelper _log;
private IPAddress _serverAddress = IPAddress.IPv6Loopback;
// Accessible directories for UWP app:
// C:\Users\<UserName>\AppData\Local\Packages\<ApplicationPackageName>\
private string TestFileName = Environment.GetEnvironmentVariable("LocalAppData") + @"\NCLTest.Socket.SendPacketsAsync.testpayload";
private static int s_testFileSize = 1024;
#region Additional test attributes
public SendPacketsAsync(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
byte[] buffer = new byte[s_testFileSize];
for (int i = 0; i < s_testFileSize; i++)
{
buffer[i] = (byte)(i % 255);
}
try
{
_log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize);
using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew))
{
fs.Write(buffer, 0, buffer.Length);
}
}
catch (IOException)
{
// Test payload file already exists.
_log.WriteLine("Payload file exists: {0}", TestFileName);
}
}
#endregion Additional test attributes
#region Basic Arguments
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Disposed_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
sock.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
{
sock.SendPacketsAsync(new SocketAsyncEventArgs());
});
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullArgs_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
AssertExtensions.Throws<ArgumentNullException>("e", () => sock.SendPacketsAsync(null));
}
}
}
[Fact]
public void NotConnected_Throw()
{
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
// Needs to be connected before send
Assert.Throws<NotSupportedException>(() =>
{
socket.SendPacketsAsync(new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] });
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null m_SendPacketsElementsInternal array")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullList_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentNullException>("e.SendPacketsElements", () => SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0));
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NullElement_Ignored(SocketImplementationType type)
{
SendPackets(type, (SendPacketsElement)null, 0);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void EmptyList_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SocketAsyncEventArgs_DefaultSendSize_0()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
Assert.Equal(0, args.SendPacketsSendSize);
}
#endregion Basic Arguments
#region Buffers
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBuffer_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10]), 10);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBufferRange_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void EmptyBuffer_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[0]), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferZeroCount_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type)
{
SendPacketsElement[] elements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[10], 4, 0), // Ignored
new SendPacketsElement(new byte[10], 4, 4),
new SendPacketsElement(new byte[10], 0, 4)
};
SendPackets(type, elements, SocketError.Success, 8);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
// First do an empty send, ignored
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 3, 0)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(0, args.BytesTransferred);
completed.Reset();
// Now do a real send
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 1, 4)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(4, args.BytesTransferred);
}
}
}
}
#endregion Buffers
#region TransmitFileOptions
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4);
}
#endregion
#region Files
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
SendPackets(type, new SendPacketsElement(string.Empty), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix
public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(" "), 0);
});
}
[Theory]
[ActiveIssue(27269)]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix
public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type)
{
AssertExtensions.Throws<ArgumentException>("path", null, () =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type)
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type)
{
Assert.Throws<FileNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("DoesntExit"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_File_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FilePart_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type)
{
SendPacketsElement[] elements = new SendPacketsElement[]
{
new SendPacketsElement(TestFileName, 10, 20),
new SendPacketsElement(TestFileName, 30, 10),
new SendPacketsElement(TestFileName, 0, 10),
};
SendPackets(type, elements, SocketError.Success, 40);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0);
}
#endregion Files
#region Helpers
private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = new[] { element };
args.SendPacketsFlags = flags;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
switch (flags)
{
case TransmitFileOptions.Disconnect:
// Sending data again throws with socket shut down error.
Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); });
break;
case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect:
// Able to send data again with reuse socket flag set.
Assert.Equal(1, sock.Send(new byte[1] { 01 }));
break;
}
}
}
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected)
{
SendPackets(type, new SendPacketsElement[] { element }, SocketError.Success, bytesExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResut, int bytesExpected)
{
SendPackets(type, new SendPacketsElement[] { element }, expectedResut, bytesExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResut, int bytesExpected)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = elements;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(expectedResut, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
}
}
}
private void OnCompleted(object sender, SocketAsyncEventArgs e)
{
EventWaitHandle handle = (EventWaitHandle)e.UserToken;
handle.Set();
}
#endregion Helpers
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace OneNoteDuplicatesRemover
{
public class OneNoteAccessor
{
// Member Variables
private OneNoteApplicationWrapper onenoteApplication = null;
private Dictionary<string, OneNotePageInfo> pageInfos = null;
private string lastSelectedPageId = null;
public delegate void CancelledEventHandler();
public event CancelledEventHandler OnCancelled = null;
public Tuple<bool, string> InitializeOneNoteWrapper()
{
onenoteApplication = new OneNoteApplicationWrapper();
if (onenoteApplication.InitializeOneNoteTypeLibrary())
{
return Tuple.Create(true, "");
}
else
{
return Tuple.Create(false, "Unable to initialize OneNote type library.");
}
}
public Type GetApplicationType()
{
return onenoteApplication.GetApplicationType();
}
private Tuple<bool, string> UpdatePageInfos()
{
pageInfos = new Dictionary<string, OneNotePageInfo>();
string rawXmlString = "";
if (onenoteApplication.TryGetPageHierarchyAsXML(out rawXmlString) == false)
{
return Tuple.Create(false, "Unable to retrieve page hierarchy.");
}
etc.LoggerHelper.LogInfo("Retrieved page hierarchy: {0} bytes.", rawXmlString.Length);
System.Xml.XmlDocument hierarchyXml = new System.Xml.XmlDocument();
try
{
hierarchyXml.LoadXml(rawXmlString);
}
catch (System.Exception exception)
{
etc.LoggerHelper.LogUnexpectedException(exception);
return Tuple.Create(false, "Unable to parse page hierarchy.");
}
System.Xml.XmlNodeList pageNodeList = hierarchyXml.GetElementsByTagName("one:Page");
foreach (System.Xml.XmlNode pageNode in pageNodeList)
{
try
{
string pageUniqueId = pageNode.Attributes["ID"].Value;
string parentNodeName = pageNode.ParentNode.Name;
if (parentNodeName == "one:Section")
{
// We must check whether the pages are deleted. Otherwise, we may end up deleting the duplicates in the trash folder.
if (IsPageDeleted(pageNode) == false)
{
if (pageInfos.ContainsKey(pageUniqueId) == false)
{
// 'ID', 'path' and 'name' attributes always exist.
string sectionId = pageNode.ParentNode.Attributes["ID"].Value;
string sectionPath = pageNode.ParentNode.Attributes["path"].Value;
string sectionName = pageNode.ParentNode.Attributes["name"].Value;
OneNotePageInfo newPageInfo = new OneNotePageInfo();
newPageInfo.ParentSectionId = sectionId;
newPageInfo.ParentSectionFilePath = sectionPath;
newPageInfo.ParentSectionName = sectionName;
newPageInfo.PageTitle = pageNode.Attributes["name"].Value;
pageInfos.Add(pageUniqueId, newPageInfo);
}
else
{
return Tuple.Create(false, string.Format("The page id ({0}) is not unique.", pageUniqueId));
}
}
}
}
catch (System.Exception exception)
{
etc.LoggerHelper.LogUnexpectedException(exception);
return Tuple.Create(false, "The page hierarchy is corrupted.");
}
}
return Tuple.Create(true, "");
}
public Tuple<bool, string> ScanOneNotePages(IProgress<Tuple<int, int, int, string>> progress, System.Threading.CancellationToken cancellationToken)
{
Tuple<bool, string> resultUpdatePageInfos = UpdatePageInfos();
if (resultUpdatePageInfos.Item1 == false)
{
return resultUpdatePageInfos;
}
else
{
etc.LoggerHelper.LogInfo("Found {0} pages.", pageInfos.Count);
int statCountReadSuccess = 0;
int statCountReadFailed = 0;
int statCountTotal = pageInfos.Count;
string statPageTitle = null;
progress.Report(Tuple.Create(statCountReadSuccess, statCountReadFailed, statCountTotal, statPageTitle));
foreach (KeyValuePair<string, OneNotePageInfo> elem in pageInfos)
{
if (cancellationToken.IsCancellationRequested)
{
OnCancelled.Invoke();
break;
}
string pageId = elem.Key;
OneNotePageInfo pageInfo = elem.Value;
string pageContent = "";
bool successHash = false;
pageInfo.HashValueForInnerText = null;
if (onenoteApplication.TryGetPageContent(elem.Key, out pageContent))
{
try
{
System.Xml.XmlDocument pageContentXml = new System.Xml.XmlDocument();
pageContentXml.LoadXml(pageContent);
/*
* Though the page contents are identical, it is quite common to see different 'objectID' and 'lastModified' attributes.
* This difference results in a completely different hash value, which cannot be detected by other duplicate remove software.
* By simply taking 'innerText' of the internal XML-like format, those attributes will be ignored.
* [!] The underlying assumption is that a user cannot modify the attributes directly.
*/
if (TryCalculateHashValue(pageContentXml.InnerText, out string hashValue))
{
successHash = true;
pageInfo.HashValueForInnerText = hashValue;
}
else
{
etc.LoggerHelper.LogWarn("Failed to calculate hash for the page ({0}).", pageId);
}
}
catch (System.Exception exception)
{
etc.LoggerHelper.LogUnexpectedException(exception);
}
}
statPageTitle = pageInfo.PageTitle;
if (successHash)
{
statCountReadSuccess += 1;
}
else
{
statCountReadFailed += 1;
etc.LoggerHelper.LogWarn("Failed to retrieve the content of the page ({0}).", pageId);
}
progress.Report(Tuple.Create(statCountReadSuccess, statCountReadFailed, statCountTotal, statPageTitle));
}
}
return Tuple.Create(true, "");
}
public List<Tuple<string, string, bool>> RemovePages(List<Tuple<string, string>> pagesBeingRemoved, IProgress<Tuple<int, int, int, string>> progress, System.Threading.CancellationToken cancellationToken)
{
int countRemoved = 0;
int countFailedToRemove = 0;
int countTotal = pagesBeingRemoved.Count;
List<Tuple<string, string, bool>> ret = new List<Tuple<string, string, bool>>();
foreach (Tuple<string, string> elem in pagesBeingRemoved)
{
if (cancellationToken.IsCancellationRequested)
{
OnCancelled.Invoke();
break;
}
if (onenoteApplication.TryDeleteHierarchy(elem.Item1))
{
countRemoved += 1;
ret.Add(Tuple.Create(elem.Item1, elem.Item2, true));
}
else
{
countFailedToRemove += 1;
ret.Add(Tuple.Create(elem.Item1, elem.Item2, false));
}
progress.Report(Tuple.Create(countRemoved, countFailedToRemove, countTotal, elem.Item2));
}
return ret;
}
private static List<string> SortSectionPathList(List<string> sectionPathList)
{
sectionPathList.Sort((string left, string right) =>
{
bool isLeftCloud = (left.IndexOf("https:") == 0);
bool isRightCloud = (right.IndexOf("https:") == 0);
if (isLeftCloud && !isRightCloud)
{
return -1;
}
else if (!isLeftCloud && isRightCloud)
{
return 1;
}
else
{
// NOTE: Might be unsafe if the section name contains "OneNote_RecycleBin" (very unlikely)
bool isLeftRecycleBin = left.Contains("\\OneNote_RecycleBin");
bool isRightRecycleBin = right.Contains("\\OneNote_RecycleBin");
if (isLeftRecycleBin && !isRightRecycleBin)
{
return 1;
}
else if (!isLeftRecycleBin && isRightRecycleBin)
{
return -1;
}
else
{
return left.CompareTo(right);
}
}
});
sectionPathList = sectionPathList.Distinct().ToList();
return sectionPathList;
}
public List<string> GetSectionPathList(Dictionary<string, List<Tuple<string, string>>> duplicatesGroups)
{
List<string> sectionPathList = new List<string>();
foreach (KeyValuePair<string, List<Tuple<string, string>>> groupInfo in duplicatesGroups)
{
if (groupInfo.Value.Count > 1)
{
for (int i = 0; i < groupInfo.Value.Count; ++i)
{
string pageId = groupInfo.Value[i].Item1;
string sectionPath = "";
if (TryGetSectionPath(pageId, out sectionPath))
{
sectionPathList.Add(System.IO.Path.GetDirectoryName(sectionPath));
}
}
}
}
return SortSectionPathList(sectionPathList);
}
public bool TryNavigate(string pageId)
{
/*
http://msdn.microsoft.com/en-us/library/gg649853(v=office.14).aspx
bstrPageID: The OneNote ID of the page that contains the object to delete.
bstrObjectID: The OneNote ID of the object that you want to delete.
*/
if (CheckIfPageExists(pageId))
{
if (lastSelectedPageId == null || lastSelectedPageId != pageId)
{
lastSelectedPageId = pageId;
if (onenoteApplication.TryNavigateTo(pageId))
{
return true;
}
else
{
etc.LoggerHelper.LogWarn("Navigate failed. pageId:{0}", pageId); // not critical
}
}
}
return false;
}
public bool TryFlattenSections(string targetSectionName, IProgress<Tuple<int, int, int, string>> progress, System.Threading.CancellationToken cancellationToken)
{
onenoteApplication.TryGetSectionHierarchyAsXML(out string rawXmlString);
System.Xml.XmlDocument sectionHierarchyXml = new System.Xml.XmlDocument();
try
{
sectionHierarchyXml.LoadXml(rawXmlString);
string destinationSectionId = null;
System.Xml.XmlNodeList sectionNodeList = sectionHierarchyXml.GetElementsByTagName("one:Section");
int countTotalSections = sectionNodeList.Count;
int countFlattenedSections = 0;
int countNotFlattenedSections = 0;
foreach (System.Xml.XmlNode sectionNode in sectionNodeList)
{
if (sectionNode.Attributes["name"].Value == targetSectionName)
{
destinationSectionId = sectionNode.Attributes["ID"].Value;
break;
}
}
if (destinationSectionId != null)
{
foreach (System.Xml.XmlNode sectionNode in sectionNodeList)
{
if (cancellationToken.IsCancellationRequested)
{
OnCancelled.Invoke();
break;
}
string sourceSectionName = sectionNode.Attributes["name"].Value;
if (sourceSectionName != targetSectionName)
{
string sourceSectionId = sectionNode.Attributes["ID"].Value;
if ((sectionNode.Attributes["isInRecycleBin"] == null) || (sectionNode.Attributes["isInRecycleBin"].Value != "true") &&
(sectionNode.Attributes["isDeletedPages"] == null) || (sectionNode.Attributes["isDeletedPages"].Value != "true"))
{
if (onenoteApplication.TryMergeSection(sourceSectionId, destinationSectionId))
{
countFlattenedSections += 1;
}
else
{
countNotFlattenedSections += 1;
}
}
}
progress.Report(Tuple.Create(countFlattenedSections, countNotFlattenedSections, countTotalSections, sourceSectionName));
}
return true;
}
else
{
return false;
}
}
catch (System.Exception exception)
{
etc.LoggerHelper.LogUnexpectedException(exception);
return false;
}
}
public bool CheckIfPageExists(string pageId)
{
if (pageInfos != null)
{
return pageInfos.ContainsKey(pageId);
}
else
{
etc.LoggerHelper.LogError("Pages are not loaded");
return false;
}
}
public bool TryGetSectionPath(string pageId, out string sectionPath)
{
sectionPath = "";
if (pageInfos != null)
{
if (pageInfos.ContainsKey(pageId))
{
sectionPath = pageInfos[pageId].ParentSectionFilePath;
return true;
}
else
{
etc.LoggerHelper.LogError("Page ({0}) not found!", pageId);
return false;
}
}
else
{
etc.LoggerHelper.LogError("Pages are not loaded");
return false;
}
}
public Dictionary<string, List<Tuple<string /* pageId */, string /* pageName */ >>> GetDuplicatesGroups()
{
if (pageInfos == null) { return null; }
else
{
Dictionary<string, List<Tuple<string, string>>> duplicatesGroups = new Dictionary<string, List<Tuple<string, string>>>();
foreach (KeyValuePair<string, OneNotePageInfo> elem in pageInfos)
{
string pageId = elem.Key;
OneNotePageInfo pageInfo = elem.Value;
string hashValueForInnerText = pageInfo.HashValueForInnerText;
if (hashValueForInnerText != null)
{
if (duplicatesGroups.ContainsKey(hashValueForInnerText) == false)
{
duplicatesGroups.Add(hashValueForInnerText, new List<Tuple<string, string>>());
}
duplicatesGroups[hashValueForInnerText].Add(Tuple.Create(pageId, pageInfo.PageTitle));
}
}
return duplicatesGroups;
}
}
private static bool IsPageDeleted(System.Xml.XmlNode pageNode)
{
// The 'isDeletedPages' attribute is optional. If the attribute doesn't exist, we assume that the page isn't deleted.
System.Xml.XmlAttribute isDeletedPageAttr = pageNode.ParentNode.Attributes["isDeletedPages"];
if (isDeletedPageAttr != null)
{
return bool.Parse(isDeletedPageAttr.Value);
}
else
{
return false;
}
}
private static bool TryCalculateHashValue(string rawString, out string hashValue)
{
hashValue = "";
try
{
byte[] content = Encoding.UTF8.GetBytes(rawString);
byte[] computedHashValue = System.Security.Cryptography.SHA256.Create().ComputeHash(content);
hashValue = Utils.ConvertToHexString(computedHashValue);
return true;
}
catch (System.Exception exception)
{
etc.LoggerHelper.LogUnexpectedException(exception);
return false;
}
}
}
}
| |
//
// MethodDefinition.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using RVA = System.UInt32;
namespace Mono.Cecil
{
public sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider
{
ushort attributes;
ushort impl_attributes;
internal volatile bool sem_attrs_ready;
internal MethodSemanticsAttributes sem_attrs;
Collection<CustomAttribute> custom_attributes;
Collection<SecurityDeclaration> security_declarations;
internal RVA rva;
internal PInvokeInfo pinvoke;
Collection<MethodReference> overrides;
internal MethodBody body;
public MethodAttributes Attributes
{
get { return (MethodAttributes)attributes; }
set { attributes = (ushort)value; }
}
public MethodImplAttributes ImplAttributes
{
get { return (MethodImplAttributes)impl_attributes; }
set { impl_attributes = (ushort)value; }
}
public MethodSemanticsAttributes SemanticsAttributes
{
get
{
if (sem_attrs_ready)
return sem_attrs;
if (HasImage)
{
ReadSemantics();
return sem_attrs;
}
sem_attrs = MethodSemanticsAttributes.None;
sem_attrs_ready = true;
return sem_attrs;
}
set { sem_attrs = value; }
}
internal void ReadSemantics()
{
if (sem_attrs_ready)
return;
var module = this.Module;
if (module == null)
return;
if (!module.HasImage)
return;
module.Read(this, (method, reader) => reader.ReadAllSemantics(method));
}
public bool HasSecurityDeclarations
{
get
{
if (security_declarations != null)
return security_declarations.Count > 0;
return Mixin.GetHasSecurityDeclarations(this, Module);
}
}
public Collection<SecurityDeclaration> SecurityDeclarations
{
get { return security_declarations ?? (Mixin.GetSecurityDeclarations(this, ref security_declarations, Module)); }
}
public bool HasCustomAttributes
{
get
{
if (custom_attributes != null)
return custom_attributes.Count > 0;
return Mixin.GetHasCustomAttributes(this, Module);
}
}
public Collection<CustomAttribute> CustomAttributes
{
get { return custom_attributes ?? (Mixin.GetCustomAttributes(this, ref custom_attributes, Module)); }
}
public int RVA
{
get { return (int)rva; }
}
public bool HasBody
{
get
{
return (attributes & (ushort)MethodAttributes.Abstract) == 0 &&
(attributes & (ushort)MethodAttributes.PInvokeImpl) == 0 &&
(impl_attributes & (ushort)MethodImplAttributes.InternalCall) == 0 &&
(impl_attributes & (ushort)MethodImplAttributes.Native) == 0 &&
(impl_attributes & (ushort)MethodImplAttributes.Unmanaged) == 0 &&
(impl_attributes & (ushort)MethodImplAttributes.Runtime) == 0;
}
}
public MethodBody Body
{
get
{
MethodBody localBody = this.body;
if (localBody != null)
return localBody;
if (!HasBody)
return null;
if (HasImage && rva != 0)
return Module.Read(ref body, this, (method, reader) => reader.ReadMethodBody(method));
return body = new MethodBody(this);
}
set
{
// we reset Body to null in ILSpy to save memory; so we need that operation to be thread-safe
lock (Module.SyncRoot)
{
body = value;
}
}
}
public bool HasPInvokeInfo
{
get
{
if (pinvoke != null)
return true;
return IsPInvokeImpl;
}
}
public PInvokeInfo PInvokeInfo
{
get
{
if (pinvoke != null)
return pinvoke;
if (HasImage && IsPInvokeImpl)
return Module.Read(ref pinvoke, this, (method, reader) => reader.ReadPInvokeInfo(method));
return null;
}
set
{
IsPInvokeImpl = true;
pinvoke = value;
}
}
public bool HasOverrides
{
get
{
if (overrides != null)
return overrides.Count > 0;
if (HasImage)
return Module.Read(this, (method, reader) => reader.HasOverrides(method));
return false;
}
}
public Collection<MethodReference> Overrides
{
get
{
if (overrides != null)
return overrides;
if (HasImage)
return Module.Read(ref overrides, this, (method, reader) => reader.ReadOverrides(method));
return overrides = new Collection<MethodReference>();
}
}
public override bool HasGenericParameters
{
get
{
if (generic_parameters != null)
return generic_parameters.Count > 0;
return Mixin.GetHasGenericParameters(this, Module);
}
}
public override Collection<GenericParameter> GenericParameters
{
get { return generic_parameters ?? (Mixin.GetGenericParameters(this, ref generic_parameters, Module)); }
}
#region MethodAttributes
public bool IsCompilerControlled
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.CompilerControlled); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.CompilerControlled, value); }
}
public bool IsPrivate
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Private); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Private, value); }
}
public bool IsFamilyAndAssembly
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamANDAssem); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamANDAssem, value); }
}
public bool IsAssembly
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Assembly); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Assembly, value); }
}
public bool IsFamily
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Family); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Family, value); }
}
public bool IsFamilyOrAssembly
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamORAssem); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.FamORAssem, value); }
}
public bool IsPublic
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Public); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.MemberAccessMask, (ushort)MethodAttributes.Public, value); }
}
public bool IsStatic
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Static); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Static, value); }
}
public bool IsFinal
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Final); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Final, value); }
}
public bool IsVirtual
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Virtual); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Virtual, value); }
}
public bool IsHideBySig
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.HideBySig); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.HideBySig, value); }
}
public bool IsReuseSlot
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.ReuseSlot); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.ReuseSlot, value); }
}
public bool IsNewSlot
{
get { return Mixin.GetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.NewSlot); }
set { attributes = Mixin.SetMaskedAttributes(attributes,(ushort)MethodAttributes.VtableLayoutMask, (ushort)MethodAttributes.NewSlot, value); }
}
public bool IsCheckAccessOnOverride
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.CheckAccessOnOverride); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.CheckAccessOnOverride, value); }
}
public bool IsAbstract
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.Abstract); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.Abstract, value); }
}
public bool IsSpecialName
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.SpecialName); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.SpecialName, value); }
}
public bool IsPInvokeImpl
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.PInvokeImpl); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.PInvokeImpl, value); }
}
public bool IsUnmanagedExport
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.UnmanagedExport); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.UnmanagedExport, value); }
}
public bool IsRuntimeSpecialName
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.RTSpecialName); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.RTSpecialName, value); }
}
public bool HasSecurity
{
get { return Mixin.GetAttributes(attributes,(ushort)MethodAttributes.HasSecurity); }
set { attributes =Mixin.SetAttributes(attributes,(ushort)MethodAttributes.HasSecurity, value); }
}
#endregion
#region MethodImplAttributes
public bool IsIL
{
get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.IL); }
set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.IL, value); }
}
public bool IsNative
{
get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Native); }
set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Native, value); }
}
public bool IsRuntime
{
get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Runtime); }
set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.CodeTypeMask, (ushort)MethodImplAttributes.Runtime, value); }
}
public bool IsUnmanaged
{
get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Unmanaged); }
set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Unmanaged, value); }
}
public bool IsManaged
{
get { return Mixin.GetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Managed); }
set { impl_attributes = Mixin.SetMaskedAttributes(impl_attributes,(ushort)MethodImplAttributes.ManagedMask, (ushort)MethodImplAttributes.Managed, value); }
}
public bool IsForwardRef
{
get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.ForwardRef); }
set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.ForwardRef, value); }
}
public bool IsPreserveSig
{
get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.PreserveSig); }
set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.PreserveSig, value); }
}
public bool IsInternalCall
{
get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.InternalCall); }
set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.InternalCall, value); }
}
public bool IsSynchronized
{
get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.Synchronized); }
set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.Synchronized, value); }
}
public bool NoInlining
{
get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.NoInlining); }
set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.NoInlining, value); }
}
public bool NoOptimization
{
get { return Mixin.GetAttributes(impl_attributes, (ushort)MethodImplAttributes.NoOptimization); }
set { impl_attributes = Mixin.SetAttributes(impl_attributes,(ushort)MethodImplAttributes.NoOptimization, value); }
}
#endregion
#region MethodSemanticsAttributes
public bool IsSetter
{
get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Setter); }
set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Setter, value); }
}
public bool IsGetter
{
get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Getter); }
set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Getter, value); }
}
public bool IsOther
{
get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Other); }
set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Other, value); }
}
public bool IsAddOn
{
get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.AddOn); }
set { Mixin.SetSemantics(this, MethodSemanticsAttributes.AddOn, value); }
}
public bool IsRemoveOn
{
get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.RemoveOn); }
set { Mixin.SetSemantics(this, MethodSemanticsAttributes.RemoveOn, value); }
}
public bool IsFire
{
get { return Mixin.GetSemantics(this, MethodSemanticsAttributes.Fire); }
set { Mixin.SetSemantics(this, MethodSemanticsAttributes.Fire, value); }
}
#endregion
public new TypeDefinition DeclaringType
{
get { return (TypeDefinition)base.DeclaringType; }
set { base.DeclaringType = value; }
}
public bool IsConstructor
{
get
{
return this.IsRuntimeSpecialName
&& this.IsSpecialName
&& (this.Name == ".cctor" || this.Name == ".ctor");
}
}
public override bool IsDefinition
{
get { return true; }
}
internal MethodDefinition()
{
this.token = new MetadataToken(TokenType.Method);
}
public MethodDefinition(string name, MethodAttributes attributes, TypeReference returnType)
: base(name, returnType)
{
this.attributes = (ushort)attributes;
this.HasThis = !this.IsStatic;
this.token = new MetadataToken(TokenType.Method);
}
public override MethodDefinition Resolve()
{
return this;
}
}
static partial class Mixin
{
public static ParameterDefinition GetParameter(MethodBody self, int index)
{
var method = self.method;
if (method.HasThis)
{
if (index == 0)
return self.ThisParameter;
index--;
}
var parameters = method.Parameters;
if (index < 0 || index >= parameters.size)
return null;
return parameters[index];
}
public static VariableDefinition GetVariable(MethodBody self, int index)
{
var variables = self.Variables;
if (index < 0 || index >= variables.size)
return null;
return variables[index];
}
public static bool GetSemantics(MethodDefinition self, MethodSemanticsAttributes semantics)
{
return (self.SemanticsAttributes & semantics) != 0;
}
public static void SetSemantics(MethodDefinition self, MethodSemanticsAttributes semantics, bool value)
{
if (value)
self.SemanticsAttributes |= semantics;
else
self.SemanticsAttributes &= ~semantics;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
namespace OpenSim.ApplicationPlugins.Rest.Inventory
{
public class RestAppearanceServices : IRest
{
// private static readonly int PARM_USERID = 0;
// private static readonly int PARM_PATH = 1;
private bool enabled = false;
private string qPrefix = "appearance";
/// <summary>
/// The constructor makes sure that the service prefix is absolute
/// and the registers the service handler and the allocator.
/// </summary>
public RestAppearanceServices()
{
Rest.Log.InfoFormat("{0} User appearance services initializing", MsgId);
Rest.Log.InfoFormat("{0} Using REST Implementation Version {1}", MsgId, Rest.Version);
// If a relative path was specified for the handler's domain,
// add the standard prefix to make it absolute, e.g. /admin
if (!qPrefix.StartsWith(Rest.UrlPathSeparator))
{
Rest.Log.InfoFormat("{0} Domain is relative, adding absolute prefix", MsgId);
qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix);
qPrefix = String.Format("{0}{1}{2}", Rest.Prefix, Rest.UrlPathSeparator, qPrefix);
Rest.Log.InfoFormat("{0} Domain is now <{1}>", MsgId, qPrefix);
}
// Register interface using the absolute URI.
Rest.Plugin.AddPathHandler(DoAppearance,qPrefix,Allocate);
// Activate if everything went OK
enabled = true;
Rest.Log.InfoFormat("{0} User appearance services initialization complete", MsgId);
}
/// <summary>
/// Post-construction, pre-enabled initialization opportunity
/// Not currently exploited.
/// </summary>
public void Initialize()
{
}
/// <summary>
/// Called by the plug-in to halt service processing. Local processing is
/// disabled.
/// </summary>
public void Close()
{
enabled = false;
Rest.Log.InfoFormat("{0} User appearance services closing down", MsgId);
}
/// <summary>
/// This property is declared locally because it is used a lot and
/// brevity is nice.
/// </summary>
internal string MsgId
{
get { return Rest.MsgId; }
}
#region Interface
/// <summary>
/// The plugin (RestHandler) calls this method to allocate the request
/// state carrier for a new request. It is destroyed when the request
/// completes. All request-instance specific state is kept here. This
/// is registered when this service provider is registered.
/// </summary>
/// <param name=request>Inbound HTTP request information</param>
/// <param name=response>Outbound HTTP request information</param>
/// <param name=qPrefix>REST service domain prefix</param>
/// <returns>A RequestData instance suitable for this service</returns>
private RequestData Allocate(OSHttpRequest request, OSHttpResponse response, string prefix)
{
return (RequestData) new AppearanceRequestData(request, response, prefix);
}
/// <summary>
/// This method is registered with the handler when this service provider
/// is initialized. It is called whenever the plug-in identifies this service
/// provider as the best match for a given request.
/// It handles all aspects of inventory REST processing, i.e. /admin/inventory
/// </summary>
/// <param name=hdata>A consolidated HTTP request work area</param>
private void DoAppearance(RequestData hdata)
{
// !!! REFACTORIMG PROBLEM. This needs rewriting for 0.7
//AppearanceRequestData rdata = (AppearanceRequestData) hdata;
//Rest.Log.DebugFormat("{0} DoAppearance ENTRY", MsgId);
//// If we're disabled, do nothing.
//if (!enabled)
//{
// return;
//}
//// Now that we know this is a serious attempt to
//// access inventory data, we should find out who
//// is asking, and make sure they are authorized
//// to do so. We need to validate the caller's
//// identity before revealing anything about the
//// status quo. Authenticate throws an exception
//// via Fail if no identity information is present.
////
//// With the present HTTP server we can't use the
//// builtin authentication mechanisms because they
//// would be enforced for all in-bound requests.
//// Instead we look at the headers ourselves and
//// handle authentication directly.
//try
//{
// if (!rdata.IsAuthenticated)
// {
// rdata.Fail(Rest.HttpStatusCodeNotAuthorized,String.Format("user \"{0}\" could not be authenticated", rdata.userName));
// }
//}
//catch (RestException e)
//{
// if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
// {
// Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// else
// {
// Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// throw (e);
//}
//Rest.Log.DebugFormat("{0} Authenticated {1}", MsgId, rdata.userName);
//// We can only get here if we are authorized
////
//// The requestor may have specified an UUID or
//// a conjoined FirstName LastName string. We'll
//// try both. If we fail with the first, UUID,
//// attempt, we try the other. As an example, the
//// URI for a valid inventory request might be:
////
//// http://<host>:<port>/admin/inventory/Arthur Dent
////
//// Indicating that this is an inventory request for
//// an avatar named Arthur Dent. This is ALL that is
//// required to designate a GET for an entire
//// inventory.
////
//// Do we have at least a user agent name?
//if (rdata.Parameters.Length < 1)
//{
// Rest.Log.WarnFormat("{0} Appearance: No user agent identifier specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "no user identity specified");
//}
//// The first parameter MUST be the agent identification, either an UUID
//// or a space-separated First-name Last-Name specification. We check for
//// an UUID first, if anyone names their character using a valid UUID
//// that identifies another existing avatar will cause this a problem...
//try
//{
// rdata.uuid = new UUID(rdata.Parameters[PARM_USERID]);
// Rest.Log.DebugFormat("{0} UUID supplied", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(rdata.uuid);
//}
//catch
//{
// string[] names = rdata.Parameters[PARM_USERID].Split(Rest.CA_SPACE);
// if (names.Length == 2)
// {
// Rest.Log.DebugFormat("{0} Agent Name supplied [2]", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(names[0],names[1]);
// }
// else
// {
// Rest.Log.WarnFormat("{0} A Valid UUID or both first and last names must be specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid user identity");
// }
//}
//// If the user profile is null then either the server is broken, or the
//// user is not known. We always assume the latter case.
//if (rdata.userProfile != null)
//{
// Rest.Log.DebugFormat("{0} User profile obtained for agent {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
//}
//else
//{
// Rest.Log.WarnFormat("{0} No user profile for {1}", MsgId, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeNotFound, "unrecognized user identity");
//}
//// If we get to here, then we have effectively validated the user's
//switch (rdata.method)
//{
// case Rest.HEAD : // Do the processing, set the status code, suppress entity
// DoGet(rdata);
// rdata.buffer = null;
// break;
// case Rest.GET : // Do the processing, set the status code, return entity
// DoGet(rdata);
// break;
// case Rest.PUT : // Update named element
// DoUpdate(rdata);
// break;
// case Rest.POST : // Add new information to identified context.
// DoExtend(rdata);
// break;
// case Rest.DELETE : // Delete information
// DoDelete(rdata);
// break;
// default :
// Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
// MsgId, rdata.method, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
// String.Format("{0} not supported", rdata.method));
// break;
//}
}
#endregion Interface
#region method-specific processing
/// <summary>
/// This method implements GET processing for user's appearance.
/// </summary>
/// <param name=rdata>HTTP service request work area</param>
// private void DoGet(AppearanceRequestData rdata)
// {
// AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID);
//
// if (adata == null)
// {
// rdata.Fail(Rest.HttpStatusCodeNoContent,
// String.Format("appearance data not found for user {0} {1}",
// rdata.userProfile.FirstName, rdata.userProfile.SurName));
// }
// rdata.userAppearance = adata.ToAvatarAppearance(rdata.userProfile.ID);
//
// rdata.initXmlWriter();
//
// FormatUserAppearance(rdata);
//
// // Indicate a successful request
//
// rdata.Complete();
//
// // Send the response to the user. The body will be implicitly
// // constructed from the result of the XML writer.
//
// rdata.Respond(String.Format("Appearance {0} Normal completion", rdata.method));
// }
/// <summary>
/// POST adds NEW information to the user profile database.
/// This effectively resets the appearance before applying those
/// characteristics supplied in the request.
/// </summary>
// private void DoExtend(AppearanceRequestData rdata)
// {
//
// bool created = false;
// bool modified = false;
// string newnode = String.Empty;
//
// Rest.Log.DebugFormat("{0} POST ENTRY", MsgId);
//
// //AvatarAppearance old = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
//
// rdata.userAppearance = new AvatarAppearance();
//
// // Although the following behavior is admitted by HTTP I am becoming
// // increasingly doubtful that it is appropriate for REST. If I attempt to
// // add a new record, and it already exists, then it seems to me that the
// // attempt should fail, rather than update the existing record.
// AvatarData adata = null;
// if (GetUserAppearance(rdata))
// {
// modified = rdata.userAppearance != null;
// created = !modified;
// adata = new AvatarData(rdata.userAppearance);
// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
// // Rest.UserServices.UpdateUserProfile(rdata.userProfile);
// }
// else
// {
// created = true;
// adata = new AvatarData(rdata.userAppearance);
// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
// // Rest.UserServices.UpdateUserProfile(rdata.userProfile);
// }
//
// if (created)
// {
// newnode = String.Format("{0} {1}", rdata.userProfile.FirstName,
// rdata.userProfile.SurName);
// // Must include a location header with a URI that identifies the new resource.
//
// rdata.AddHeader(Rest.HttpHeaderLocation,String.Format("http://{0}{1}:{2}{3}{4}",
// rdata.hostname,rdata.port,rdata.path,Rest.UrlPathSeparator, newnode));
// rdata.Complete(Rest.HttpStatusCodeCreated);
//
// }
// else
// {
// if (modified)
// {
// rdata.Complete(Rest.HttpStatusCodeOK);
// }
// else
// {
// rdata.Complete(Rest.HttpStatusCodeNoContent);
// }
// }
//
// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method));
//
// }
/// <summary>
/// This updates the user's appearance. not all aspects need to be provided,
/// only those supplied will be changed.
/// </summary>
// private void DoUpdate(AppearanceRequestData rdata)
// {
//
// // REFACTORING PROBLEM This was commented out. It doesn't work for 0.7
//
// //bool created = false;
// //bool modified = false;
//
//
// //rdata.userAppearance = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
//
// //// If the user exists then this is considered a modification regardless
// //// of what may, or may not be, specified in the payload.
//
// //if (rdata.userAppearance != null)
// //{
// // modified = true;
// // Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance);
// // Rest.UserServices.UpdateUserProfile(rdata.userProfile);
// //}
//
// //if (created)
// //{
// // rdata.Complete(Rest.HttpStatusCodeCreated);
// //}
// //else
// //{
// // if (modified)
// // {
// // rdata.Complete(Rest.HttpStatusCodeOK);
// // }
// // else
// // {
// // rdata.Complete(Rest.HttpStatusCodeNoContent);
// // }
// //}
//
// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method));
//
// }
/// <summary>
/// Delete the specified user's appearance. This actually performs a reset
/// to the default avatar appearance, if the info is already there.
/// Existing ownership is preserved. All prior updates are lost and can not
/// be recovered.
/// </summary>
// private void DoDelete(AppearanceRequestData rdata)
// {
// AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID);
//
// if (adata != null)
// {
// AvatarAppearance old = adata.ToAvatarAppearance(rdata.userProfile.ID);
// rdata.userAppearance = new AvatarAppearance();
// rdata.userAppearance.Owner = old.Owner;
// adata = new AvatarData(rdata.userAppearance);
//
// Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
//
// rdata.Complete();
// }
// else
// {
//
// rdata.Complete(Rest.HttpStatusCodeNoContent);
// }
//
// rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method));
// }
#endregion method-specific processing
private bool GetUserAppearance(AppearanceRequestData rdata)
{
XmlReader xml;
bool indata = false;
rdata.initXmlReader();
xml = rdata.reader;
while (xml.Read())
{
switch (xml.NodeType)
{
case XmlNodeType.Element :
switch (xml.Name)
{
case "Appearance" :
if (xml.MoveToAttribute("Height"))
{
rdata.userAppearance.AvatarHeight = (float) Convert.ToDouble(xml.Value);
indata = true;
}
if (xml.MoveToAttribute("Owner"))
{
rdata.userAppearance.Owner = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Serial"))
{
rdata.userAppearance.Serial = Convert.ToInt32(xml.Value);
indata = true;
}
break;
/*
case "Body" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.BodyItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.BodyAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Skin" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.SkinItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.SkinAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Hair" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.HairItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.HairAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Eyes" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.EyesItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.EyesAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Shirt" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.ShirtItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.ShirtAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Pants" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.PantsItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.PantsAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Shoes" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.ShoesItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.ShoesAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Socks" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.SocksItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.SocksAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Jacket" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.JacketItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.JacketAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Gloves" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.GlovesItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.GlovesAsset = (UUID)xml.Value;
indata = true;
}
break;
case "UnderShirt" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.UnderShirtItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.UnderShirtAsset = (UUID)xml.Value;
indata = true;
}
break;
case "UnderPants" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.UnderPantsItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.UnderPantsAsset = (UUID)xml.Value;
indata = true;
}
break;
case "Skirt" :
if (xml.MoveToAttribute("Item"))
{
rdata.userAppearance.SkirtItem = (UUID)xml.Value;
indata = true;
}
if (xml.MoveToAttribute("Asset"))
{
rdata.userAppearance.SkirtAsset = (UUID)xml.Value;
indata = true;
}
break;
*/
case "Attachment" :
{
int ap;
UUID asset;
UUID item;
if (xml.MoveToAttribute("AtPoint"))
{
ap = Convert.ToInt32(xml.Value);
if (xml.MoveToAttribute("Asset"))
{
asset = new UUID(xml.Value);
if (xml.MoveToAttribute("Asset"))
{
item = new UUID(xml.Value);
rdata.userAppearance.SetAttachment(ap, item, asset);
indata = true;
}
}
}
}
break;
case "Texture" :
if (xml.MoveToAttribute("Default"))
{
rdata.userAppearance.Texture = new Primitive.TextureEntry(new UUID(xml.Value));
indata = true;
}
break;
case "Face" :
{
uint index;
if (xml.MoveToAttribute("Index"))
{
index = Convert.ToUInt32(xml.Value);
if (xml.MoveToAttribute("Id"))
{
rdata.userAppearance.Texture.CreateFace(index).TextureID = new UUID(xml.Value);
indata = true;
}
}
}
break;
case "VisualParameters" :
{
xml.ReadContentAsBase64(rdata.userAppearance.VisualParams,
0, rdata.userAppearance.VisualParams.Length);
indata = true;
}
break;
}
break;
}
}
return indata;
}
private void FormatPart(AppearanceRequestData rdata, string part, UUID item, UUID asset)
{
if (item != UUID.Zero || asset != UUID.Zero)
{
rdata.writer.WriteStartElement(part);
if (item != UUID.Zero)
{
rdata.writer.WriteAttributeString("Item",item.ToString());
}
if (asset != UUID.Zero)
{
rdata.writer.WriteAttributeString("Asset",asset.ToString());
}
rdata.writer.WriteEndElement();
}
}
private void FormatUserAppearance(AppearanceRequestData rdata)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance", MsgId);
if (rdata.userAppearance != null)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: appearance object exists", MsgId);
rdata.writer.WriteStartElement("Appearance");
rdata.writer.WriteAttributeString("Height", rdata.userAppearance.AvatarHeight.ToString());
if (rdata.userAppearance.Owner != UUID.Zero)
rdata.writer.WriteAttributeString("Owner", rdata.userAppearance.Owner.ToString());
rdata.writer.WriteAttributeString("Serial", rdata.userAppearance.Serial.ToString());
/*
FormatPart(rdata, "Body", rdata.userAppearance.BodyItem, rdata.userAppearance.BodyAsset);
FormatPart(rdata, "Skin", rdata.userAppearance.SkinItem, rdata.userAppearance.SkinAsset);
FormatPart(rdata, "Hair", rdata.userAppearance.HairItem, rdata.userAppearance.HairAsset);
FormatPart(rdata, "Eyes", rdata.userAppearance.EyesItem, rdata.userAppearance.EyesAsset);
FormatPart(rdata, "Shirt", rdata.userAppearance.ShirtItem, rdata.userAppearance.ShirtAsset);
FormatPart(rdata, "Pants", rdata.userAppearance.PantsItem, rdata.userAppearance.PantsAsset);
FormatPart(rdata, "Skirt", rdata.userAppearance.SkirtItem, rdata.userAppearance.SkirtAsset);
FormatPart(rdata, "Shoes", rdata.userAppearance.ShoesItem, rdata.userAppearance.ShoesAsset);
FormatPart(rdata, "Socks", rdata.userAppearance.SocksItem, rdata.userAppearance.SocksAsset);
FormatPart(rdata, "Jacket", rdata.userAppearance.JacketItem, rdata.userAppearance.JacketAsset);
FormatPart(rdata, "Gloves", rdata.userAppearance.GlovesItem, rdata.userAppearance.GlovesAsset);
FormatPart(rdata, "UnderShirt", rdata.userAppearance.UnderShirtItem, rdata.userAppearance.UnderShirtAsset);
FormatPart(rdata, "UnderPants", rdata.userAppearance.UnderPantsItem, rdata.userAppearance.UnderPantsAsset);
*/
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting attachments", MsgId);
rdata.writer.WriteStartElement("Attachments");
List<AvatarAttachment> attachments = rdata.userAppearance.GetAttachments();
foreach (AvatarAttachment attach in attachments)
{
rdata.writer.WriteStartElement("Attachment");
rdata.writer.WriteAttributeString("AtPoint", attach.AttachPoint.ToString());
rdata.writer.WriteAttributeString("Item", attach.ItemID.ToString());
rdata.writer.WriteAttributeString("Asset", attach.AssetID.ToString());
rdata.writer.WriteEndElement();
}
rdata.writer.WriteEndElement();
Primitive.TextureEntry texture = rdata.userAppearance.Texture;
if (texture != null && (texture.DefaultTexture != null || texture.FaceTextures != null))
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting textures", MsgId);
rdata.writer.WriteStartElement("Texture");
if (texture.DefaultTexture != null)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting default texture", MsgId);
rdata.writer.WriteAttributeString("Default",
texture.DefaultTexture.TextureID.ToString());
}
if (texture.FaceTextures != null)
{
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting face textures", MsgId);
for (int i=0; i<texture.FaceTextures.Length;i++)
{
if (texture.FaceTextures[i] != null)
{
rdata.writer.WriteStartElement("Face");
rdata.writer.WriteAttributeString("Index", i.ToString());
rdata.writer.WriteAttributeString("Id",
texture.FaceTextures[i].TextureID.ToString());
rdata.writer.WriteEndElement();
}
}
}
rdata.writer.WriteEndElement();
}
Rest.Log.DebugFormat("{0} FormatUserAppearance: Formatting visual parameters", MsgId);
rdata.writer.WriteStartElement("VisualParameters");
rdata.writer.WriteBase64(rdata.userAppearance.VisualParams,0,
rdata.userAppearance.VisualParams.Length);
rdata.writer.WriteEndElement();
rdata.writer.WriteFullEndElement();
}
Rest.Log.DebugFormat("{0} FormatUserAppearance: completed", MsgId);
return;
}
#region appearance RequestData extension
internal class AppearanceRequestData : RequestData
{
/// <summary>
/// These are the inventory specific request/response state
/// extensions.
/// </summary>
internal UUID uuid = UUID.Zero;
internal UserProfileData userProfile = null;
internal AvatarAppearance userAppearance = null;
internal AppearanceRequestData(OSHttpRequest request, OSHttpResponse response, string prefix)
: base(request, response, prefix)
{
}
}
#endregion Appearance RequestData extension
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute.Models
{
/// <summary>
/// Describes a Border Gateway Protocol Peering.
/// </summary>
public partial class AzureBgpPeering
{
private string _advertisedCommunities;
/// <summary>
/// Optional. Specifies the communities that will be advertised by the
/// peer over this BGP peering. Specific to Microsoft type of peering.
/// </summary>
public string AdvertisedCommunities
{
get { return this._advertisedCommunities; }
set { this._advertisedCommunities = value; }
}
private string _advertisedCommunitiesIpv6;
/// <summary>
/// Optional. Specifies the communities that will be advertised by the
/// Ipv6 peer over this BGP peering. Specific to Microsoft type of
/// peering.
/// </summary>
public string AdvertisedCommunitiesIpv6
{
get { return this._advertisedCommunitiesIpv6; }
set { this._advertisedCommunitiesIpv6 = value; }
}
private string _advertisedPublicPrefixes;
/// <summary>
/// Optional. Specifies the public prefixes that will be advertised by
/// the peer over this BGP peering. Specific to Microsoft type of
/// peering.
/// </summary>
public string AdvertisedPublicPrefixes
{
get { return this._advertisedPublicPrefixes; }
set { this._advertisedPublicPrefixes = value; }
}
private string _advertisedPublicPrefixesIpv6;
/// <summary>
/// Optional. Specifies the public prefixes that will be advertised by
/// the Ipv6 peer over this BGP peering. Specific to Microsoft type of
/// peering.
/// </summary>
public string AdvertisedPublicPrefixesIpv6
{
get { return this._advertisedPublicPrefixesIpv6; }
set { this._advertisedPublicPrefixesIpv6 = value; }
}
private string _advertisedPublicPrefixesState;
/// <summary>
/// Optional. Specifies whether the Azure network has been configured
/// to accept the public prefixes specified as will be advertised by
/// the peer over this BGP peering. Specific to Mirosoft type of
/// peering.
/// </summary>
public string AdvertisedPublicPrefixesState
{
get { return this._advertisedPublicPrefixesState; }
set { this._advertisedPublicPrefixesState = value; }
}
private string _advertisedPublicPrefixesStateIpv6;
/// <summary>
/// Optional. Specifies whether the Azure network has been configured
/// to accept the Ipv6 public prefixes specified as will be advertised
/// by the peer over this BGP peering. Specific to Mirosoft type of
/// peering.
/// </summary>
public string AdvertisedPublicPrefixesStateIpv6
{
get { return this._advertisedPublicPrefixesStateIpv6; }
set { this._advertisedPublicPrefixesStateIpv6 = value; }
}
private uint _azureAsn;
/// <summary>
/// Optional. Specifies the numeric identifier of the public autonomous
/// system (AS) in which the device of Windows Azure is configured.
/// </summary>
public uint AzureAsn
{
get { return this._azureAsn; }
set { this._azureAsn = value; }
}
private uint _customerAutonomousSystemNumber;
/// <summary>
/// Optional. Specifies the numeric identifier of the public autonomous
/// system (AS) in which the device of the customer is configured.
/// </summary>
public uint CustomerAutonomousSystemNumber
{
get { return this._customerAutonomousSystemNumber; }
set { this._customerAutonomousSystemNumber = value; }
}
private uint _customerAutonomousSystemNumberIpv6;
/// <summary>
/// Optional. Specifies the numeric identifier of the public autonomous
/// system (AS) in which the device of the customer is configured for
/// Ipv6.
/// </summary>
public uint CustomerAutonomousSystemNumberIpv6
{
get { return this._customerAutonomousSystemNumberIpv6; }
set { this._customerAutonomousSystemNumberIpv6 = value; }
}
private uint _legacyMode;
/// <summary>
/// Optional. Specifies the legacy mode. Specific to Microsoft type of
/// peering.
/// </summary>
public uint LegacyMode
{
get { return this._legacyMode; }
set { this._legacyMode = value; }
}
private uint _peerAsn;
/// <summary>
/// Optional. Specifies the numeric identifier of the public autonomous
/// system (AS) in which the device of the service provider is
/// configured.
/// </summary>
public uint PeerAsn
{
get { return this._peerAsn; }
set { this._peerAsn = value; }
}
private string _primaryAzurePort;
/// <summary>
/// Optional. Specifies the name of the primary port.
/// </summary>
public string PrimaryAzurePort
{
get { return this._primaryAzurePort; }
set { this._primaryAzurePort = value; }
}
private string _primaryPeerSubnet;
/// <summary>
/// Optional. Specifies the subnet addresses of the interface to be
/// used for establishing the BGP session on the primary port.
/// </summary>
public string PrimaryPeerSubnet
{
get { return this._primaryPeerSubnet; }
set { this._primaryPeerSubnet = value; }
}
private string _primaryPeerSubnetIpv6;
/// <summary>
/// Optional. Specifies the subnet addresses of the interface to be
/// used for establishing the Ipv6 BGP session on the primary port.
/// </summary>
public string PrimaryPeerSubnetIpv6
{
get { return this._primaryPeerSubnetIpv6; }
set { this._primaryPeerSubnetIpv6 = value; }
}
private string _routingRegistryName;
/// <summary>
/// Optional. Specifies the Routing Registry to look up to validate the
/// prefixes specified in AdvertisedPublicPrefixes
/// </summary>
public string RoutingRegistryName
{
get { return this._routingRegistryName; }
set { this._routingRegistryName = value; }
}
private string _routingRegistryNameIpv6;
/// <summary>
/// Optional. Specifies the Routing Registry to look up to validate the
/// prefixes specified in AdvertisedPublicPrefixesIpv6
/// </summary>
public string RoutingRegistryNameIpv6
{
get { return this._routingRegistryNameIpv6; }
set { this._routingRegistryNameIpv6 = value; }
}
private string _secondaryAzurePort;
/// <summary>
/// Optional. Specifies the name of the secondary port.
/// </summary>
public string SecondaryAzurePort
{
get { return this._secondaryAzurePort; }
set { this._secondaryAzurePort = value; }
}
private string _secondaryPeerSubnet;
/// <summary>
/// Optional. Specifies the subnet addresses of the interface to be
/// used for establishing the BGP session on the secondary port.
/// </summary>
public string SecondaryPeerSubnet
{
get { return this._secondaryPeerSubnet; }
set { this._secondaryPeerSubnet = value; }
}
private string _secondaryPeerSubnetIpv6;
/// <summary>
/// Optional. Specifies the subnet addresses of the interface to be
/// used for establishing the Ipv6 BGP session on the secondary port.
/// </summary>
public string SecondaryPeerSubnetIpv6
{
get { return this._secondaryPeerSubnetIpv6; }
set { this._secondaryPeerSubnetIpv6 = value; }
}
private BgpPeeringState _state;
/// <summary>
/// Optional. The current state of the BGP session. Possible values are
/// Disabled, Enabled.
/// </summary>
public BgpPeeringState State
{
get { return this._state; }
set { this._state = value; }
}
private BgpPeeringState _stateIpv6;
/// <summary>
/// Optional. The current state of the Ipv6 BGP session. Possible
/// values are Disabled, Enabled.
/// </summary>
public BgpPeeringState StateIpv6
{
get { return this._stateIpv6; }
set { this._stateIpv6 = value; }
}
private uint _vlanId;
/// <summary>
/// Optional. Specifies the identifier that is used to identify the
/// customer.
/// </summary>
public uint VlanId
{
get { return this._vlanId; }
set { this._vlanId = value; }
}
/// <summary>
/// Initializes a new instance of the AzureBgpPeering class.
/// </summary>
public AzureBgpPeering()
{
}
}
}
| |
namespace Mikepenz.Typeface
{
using System;
using System.Collections.Generic;
using System.Linq;
using Android.Util;
using Mikepenz.Iconics.Typeface;
public class Meteoconcs : Java.Lang.Object, ITypeface
{
const string TtfFile = "meteocons.ttf";
static Android.Graphics.Typeface _typeface = null;
static Dictionary<string, Java.Lang.Character> _chars;
public IIcon GetIcon(string key)
{
return Icon.Values.ToList().Find(icon => icon.Name.Equals(key));
}
public IDictionary<string, Java.Lang.Character> Characters {
get {
return _chars ?? (_chars = Icon.Values.ToDictionary(icon => icon.Name, icon => new Java.Lang.Character(icon.Character)));
}
}
public string MappingPrefix {
get {
return "met";
}
}
public string FontName {
get {
return "Meteocons";
}
}
public string Version {
get {
return "1.1.1";
}
}
public int IconCount {
get {
return _chars.Count;
}
}
public ICollection<string> Icons {
get {
return Icon.Values.Select(icon => icon.Name).ToList();
}
}
public string Author {
get {
return "Alessio Atzeni";
}
}
public string Url {
get {
return "http://www.alessioatzeni.com/meteocons/";
}
}
public string Description {
get {
return "Meteocons is a set of weather icons, it containing 40+ icons available in PSD, CSH, EPS, SVG, Desktop font and Web font. All icon and updates are free and always will be.";
}
}
public string License {
get {
return "";
}
}
public string LicenseUrl {
get {
return "";
}
}
public Android.Graphics.Typeface GetTypeface(Android.Content.Context context)
{
if(_typeface == null) {
try {
_typeface = Android.Graphics.Typeface.CreateFromAsset(context.Assets, "fonts/" + TtfFile);
} catch(Exception e) {
var message = string.Format("Failed to load font file : {0} for {1} typeface. Reason: {2}", TtfFile, FontName, e.Message);
Log.Error("Iconics", message);
}
}
return _typeface;
}
public class Icon : Java.Lang.Object, IIcon
{
readonly char character;
readonly string name;
static ITypeface _typeFace;
public Icon(char character, string name)
{
this.character = character;
this.name = name;
}
public char Character {
get {
return this.character;
}
}
public string FormattedName {
get {
return "{" + this.name + "}";
}
}
public string Name {
get {
return this.name;
}
}
public ITypeface Typeface {
get {
return _typeFace ?? (_typeFace = new Meteoconcs());
}
}
public static readonly Icon MetWindyRainInv = new Icon('\ue800', "met_windy_rain_inv");
public static readonly Icon MetSnowInv = new Icon('\ue801', "met_snow_inv");
public static readonly Icon MetSnowHeavyInv = new Icon('\ue802', "met_snow_heavy_inv");
public static readonly Icon MetHailInv = new Icon('\ue803', "met_hail_inv");
public static readonly Icon MetCloudsInv = new Icon('\ue804', "met_clouds_inv");
public static readonly Icon MetCloudsFlashInv = new Icon('\ue805', "met_clouds_flash_inv");
public static readonly Icon MetTemperature = new Icon('\ue806', "met_temperature");
public static readonly Icon MetCompass = new Icon('\ue807', "met_compass");
public static readonly Icon MetNa = new Icon('\ue808', "met_na");
public static readonly Icon MetCelcius = new Icon('\ue809', "met_celcius");
public static readonly Icon MetFahrenheit = new Icon('\ue80a', "met_fahrenheit");
public static readonly Icon MetCloudsFlashAlt = new Icon('\ue80b', "met_clouds_flash_alt");
public static readonly Icon MetSunInv = new Icon('\ue80c', "met_sun_inv");
public static readonly Icon MetMoonInv = new Icon('\ue80d', "met_moon_inv");
public static readonly Icon MetCloudSunInv = new Icon('\ue80e', "met_cloud_sun_inv");
public static readonly Icon MetCloudMoonInv = new Icon('\ue80f', "met_cloud_moon_inv");
public static readonly Icon MetCloudInv = new Icon('\ue810', "met_cloud_inv");
public static readonly Icon MetCloudFlashInv = new Icon('\ue811', "met_cloud_flash_inv");
public static readonly Icon MetDrizzleInv = new Icon('\ue812', "met_drizzle_inv");
public static readonly Icon MetRainInv = new Icon('\ue813', "met_rain_inv");
public static readonly Icon MetWindyInv = new Icon('\ue814', "met_windy_inv");
public static readonly Icon MetSunrise = new Icon('\ue815', "met_sunrise");
public static readonly Icon MetSun = new Icon('\ue816', "met_sun");
public static readonly Icon MetMoon = new Icon('\ue817', "met_moon");
public static readonly Icon MetEclipse = new Icon('\ue818', "met_eclipse");
public static readonly Icon MetMist = new Icon('\ue819', "met_mist");
public static readonly Icon MetWind = new Icon('\ue81a', "met_wind");
public static readonly Icon MetSnowflake = new Icon('\ue81b', "met_snowflake");
public static readonly Icon MetCloudSun = new Icon('\ue81c', "met_cloud_sun");
public static readonly Icon MetCloudMoon = new Icon('\ue81d', "met_cloud_moon");
public static readonly Icon MetFogSun = new Icon('\ue81e', "met_fog_sun");
public static readonly Icon MetFogMoon = new Icon('\ue81f', "met_fog_moon");
public static readonly Icon MetFogCloud = new Icon('\ue820', "met_fog_cloud");
public static readonly Icon MetFog = new Icon('\ue821', "met_fog");
public static readonly Icon MetCloud = new Icon('\ue822', "met_cloud");
public static readonly Icon MetCloudFlash = new Icon('\ue823', "met_cloud_flash");
public static readonly Icon MetCloudFlashAlt = new Icon('\ue824', "met_cloud_flash_alt");
public static readonly Icon MetDrizzle = new Icon('\ue825', "met_drizzle");
public static readonly Icon MetRain = new Icon('\ue826', "met_rain");
public static readonly Icon MetWindy = new Icon('\ue827', "met_windy");
public static readonly Icon MetWindyRain = new Icon('\ue828', "met_windy_rain");
public static readonly Icon MetSnow = new Icon('\ue829', "met_snow");
public static readonly Icon MetSnowAlt = new Icon('\ue82a', "met_snow_alt");
public static readonly Icon MetSnowHeavy = new Icon('\ue82b', "met_snow_heavy");
public static readonly Icon MetHail = new Icon('\ue82c', "met_hail");
public static readonly Icon MetClouds = new Icon('\ue82d', "met_clouds");
public static readonly Icon MetCloudsFlash = new Icon('\ue82e', "met_clouds_flash");
public static IEnumerable<Icon> Values {
get {
yield return MetWindyRainInv;
yield return MetSnowInv;
yield return MetSnowHeavyInv;
yield return MetHailInv;
yield return MetCloudsInv;
yield return MetCloudsFlashInv;
yield return MetTemperature;
yield return MetCompass;
yield return MetNa;
yield return MetCelcius;
yield return MetFahrenheit;
yield return MetCloudsFlashAlt;
yield return MetSunInv;
yield return MetMoonInv;
yield return MetCloudSunInv;
yield return MetCloudMoonInv;
yield return MetCloudInv;
yield return MetCloudFlashInv;
yield return MetDrizzleInv;
yield return MetRainInv;
yield return MetWindyInv;
yield return MetSunrise;
yield return MetSun;
yield return MetMoon;
yield return MetEclipse;
yield return MetMist;
yield return MetWind;
yield return MetSnowflake;
yield return MetCloudSun;
yield return MetCloudMoon;
yield return MetFogSun;
yield return MetFogMoon;
yield return MetFogCloud;
yield return MetFog;
yield return MetCloud;
yield return MetCloudFlash;
yield return MetCloudFlashAlt;
yield return MetDrizzle;
yield return MetRain;
yield return MetWindy;
yield return MetWindyRain;
yield return MetSnow;
yield return MetSnowAlt;
yield return MetSnowHeavy;
yield return MetHail;
yield return MetClouds;
yield return MetCloudsFlash;
}
}
}
}
}
| |
/*
* 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.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using log4net;
using OpenMetaverse;
using Nini.Config;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
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.Api
{
[Serializable]
public class MOD_Api : MarshalByRefObject, IMOD_Api, IScriptApi
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
internal IScriptEngine m_ScriptEngine;
internal SceneObjectPart m_host;
internal TaskInventoryItem m_item;
internal bool m_MODFunctionsEnabled = false;
internal IScriptModuleComms m_comms = null;
public void Initialize(
IScriptEngine scriptEngine, SceneObjectPart host, TaskInventoryItem item, WaitHandle coopSleepHandle)
{
m_ScriptEngine = scriptEngine;
m_host = host;
m_item = item;
if (m_ScriptEngine.Config.GetBoolean("AllowMODFunctions", false))
m_MODFunctionsEnabled = true;
m_comms = m_ScriptEngine.World.RequestModuleInterface<IScriptModuleComms>();
if (m_comms == null)
m_MODFunctionsEnabled = false;
}
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
public Scene World
{
get { return m_ScriptEngine.World; }
}
internal void MODError(string msg)
{
throw new ScriptException("MOD Runtime Error: " + msg);
}
/// <summary>
/// Dumps an error message on the debug console.
/// </summary>
/// <param name='message'></param>
internal void MODShoutError(string message)
{
if (message.Length > 1023)
message = message.Substring(0, 1023);
World.SimChat(
Utils.StringToBytes(message),
ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL,
m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, false);
IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message);
}
/// <summary>
///
/// </summary>
/// <param name="fname">The name of the function to invoke</param>
/// <param name="parms">List of parameters</param>
/// <returns>string result of the invocation</returns>
public void modInvokeN(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(string))
MODError(String.Format("return type mismatch for {0}",fname));
modInvoke(fname,parms);
}
public LSL_String modInvokeS(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(string))
MODError(String.Format("return type mismatch for {0}",fname));
string result = (string)modInvoke(fname,parms);
return new LSL_String(result);
}
public LSL_Integer modInvokeI(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(int))
MODError(String.Format("return type mismatch for {0}",fname));
int result = (int)modInvoke(fname,parms);
return new LSL_Integer(result);
}
public LSL_Float modInvokeF(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(float))
MODError(String.Format("return type mismatch for {0}",fname));
float result = (float)modInvoke(fname,parms);
return new LSL_Float(result);
}
public LSL_Key modInvokeK(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(UUID))
MODError(String.Format("return type mismatch for {0}",fname));
UUID result = (UUID)modInvoke(fname,parms);
return new LSL_Key(result.ToString());
}
public LSL_Vector modInvokeV(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(OpenMetaverse.Vector3))
MODError(String.Format("return type mismatch for {0}",fname));
OpenMetaverse.Vector3 result = (OpenMetaverse.Vector3)modInvoke(fname,parms);
return new LSL_Vector(result.X,result.Y,result.Z);
}
public LSL_Rotation modInvokeR(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(OpenMetaverse.Quaternion))
MODError(String.Format("return type mismatch for {0}",fname));
OpenMetaverse.Quaternion result = (OpenMetaverse.Quaternion)modInvoke(fname,parms);
return new LSL_Rotation(result.X,result.Y,result.Z,result.W);
}
public LSL_List modInvokeL(string fname, params object[] parms)
{
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type returntype = m_comms.LookupReturnType(fname);
if (returntype != typeof(object[]))
MODError(String.Format("return type mismatch for {0}",fname));
object[] result = (object[])modInvoke(fname,parms);
object[] llist = new object[result.Length];
for (int i = 0; i < result.Length; i++)
{
if (result[i] is string)
{
llist[i] = new LSL_String((string)result[i]);
}
else if (result[i] is int)
{
llist[i] = new LSL_Integer((int)result[i]);
}
else if (result[i] is float)
{
llist[i] = new LSL_Float((float)result[i]);
}
else if (result[i] is double)
{
llist[i] = new LSL_Float((double)result[i]);
}
else if (result[i] is UUID)
{
llist[i] = new LSL_Key(result[i].ToString());
}
else if (result[i] is OpenMetaverse.Vector3)
{
OpenMetaverse.Vector3 vresult = (OpenMetaverse.Vector3)result[i];
llist[i] = new LSL_Vector(vresult.X, vresult.Y, vresult.Z);
}
else if (result[i] is OpenMetaverse.Quaternion)
{
OpenMetaverse.Quaternion qresult = (OpenMetaverse.Quaternion)result[i];
llist[i] = new LSL_Rotation(qresult.X, qresult.Y, qresult.Z, qresult.W);
}
else
{
MODError(String.Format("unknown list element {1} returned by {0}", fname, result[i].GetType().Name));
}
}
return new LSL_List(llist);
}
/// <summary>
/// Invokes a preregistered function through the ScriptModuleComms class
/// </summary>
/// <param name="fname">The name of the function to invoke</param>
/// <param name="fname">List of parameters</param>
/// <returns>string result of the invocation</returns>
protected object modInvoke(string fname, params object[] parms)
{
if (!m_MODFunctionsEnabled)
{
MODShoutError("Module command functions not enabled");
return "";
}
// m_log.DebugFormat(
// "[MOD API]: Invoking dynamic function {0}, args '{1}' with {2} return type",
// fname,
// string.Join(",", Array.ConvertAll<object, string>(parms, o => o.ToString())),
// ((MethodInfo)MethodBase.GetCurrentMethod()).ReturnType);
Type[] signature = m_comms.LookupTypeSignature(fname);
if (signature.Length != parms.Length)
MODError(String.Format("wrong number of parameters to function {0}",fname));
object[] convertedParms = new object[parms.Length];
for (int i = 0; i < parms.Length; i++)
convertedParms[i] = ConvertFromLSL(parms[i], signature[i], fname);
// now call the function, the contract with the function is that it will always return
// non-null but don't trust it completely
try
{
object result = m_comms.InvokeOperation(m_host.UUID, m_item.ItemID, fname, convertedParms);
if (result != null)
return result;
MODError(String.Format("Invocation of {0} failed; null return value",fname));
}
catch (Exception e)
{
MODError(String.Format("Invocation of {0} failed; {1}",fname,e.Message));
}
return null;
}
/// <summary>
/// Send a command to functions registered on an event
/// </summary>
public string modSendCommand(string module, string command, string k)
{
if (!m_MODFunctionsEnabled)
{
MODShoutError("Module command functions not enabled");
return UUID.Zero.ToString();;
}
UUID req = UUID.Random();
m_comms.RaiseEvent(m_item.ItemID, req.ToString(), module, command, k);
return req.ToString();
}
/// <summary>
/// </summary>
protected object ConvertFromLSL(object lslparm, Type type, string fname)
{
// ---------- String ----------
if (lslparm is LSL_String)
{
if (type == typeof(string))
return (string)(LSL_String)lslparm;
// Need to check for UUID since keys are often treated as strings
if (type == typeof(UUID))
return new UUID((string)(LSL_String)lslparm);
}
// ---------- Integer ----------
else if (lslparm is LSL_Integer)
{
if (type == typeof(int) || type == typeof(float))
return (int)(LSL_Integer)lslparm;
}
// ---------- Float ----------
else if (lslparm is LSL_Float)
{
if (type == typeof(float))
return (float)(LSL_Float)lslparm;
}
// ---------- Key ----------
else if (lslparm is LSL_Key)
{
if (type == typeof(UUID))
return new UUID((LSL_Key)lslparm);
}
// ---------- Rotation ----------
else if (lslparm is LSL_Rotation)
{
if (type == typeof(OpenMetaverse.Quaternion))
{
return (OpenMetaverse.Quaternion)((LSL_Rotation)lslparm);
}
}
// ---------- Vector ----------
else if (lslparm is LSL_Vector)
{
if (type == typeof(OpenMetaverse.Vector3))
{
return (OpenMetaverse.Vector3)((LSL_Vector)lslparm);
}
}
// ---------- List ----------
else if (lslparm is LSL_List)
{
if (type == typeof(object[]))
{
object[] plist = (lslparm as LSL_List).Data;
object[] result = new object[plist.Length];
for (int i = 0; i < plist.Length; i++)
{
if (plist[i] is LSL_String)
result[i] = (string)(LSL_String)plist[i];
else if (plist[i] is LSL_Integer)
result[i] = (int)(LSL_Integer)plist[i];
// The int check exists because of the many plain old int script constants in ScriptBase which
// are not LSL_Integers.
else if (plist[i] is int)
result[i] = plist[i];
else if (plist[i] is LSL_Float)
result[i] = (float)(LSL_Float)plist[i];
else if (plist[i] is LSL_Key)
result[i] = new UUID((LSL_Key)plist[i]);
else if (plist[i] is LSL_Rotation)
result[i] = (Quaternion)((LSL_Rotation)plist[i]);
else if (plist[i] is LSL_Vector)
result[i] = (Vector3)((LSL_Vector)plist[i]);
else
MODError(String.Format("{0}: unknown LSL list element type", fname));
}
return result;
}
}
MODError(String.Format("{0}: parameter type mismatch; expecting {1}, type(parm)={2}", fname, type.Name, lslparm.GetType()));
return null;
}
}
}
| |
namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using NUnit.Framework;
using System;
using System.IO;
/// <summary>
/// Tests from https://github.com/html5lib/html5lib-tests:
/// tree-construction/tricky01.dat
/// </summary>
[TestFixture]
public class TrickyTests
{
[Test]
public void BoldAndNotBold()
{
var doc = (@"<b><p>Bold </b> Not bold</p>
Also not bold.").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(3, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var dochtmlbodyb = dochtmlbody.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodyb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodyb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyb.NodeType);
var dochtmlbodyp = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbodyp.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyp.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyp.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyp.NodeType);
var dochtmlbodypb = dochtmlbodyp.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodypb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodypb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodypb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypb.NodeType);
var text1 = dochtmlbodypb.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual("Bold ", text1.TextContent);
var text2 = dochtmlbodyp.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual(" Not bold", text2.TextContent);
var text3 = dochtmlbody.ChildNodes[2];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual("\nAlso not bold.", text3.TextContent);
}
[Test]
public void ItalicAndOrRed()
{
var doc = (@"<html>
<font color=red><i>Italic and Red<p>Italic and Red </font> Just italic.</p> Italic only.</i> Plain
<p>I should not be red. <font color=red>Red. <i>Italic and red.</p>
<p>Italic and red. </i> Red.</font> I should not be red.</p>
<b>Bold <i>Bold and italic</b> Only Italic </i> Plain").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(10, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var dochtmlbodyfont1 = dochtmlbody.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodyfont1.ChildNodes.Length);
Assert.AreEqual(1, dochtmlbodyfont1.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyfont1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfont1.NodeType);
Assert.AreEqual("red", dochtmlbodyfont1.Attributes.GetNamedItem("color").Value);
var dochtmlbodyfonti1 = dochtmlbodyfont1.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodyfonti1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfonti1.Attributes.Length);
Assert.AreEqual("i", dochtmlbodyfonti1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfonti1.NodeType);
var text1 = dochtmlbodyfonti1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual(@"Italic and Red", text1.TextContent);
var dochtmlbodyi1 = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbodyi1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyi1.Attributes.Length);
Assert.AreEqual("i", dochtmlbodyi1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyi1.NodeType);
var dochtmlbodyip = dochtmlbodyi1.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtmlbodyip.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyip.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyip.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyip.NodeType);
var dochtmlbodyipfont = dochtmlbodyip.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodyipfont.ChildNodes.Length);
Assert.AreEqual(1, dochtmlbodyipfont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyipfont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyipfont.NodeType);
Assert.AreEqual("red", dochtmlbodyipfont.Attributes.GetNamedItem("color").Value);
var text2 = dochtmlbodyipfont.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual(@"Italic and Red ", text2.TextContent);
var dochtmlbodyfont2 = dochtmlbody.ChildNodes[4] as Element;
Assert.AreEqual(1, dochtmlbodyfont2.ChildNodes.Length);
Assert.AreEqual(1, dochtmlbodyfont2.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyfont2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfont2.NodeType);
Assert.AreEqual("red", dochtmlbodyfont2.Attributes.GetNamedItem("color").Value);
var dochtmlbodyfonti2 = dochtmlbodyfont2.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodyfonti2.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfonti2.Attributes.Length);
Assert.AreEqual("i", dochtmlbodyfonti2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfonti2.NodeType);
var text3 = dochtmlbodyfonti2.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual("\n", text3.TextContent);
var dochtmlbodyp = dochtmlbody.ChildNodes[5] as Element;
Assert.AreEqual(2, dochtmlbodyp.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyp.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyp.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyp.NodeType);
var dochtmlbodypfont = dochtmlbodyp.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtmlbodypfont.ChildNodes.Length);
Assert.AreEqual(1, dochtmlbodypfont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodypfont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypfont.NodeType);
Assert.AreEqual("red", dochtmlbodypfont.Attributes.GetNamedItem("color").Value);
var dochtmlbodypfonti = dochtmlbodypfont.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodypfonti.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodypfonti.Attributes.Length);
Assert.AreEqual("i", dochtmlbodypfonti.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypfonti.NodeType);
var text4 = dochtmlbodypfonti.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text4.NodeType);
Assert.AreEqual(@"Italic and red. ", text4.TextContent);
var text5 = dochtmlbodypfont.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text5.NodeType);
Assert.AreEqual(@" Red.", text5.TextContent);
var text6 = dochtmlbodyp.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text6.NodeType);
Assert.AreEqual(@" I should not be red.", text6.TextContent);
var text7 = dochtmlbody.ChildNodes[6];
Assert.AreEqual(NodeType.Text, text7.NodeType);
Assert.AreEqual("\n", text7.TextContent);
var dochtmlbodyb = dochtmlbody.ChildNodes[7] as Element;
Assert.AreEqual(2, dochtmlbodyb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodyb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyb.NodeType);
var text8 = dochtmlbodyb.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text8.NodeType);
Assert.AreEqual(@"Bold ", text8.TextContent);
var dochtmlbodybi = dochtmlbodyb.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodybi.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodybi.Attributes.Length);
Assert.AreEqual("i", dochtmlbodybi.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodybi.NodeType);
var text9 = dochtmlbodybi.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text9.NodeType);
Assert.AreEqual(@"Bold and italic", text9.TextContent);
var dochtmlbodyi3 = dochtmlbody.ChildNodes[8] as Element;
Assert.AreEqual(1, dochtmlbodyi3.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyi3.Attributes.Length);
Assert.AreEqual("i", dochtmlbodyi3.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyi3.NodeType);
var text10 = dochtmlbodyi3.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text10.NodeType);
Assert.AreEqual(@" Only Italic ", text10.TextContent);
var text11 = dochtmlbody.ChildNodes[9];
Assert.AreEqual(NodeType.Text, text11.NodeType);
Assert.AreEqual(@" Plain", text11.TextContent);
}
[Test]
public void FormattingParagraphs()
{
var doc = (@"<html><body>
<p><font size=""7"">First paragraph.</p>
<p>Second paragraph.</p></font>
<b><p><i>Bold and Italic</b> Italic</p>").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(6, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var text1 = dochtmlbody.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual("\n", text1.TextContent);
var dochtmlbodyp1 = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodyp1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyp1.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyp1.NodeType);
var dochtmlbodypfont = dochtmlbodyp1.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodypfont.ChildNodes.Length);
Assert.AreEqual(1, dochtmlbodypfont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodypfont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypfont.NodeType);
Assert.AreEqual("7", dochtmlbodypfont.Attributes.GetNamedItem("size").Value);
var text2 = dochtmlbodypfont.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual(@"First paragraph.", text2.TextContent);
var dochtmlbodyfont = dochtmlbody.ChildNodes[2] as Element;
Assert.AreEqual(2, dochtmlbodyfont.ChildNodes.Length);
Assert.AreEqual(1, dochtmlbodyfont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyfont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfont.NodeType);
Assert.AreEqual("7", dochtmlbodyfont.Attributes.GetNamedItem("size").Value);
var text3 = dochtmlbodyfont.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual("\n", text3.TextContent);
var dochtmlbodyfontp = dochtmlbodyfont.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodyfontp.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfontp.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyfontp.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfontp.NodeType);
var text4 = dochtmlbodyfontp.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text4.NodeType);
Assert.AreEqual(@"Second paragraph.", text4.TextContent);
var text5 = dochtmlbody.ChildNodes[3];
Assert.AreEqual(NodeType.Text, text5.NodeType);
Assert.AreEqual("\n", text5.TextContent);
var dochtmlbodyb = dochtmlbody.ChildNodes[4] as Element;
Assert.AreEqual(0, dochtmlbodyb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodyb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyb.NodeType);
var dochtmlbodyp2 = dochtmlbody.ChildNodes[5] as Element;
Assert.AreEqual(2, dochtmlbodyp2.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyp2.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyp2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyp2.NodeType);
var dochtmlbodypb = dochtmlbodyp2.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodypb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodypb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodypb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypb.NodeType);
var dochtmlbodypbi = dochtmlbodypb.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodypbi.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodypbi.Attributes.Length);
Assert.AreEqual("i", dochtmlbodypbi.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypbi.NodeType);
var text6 = dochtmlbodypbi.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text6.NodeType);
Assert.AreEqual(@"Bold and Italic", text6.TextContent);
var dochtmlbodypi = dochtmlbodyp2.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodypi.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodypi.Attributes.Length);
Assert.AreEqual("i", dochtmlbodypi.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypi.NodeType);
var text7 = dochtmlbodypi.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text7.NodeType);
Assert.AreEqual(@" Italic", text7.TextContent);
}
[Test]
public void DefinitionListWithFormatting()
{
var doc = (@"<html>
<dl>
<dt><b>Boo
<dd>Goo?
</dl>
</html>").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var dochtmlbodydl = dochtmlbody.ChildNodes[0] as Element;
Assert.AreEqual(3, dochtmlbodydl.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydl.Attributes.Length);
Assert.AreEqual("dl", dochtmlbodydl.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydl.NodeType);
var text1 = dochtmlbodydl.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual("\n", text1.TextContent);
var dochtmlbodydldt = dochtmlbodydl.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodydldt.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydldt.Attributes.Length);
Assert.AreEqual("dt", dochtmlbodydldt.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydldt.NodeType);
var dochtmlbodydldtb = dochtmlbodydldt.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodydldtb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydldtb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodydldtb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydldtb.NodeType);
var text2 = dochtmlbodydldtb.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual("Boo\n", text2.TextContent);
var dochtmlbodydldd = dochtmlbodydl.ChildNodes[2] as Element;
Assert.AreEqual(1, dochtmlbodydldd.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydldd.Attributes.Length);
Assert.AreEqual("dd", dochtmlbodydldd.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydldd.NodeType);
var dochtmlbodydlddb = dochtmlbodydldd.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodydlddb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydlddb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodydlddb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydlddb.NodeType);
var text3 = dochtmlbodydlddb.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual("Goo?\n", text3.TextContent);
var dochtmlbodyb = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodyb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodyb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyb.NodeType);
var text4 = dochtmlbodyb.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text4.NodeType);
Assert.AreEqual("\n", text4.TextContent);
}
[Test]
public void HelloWorldWithSomeDivs()
{
var doc = (@"<html><body>
<label><a><div>Hello<div>World</div></a></label>
</body></html>").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var text1 = dochtmlbody.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual("\n", text1.TextContent);
var dochtmlbodylabel = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbodylabel.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodylabel.Attributes.Length);
Assert.AreEqual("label", dochtmlbodylabel.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodylabel.NodeType);
var dochtmlbodylabela = dochtmlbodylabel.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodylabela.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodylabela.Attributes.Length);
Assert.AreEqual("a", dochtmlbodylabela.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodylabela.NodeType);
var dochtmlbodylabeldiv = dochtmlbodylabel.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbodylabeldiv.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodylabeldiv.Attributes.Length);
Assert.AreEqual("div", dochtmlbodylabeldiv.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodylabeldiv.NodeType);
var dochtmlbodylabeldiva = dochtmlbodylabeldiv.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtmlbodylabeldiva.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodylabeldiva.Attributes.Length);
Assert.AreEqual("a", dochtmlbodylabeldiva.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodylabeldiva.NodeType);
var text2 = dochtmlbodylabeldiva.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual(@"Hello", text2.TextContent);
var dochtmlbodylabeldivadiv = dochtmlbodylabeldiva.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodylabeldivadiv.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodylabeldivadiv.Attributes.Length);
Assert.AreEqual("div", dochtmlbodylabeldivadiv.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodylabeldivadiv.NodeType);
var text3 = dochtmlbodylabeldivadiv.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual(@"World", text3.TextContent);
var text4 = dochtmlbodylabeldiv.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text4.NodeType);
Assert.AreEqual(" \n", text4.TextContent);
}
[Test]
public void TableFormattingGoneWild()
{
var doc = (@"<table><center> <font>a</center> <img> <tr><td> </td> </tr> </table>").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(3, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var dochtmlbodycenter = dochtmlbody.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtmlbodycenter.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodycenter.Attributes.Length);
Assert.AreEqual("center", dochtmlbodycenter.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodycenter.NodeType);
var text1 = dochtmlbodycenter.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual(@" ", text1.TextContent);
var dochtmlbodycenterfont = dochtmlbodycenter.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodycenterfont.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodycenterfont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodycenterfont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodycenterfont.NodeType);
var text2 = dochtmlbodycenterfont.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual(@"a", text2.TextContent);
var dochtmlbodyfont = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbodyfont.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyfont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfont.NodeType);
var dochtmlbodyfontimg = dochtmlbodyfont.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodyfontimg.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfontimg.Attributes.Length);
Assert.AreEqual("img", dochtmlbodyfontimg.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfontimg.NodeType);
var text3 = dochtmlbodyfont.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual(@" ", text3.TextContent);
var dochtmlbodytable = dochtmlbody.ChildNodes[2] as Element;
Assert.AreEqual(2, dochtmlbodytable.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytable.Attributes.Length);
Assert.AreEqual("table", dochtmlbodytable.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytable.NodeType);
var text4 = dochtmlbodytable.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text4.NodeType);
Assert.AreEqual(@" ", text4.TextContent);
var dochtmlbodytabletbody = dochtmlbodytable.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbodytabletbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbody.Attributes.Length);
Assert.AreEqual("tbody", dochtmlbodytabletbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbody.NodeType);
var dochtmlbodytabletbodytr = dochtmlbodytabletbody.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtmlbodytabletbodytr.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbodytr.Attributes.Length);
Assert.AreEqual("tr", dochtmlbodytabletbodytr.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbodytr.NodeType);
var dochtmlbodytabletbodytrtd = dochtmlbodytabletbodytr.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodytabletbodytrtd.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbodytrtd.Attributes.Length);
Assert.AreEqual("td", dochtmlbodytabletbodytrtd.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbodytrtd.NodeType);
var text5 = dochtmlbodytabletbodytrtd.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text5.NodeType);
Assert.AreEqual(@" ", text5.TextContent);
var text6 = dochtmlbodytabletbodytr.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text6.NodeType);
Assert.AreEqual(@" ", text6.TextContent);
var text7 = dochtmlbodytabletbody.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text7.NodeType);
Assert.AreEqual(@" ", text7.TextContent);
}
[Test]
public void YouShouldSeeThisText()
{
var doc = (@"<table><tr><p><a><p>You should see this text.").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(3, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var dochtmlbodyp1 = dochtmlbody.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodyp1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyp1.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyp1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyp1.NodeType);
var dochtmlbodypa1 = dochtmlbodyp1.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodypa1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodypa1.Attributes.Length);
Assert.AreEqual("a", dochtmlbodypa1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypa1.NodeType);
var dochtmlbodyp2 = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodyp2.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyp2.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyp2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyp2.NodeType);
var dochtmlbodypa2 = dochtmlbodyp2.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodypa2.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodypa2.Attributes.Length);
Assert.AreEqual("a", dochtmlbodypa2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodypa2.NodeType);
var text1 = dochtmlbodypa2.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual(@"You should see this text.", text1.TextContent);
var dochtmlbodytable = dochtmlbody.ChildNodes[2] as Element;
Assert.AreEqual(1, dochtmlbodytable.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytable.Attributes.Length);
Assert.AreEqual("table", dochtmlbodytable.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytable.NodeType);
var dochtmlbodytabletbody = dochtmlbodytable.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodytabletbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbody.Attributes.Length);
Assert.AreEqual("tbody", dochtmlbodytabletbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbody.NodeType);
var dochtmlbodytabletbodytr = dochtmlbodytabletbody.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodytabletbodytr.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbodytr.Attributes.Length);
Assert.AreEqual("tr", dochtmlbodytabletbodytr.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbodytr.NodeType);
}
[Test]
public void InsanelyBadlyNestedTagSequence()
{
var doc = (@"<TABLE>
<TR>
<CENTER><CENTER><TD></TD></TR><TR>
<FONT>
<TABLE><tr></tr></TABLE>
</P>
<a></font><font></a>
This page contains an insanely badly-nested tag sequence.").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(7, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var dochtmlbodycenter = dochtmlbody.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodycenter.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodycenter.Attributes.Length);
Assert.AreEqual("center", dochtmlbodycenter.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodycenter.NodeType);
var dochtmlbodycentercenter = dochtmlbodycenter.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodycentercenter.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodycentercenter.Attributes.Length);
Assert.AreEqual("center", dochtmlbodycentercenter.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodycentercenter.NodeType);
var dochtmlbodyfont = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodyfont.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyfont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfont.NodeType);
var text1 = dochtmlbodyfont.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual("\n", text1.TextContent);
var dochtmlbodytable = dochtmlbody.ChildNodes[2] as Element;
Assert.AreEqual(2, dochtmlbodytable.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytable.Attributes.Length);
Assert.AreEqual("table", dochtmlbodytable.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytable.NodeType);
var text2 = dochtmlbodytable.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual("\n", text2.TextContent);
var dochtmlbodytabletbody1 = dochtmlbodytable.ChildNodes[1] as Element;
Assert.AreEqual(2, dochtmlbodytabletbody1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbody1.Attributes.Length);
Assert.AreEqual("tbody", dochtmlbodytabletbody1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbody1.NodeType);
var dochtmlbodytabletbodytr1 = dochtmlbodytabletbody1.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtmlbodytabletbodytr1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbodytr1.Attributes.Length);
Assert.AreEqual("tr", dochtmlbodytabletbodytr1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbodytr1.NodeType);
var text3 = dochtmlbodytabletbodytr1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual("\n", text3.TextContent);
var dochtmlbodytabletbodytrtd = dochtmlbodytabletbodytr1.ChildNodes[1] as Element;
Assert.AreEqual(0, dochtmlbodytabletbodytrtd.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbodytrtd.Attributes.Length);
Assert.AreEqual("td", dochtmlbodytabletbodytrtd.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbodytrtd.NodeType);
var dochtmlbodytabletbodytr2 = dochtmlbodytabletbody1.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodytabletbodytr2.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbodytr2.Attributes.Length);
Assert.AreEqual("tr", dochtmlbodytabletbodytr2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbodytr2.NodeType);
var text4 = dochtmlbodytabletbodytr2.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text4.NodeType);
Assert.AreEqual("\n", text4.TextContent);
var dochtmlbodytable2 = dochtmlbody.ChildNodes[3] as Element;
Assert.AreEqual(1, dochtmlbodytable2.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytable2.Attributes.Length);
Assert.AreEqual("table", dochtmlbodytable2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytable2.NodeType);
var dochtmlbodytabletbody = dochtmlbodytable2.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodytabletbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbody.Attributes.Length);
Assert.AreEqual("tbody", dochtmlbodytabletbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbody.NodeType);
var dochtmlbodytabletbodytr = dochtmlbodytabletbody.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodytabletbodytr.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodytabletbodytr.Attributes.Length);
Assert.AreEqual("tr", dochtmlbodytabletbodytr.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodytabletbodytr.NodeType);
var dochtmlbodyfont1 = dochtmlbody.ChildNodes[4] as Element;
Assert.AreEqual(4, dochtmlbodyfont1.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfont1.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyfont1.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfont1.NodeType);
var text5 = dochtmlbodyfont1.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text5.NodeType);
Assert.AreEqual("\n", text5.TextContent);
var dochtmlbodyfontp = dochtmlbodyfont1.ChildNodes[1] as Element;
Assert.AreEqual(0, dochtmlbodyfontp.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfontp.Attributes.Length);
Assert.AreEqual("p", dochtmlbodyfontp.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfontp.NodeType);
var text6 = dochtmlbodyfont1.ChildNodes[2];
Assert.AreEqual(NodeType.Text, text6.NodeType);
Assert.AreEqual("\n", text6.TextContent);
var dochtmlbodyfonta = dochtmlbodyfont1.ChildNodes[3] as Element;
Assert.AreEqual(0, dochtmlbodyfonta.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfonta.Attributes.Length);
Assert.AreEqual("a", dochtmlbodyfonta.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfonta.NodeType);
var dochtmlbodya = dochtmlbody.ChildNodes[5] as Element;
Assert.AreEqual(1, dochtmlbodya.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodya.Attributes.Length);
Assert.AreEqual("a", dochtmlbodya.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodya.NodeType);
var dochtmlbodyafont = dochtmlbodya.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodyafont.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyafont.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyafont.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyafont.NodeType);
var dochtmlbodyfont2 = dochtmlbody.ChildNodes[6] as Element;
Assert.AreEqual(1, dochtmlbodyfont2.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyfont2.Attributes.Length);
Assert.AreEqual("font", dochtmlbodyfont2.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyfont2.NodeType);
var text7 = dochtmlbodyfont2.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text7.NodeType);
Assert.AreEqual("\nThis page contains an insanely badly-nested tag sequence.", text7.TextContent);
}
[Test]
public void ImplicitlyClosingDivs()
{
var doc = (@"<html>
<body>
<b><nobr><div>This text is in a div inside a nobr</nobr>More text that should not be in the nobr, i.e., the
nobr should have closed the div inside it implicitly. </b><pre>A pre tag outside everything else.</pre>
</body>
</html>").ToHtmlDocument();
var dochtml = doc.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtml.ChildNodes.Length);
Assert.AreEqual(0, dochtml.Attributes.Length);
Assert.AreEqual("html", dochtml.GetTagName());
Assert.AreEqual(NodeType.Element, dochtml.NodeType);
var dochtmlhead = dochtml.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlhead.ChildNodes.Length);
Assert.AreEqual(0, dochtmlhead.Attributes.Length);
Assert.AreEqual("head", dochtmlhead.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlhead.NodeType);
var dochtmlbody = dochtml.ChildNodes[1] as Element;
Assert.AreEqual(3, dochtmlbody.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbody.Attributes.Length);
Assert.AreEqual("body", dochtmlbody.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbody.NodeType);
var text1 = dochtmlbody.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text1.NodeType);
Assert.AreEqual("\n", text1.TextContent);
var dochtmlbodyb = dochtmlbody.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodyb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodyb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodyb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodyb.NodeType);
var dochtmlbodybnobr = dochtmlbodyb.ChildNodes[0] as Element;
Assert.AreEqual(0, dochtmlbodybnobr.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodybnobr.Attributes.Length);
Assert.AreEqual("nobr", dochtmlbodybnobr.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodybnobr.NodeType);
var dochtmlbodydiv = dochtmlbody.ChildNodes[2] as Element;
Assert.AreEqual(3, dochtmlbodydiv.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydiv.Attributes.Length);
Assert.AreEqual("div", dochtmlbodydiv.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydiv.NodeType);
var dochtmlbodydivb = dochtmlbodydiv.ChildNodes[0] as Element;
Assert.AreEqual(2, dochtmlbodydivb.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydivb.Attributes.Length);
Assert.AreEqual("b", dochtmlbodydivb.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydivb.NodeType);
var dochtmlbodydivbnobr = dochtmlbodydivb.ChildNodes[0] as Element;
Assert.AreEqual(1, dochtmlbodydivbnobr.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydivbnobr.Attributes.Length);
Assert.AreEqual("nobr", dochtmlbodydivbnobr.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydivbnobr.NodeType);
var text2 = dochtmlbodydivbnobr.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text2.NodeType);
Assert.AreEqual(@"This text is in a div inside a nobr", text2.TextContent);
var text3 = dochtmlbodydivb.ChildNodes[1];
Assert.AreEqual(NodeType.Text, text3.NodeType);
Assert.AreEqual("More text that should not be in the nobr, i.e., the\nnobr should have closed the div inside it implicitly. ", text3.TextContent);
var dochtmlbodydivpre = dochtmlbodydiv.ChildNodes[1] as Element;
Assert.AreEqual(1, dochtmlbodydivpre.ChildNodes.Length);
Assert.AreEqual(0, dochtmlbodydivpre.Attributes.Length);
Assert.AreEqual("pre", dochtmlbodydivpre.GetTagName());
Assert.AreEqual(NodeType.Element, dochtmlbodydivpre.NodeType);
var text4 = dochtmlbodydivpre.ChildNodes[0];
Assert.AreEqual(NodeType.Text, text4.NodeType);
Assert.AreEqual(@"A pre tag outside everything else.", text4.TextContent);
var text5 = dochtmlbodydiv.ChildNodes[2];
Assert.AreEqual(NodeType.Text, text5.NodeType);
Assert.AreEqual("\n\n", text5.TextContent);
}
[Test]
public void HtmlDomConsturctionFromBytesOnlyZerosLeadsToInfiniteLoop()
{
var bs = new Byte[5509];
using (var memoryStream = new MemoryStream(bs, false))
{
var document = memoryStream.ToHtmlDocument();
Assert.IsNotNull(document);
}
}
[Test]
public void SvgDoctypeWithIncompleteTemplateTagShouldNotPopEmptyStack_Issue735()
{
var source = @"<svg><!DOCTYPE html><<template>html><desc><template>><p>p</p></body></html>";
var document = source.ToHtmlDocument();
Assert.IsNotNull(document);
Assert.AreEqual("<html><head></head><body><svg><<template>html><desc><template>><p>p</p></template></desc></template></svg></body></html>", document.ToHtml());
}
[Test]
public void SvgDoctypeWithDoubleTemplateTagShouldNotPopEmptyStack_Issue735()
{
var source = @"<svg><!DOCTYPE html><html><template><desc><template>><p>p</p></body></html>";
var document = source.ToHtmlDocument();
Assert.IsNotNull(document);
Assert.AreEqual("<html><head></head><body><svg><html><template><desc><template>><p>p</p></template></desc></template></html></svg></body></html>", document.ToHtml());
}
[Test]
public void SvgDoctypeWithMultiOpenTemplateTagShouldNotPopEmptyStack_Issue735()
{
var source = @"<svg><!DOCTYPE html><<<template>tml><desc><template>><p>p</p></body></html>";
var document = source.ToHtmlDocument();
Assert.IsNotNull(document);
Assert.AreEqual("<html><head></head><body><svg><<<template>tml><desc><template>><p>p</p></template></desc></template></svg></body></html>", document.ToHtml());
}
[Test]
public void SvgDoctypeWithFramesetAndDoubleTemplateShouldNotPopEmptyStack_Issue735()
{
var source = @"<svg><!DOCTYPE html><<frameset>h<template>tml><desc><template>><p>p</p></body></html>";
var document = source.ToHtmlDocument();
Assert.IsNotNull(document);
Assert.AreEqual("<html><head></head><body><svg><<frameset>h<template>tml><desc><template>><p>p</p></template></desc></template></frameset></svg></body></html>", document.ToHtml());
}
[Test]
public void SvgDoctypeWithDoubleTemplateAndPreShouldNotPopEmptyStack_Issue735()
{
var source = @"<svg><!DOCTYPE html><template>>html><desc><template>><p>p</p></body></html><pre>";
var document = source.ToHtmlDocument();
Assert.IsNotNull(document);
Assert.AreEqual("<html><head></head><body><svg><template>>html><desc><template>><p>p</p><pre></pre></template></desc></template></svg></body></html>", document.ToHtml());
}
[Test]
public void HeisenbergAlgorithmShouldNotBeOutOfBounds_Issue893()
{
var content = Assets.GetManifestResourceString("Html.Heisenberg.Bug.txt");
var document = content.ToHtmlDocument();
Assert.IsNotNull(document);
}
[Test]
public void AttributeValuesWithAmpersandAndUnderscoreAreOkay_Issue902()
{
var document = new HtmlParser(new HtmlParserOptions
{
IsScripting = false,
IsStrictMode = true,
IsEmbedded = false
}).ParseDocument("<!DOCTYPE html><a href=\"https://test.de/?foo&_\"></a>");
Assert.IsNotNull(document);
}
}
}
| |
// --------------------------------------------------------------------------------------------
#region // Copyright (c) 2014, SIL International.
// <copyright from='2003' to='2014' company='SIL International'>
// Copyright (c) 2014, SIL International.
//
// Distributable under the terms of the MIT License (http://sil.mit-license.org/)
// </copyright>
#endregion
//
// This class originated in FieldWorks (under the GNU Lesser General Public License), but we
// have decided to make it avaialble in SIL.ScriptureUtils as part of Palaso so it will be more
// readily available to other projects.
// --------------------------------------------------------------------------------------------
using System;
using NUnit.Framework;
using Rhino.Mocks;
namespace SIL.Scripture.Tests
{
#region BCVRefTests
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Tests for the BCVRef class
/// </summary>
/// ----------------------------------------------------------------------------------------
[TestFixture]
public class BCVRefTests
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Setup test
/// </summary>
/// ------------------------------------------------------------------------------------
[SetUp]
public void Setup()
{
BCVRef.SupportDeuterocanon = false;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test the constructors of BCVRef
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ValidBCVRefs()
{
BCVRef bcvRef = new BCVRef(1, 2, 3, 0);
Assert.IsTrue(bcvRef.Valid);
Assert.AreEqual(1002003, bcvRef);
Assert.AreEqual(1, bcvRef.Book);
Assert.AreEqual(2, bcvRef.Chapter);
Assert.AreEqual(3, bcvRef.Verse);
bcvRef = new BCVRef(4005006);
Assert.IsTrue(bcvRef.Valid);
Assert.AreEqual(4005006, bcvRef);
Assert.AreEqual(4, bcvRef.Book);
Assert.AreEqual(5, bcvRef.Chapter);
Assert.AreEqual(6, bcvRef.Verse);
bcvRef = new BCVRef();
Assert.IsFalse(bcvRef.Valid);
Assert.AreEqual(0, bcvRef);
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(0, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Verse);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test IsValidInVersification
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void IsValidInVersification()
{
var versification = MockRepository.GenerateMock<IScrVers>();
versification.Stub(v => v.GetLastChapter(65)).Return(1);
versification.Stub(v => v.GetLastVerse(65, 1)).Return(20);
Assert.IsTrue((new BCVRef(65, 1, 1)).IsValidInVersification(versification));
Assert.IsTrue((new BCVRef(65, 1, 20)).IsValidInVersification(versification));
Assert.IsFalse((new BCVRef(65, 99, 1)).IsValidInVersification(versification));
Assert.IsFalse((new BCVRef(65, 1, 21)).IsValidInVersification(versification));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test building a BCVRef by setting individual properties.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void BuildBcvRefByProps()
{
// Build a bcvRef by individual properties
BCVRef bcvRef = new BCVRef();
bcvRef.Book = 13;
Assert.IsFalse(bcvRef.Valid); // 0 not allowed for chapter
Assert.AreEqual(13000000, bcvRef.BBCCCVVV);
Assert.AreEqual(13, bcvRef.Book);
Assert.AreEqual(0, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Verse);
bcvRef.Chapter = 1;
// a zero verse is considered valid for introduction, etc, but only for chapter 1
Assert.IsTrue(bcvRef.Valid);
Assert.AreEqual(13001000, (int)bcvRef);
Assert.AreEqual(13, bcvRef.Book);
Assert.AreEqual(1, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Verse);
bcvRef.Chapter = 14;
bcvRef.Verse = 15;
Assert.IsTrue(bcvRef.Valid);
Assert.AreEqual(13014015, (int)bcvRef);
Assert.AreEqual(13, bcvRef.Book);
Assert.AreEqual(14, bcvRef.Chapter);
Assert.AreEqual(15, bcvRef.Verse);
bcvRef = new BCVRef();
bcvRef.Chapter = 16;
Assert.IsFalse(bcvRef.Valid, "Invalid because 0 is not valid for the book number");
Assert.AreEqual(00016000, (int)bcvRef);
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(16, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Verse);
bcvRef = new BCVRef();
bcvRef.Verse = 17;
Assert.IsFalse(bcvRef.Valid, "Invalid because 0 is not valid for the book and chapter numbers");
Assert.AreEqual(00000017, (int)bcvRef);
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(0, bcvRef.Chapter);
Assert.AreEqual(17, bcvRef.Verse);
// same tests as above except that we test individual properties first
// the BCVRef object operates differently in this circumstance
bcvRef = new BCVRef();
bcvRef.Book = 21;
Assert.AreEqual(0, bcvRef.Verse);
Assert.AreEqual(0, bcvRef.Chapter);
Assert.AreEqual(21, bcvRef.Book);
Assert.AreEqual(21000000, (int)bcvRef);
Assert.IsFalse(bcvRef.Valid, "Invalid because 0 is not valid for the chapter number");
bcvRef = new BCVRef();
bcvRef.Chapter = 22;
Assert.AreEqual(0, bcvRef.Verse);
Assert.AreEqual(22, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(00022000, (int)bcvRef);
Assert.IsFalse(bcvRef.Valid, "Invalid because 0 is not valid for the book number");
bcvRef = new BCVRef();
bcvRef.Verse = 23;
Assert.AreEqual(23, bcvRef.Verse);
Assert.AreEqual(0, bcvRef.Chapter);
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(00000023, (int)bcvRef);
Assert.IsFalse(bcvRef.Valid, "Invalid because 0 is not valid for the book and chapter numbers");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test updating the Book, Chapter and Verse of a BCVRef that is created and converted
/// using the implicit operators.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void UpdateBcvRef()
{
// Test updating book
BCVRef bcvRef = new BCVRef(1001001);
bcvRef.Book = 2;
int encodedBCV = bcvRef;
Assert.AreEqual(2001001, encodedBCV);
// Test updating chapter
bcvRef = new BCVRef(1001001);
bcvRef.Chapter = 2;
encodedBCV = bcvRef;
Assert.AreEqual(1002001, encodedBCV);
// Test updating verse
bcvRef = new BCVRef(1001001);
bcvRef.Verse = 2;
encodedBCV = bcvRef;
Assert.AreEqual(1001002, encodedBCV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_Valid()
{
BCVRef reference = new BCVRef("Gen 1:1");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(01001001, reference.BBCCCVVV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_ValidNoSpace()
{
BCVRef reference = new BCVRef("GEN1:1");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(01001001, reference.BBCCCVVV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_ValidExtraSpace()
{
BCVRef reference = new BCVRef("GEN 1 : 1");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(01001001, reference.BBCCCVVV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_OnlyChapter()
{
BCVRef reference = new BCVRef("EXO 1");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(02001001, reference.BBCCCVVV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_OnlyBook()
{
BCVRef reference = new BCVRef("LEV");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(03001001, reference.BBCCCVVV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests that verses or verse bridges can be given without an explicit chapter number
/// for any of the 5 single-chapter books (Obadiah, Philemon, 2 John, 3 John, Jude).
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_ChapterOptionalForSingleChapterBooks()
{
BCVRef reference = new BCVRef("OBA 2");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(31001002, reference.BBCCCVVV);
BCVRef start = new BCVRef();
BCVRef end = new BCVRef();
BCVRef.ParseRefRange("PHM 23-25", ref start, ref end);
Assert.IsTrue(start.Valid);
Assert.IsTrue(end.Valid);
Assert.AreEqual(57001023, start.BBCCCVVV);
Assert.AreEqual(57001025, end.BBCCCVVV);
reference = new BCVRef("2JN 8");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(63001008, reference.BBCCCVVV);
BCVRef.ParseRefRange("3JN 12-15", ref start, ref end, false);
Assert.IsTrue(start.Valid);
Assert.IsTrue(end.Valid);
Assert.AreEqual(64001012, start.BBCCCVVV);
Assert.AreEqual(64001015, end.BBCCCVVV);
BCVRef.ParseRefRange("JUD 10-24", ref start, ref end, false);
Assert.IsTrue(start.Valid);
Assert.IsTrue(end.Valid);
Assert.AreEqual(65001010, start.BBCCCVVV);
Assert.AreEqual(65001024, end.BBCCCVVV);
// Test to make sure non-single chapter book doesn't get away with any funny business!
reference = new BCVRef("EXO 3-4");
Assert.IsTrue(reference.Valid);
// May not seem right or logical, but BCVRef doesn't hard-code a particular chapter-verse separator character.
Assert.AreEqual(02003004, reference.BBCCCVVV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_Bridge()
{
BCVRef reference = new BCVRef("NUM 5:1-5");
Assert.IsFalse(reference.Valid);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_Intro()
{
BCVRef reference = new BCVRef("JOS 1:0");
Assert.IsTrue(reference.Valid);
Assert.AreEqual(06001000, reference.BBCCCVVV);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_IntroInvalid()
{
BCVRef reference = new BCVRef("JOS 2:0");
Assert.IsFalse(reference.Valid, "Verse cannot be 0 except in chapter 1.");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the overload of the constructor that takes a reference string
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefString_InvalidBook()
{
BCVRef reference = new BCVRef("BLA 1:1");
Assert.IsFalse(reference.Valid);
}
///--------------------------------------------------------------------------------------
/// <summary>
/// Tests the < operator
/// </summary>
///--------------------------------------------------------------------------------------
[Test]
public void Less()
{
Assert.IsTrue(new BCVRef(1, 1, 1) < new BCVRef(2, 1, 1));
Assert.IsFalse(new BCVRef(10, 1, 1) < new BCVRef(1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) < new BCVRef(1, 1, 1, 2));
Assert.IsTrue(new BCVRef(1, 1, 1) < new BCVRef(1, 1, 1, 1));
Assert.IsFalse(new BCVRef(1, 1, 1, 1) < new BCVRef(1, 1, 1));
}
///--------------------------------------------------------------------------------------
/// <summary>
/// Tests the <= operator
/// </summary>
///--------------------------------------------------------------------------------------
[Test]
public void LessOrEqual()
{
Assert.IsTrue(new BCVRef(1, 1, 1) <= new BCVRef(2, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1) <= new BCVRef(1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) <= new BCVRef(1, 1, 1, 2));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) <= new BCVRef(1, 1, 1, 1));
Assert.IsFalse(new BCVRef(10, 1, 1) <= new BCVRef(1, 1, 1));
}
///--------------------------------------------------------------------------------------
/// <summary>
/// Tests the > operator
/// </summary>
///--------------------------------------------------------------------------------------
[Test]
public void Greater()
{
Assert.IsTrue(new BCVRef(2, 1, 1) > new BCVRef(1, 1, 1));
Assert.IsFalse(new BCVRef(1, 1, 1) > new BCVRef(10, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 2) > new BCVRef(1, 1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) > new BCVRef(1, 1, 1));
Assert.IsFalse(new BCVRef(1, 1, 1) > new BCVRef(1, 1, 1, 1));
}
///--------------------------------------------------------------------------------------
/// <summary>
/// Tests the >= operator
/// </summary>
///--------------------------------------------------------------------------------------
[Test]
public void GreaterOrEqual()
{
Assert.IsTrue(new BCVRef(2, 1, 1) >= new BCVRef(1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1) >= new BCVRef(1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 2) >= new BCVRef(1, 1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) >= new BCVRef(1, 1, 1, 1));
Assert.IsFalse(new BCVRef(1, 1, 1) >= new BCVRef(10, 1, 1));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the == operator
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void Equal()
{
Assert.IsTrue(new BCVRef(1, 1, 1) == new BCVRef(1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) == new BCVRef(1, 1, 1, 1));
Assert.IsFalse(new BCVRef(1, 1, 1, 1) == new BCVRef(1, 1, 1, 2));
Assert.IsFalse(new BCVRef(1, 1, 1, 1) == new BCVRef(1, 1, 1));
Assert.IsTrue(01001001 == new BCVRef(1, 1, 1));
Assert.IsFalse(01001001 == new BCVRef(1, 1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1) == 01001001);
Assert.IsFalse(new BCVRef(1, 1, 1, 1) == 01001001);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the != operator
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void NotEqual()
{
Assert.IsFalse(new BCVRef(1, 1, 1) != new BCVRef(1, 1, 1));
Assert.IsFalse(new BCVRef(1, 1, 1, 1) != new BCVRef(1, 1, 1, 1));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) != new BCVRef(1, 1, 1, 2));
Assert.IsTrue(new BCVRef(1, 1, 1, 1) != new BCVRef(1, 1, 1));
Assert.IsFalse(01001001 != new BCVRef(1, 1, 1));
Assert.IsTrue(01001001 != new BCVRef(1, 1, 1, 1));
Assert.IsFalse(new BCVRef(1, 1, 1) != 01001001);
Assert.IsTrue(new BCVRef(1, 1, 1, 1) != 01001001);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests that passing in invalid verse numbers doesn't cause an overflow in the chapter
/// number in the BCV ref.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void Invalid()
{
BCVRef scrRef = new BCVRef(6542, 1023, 5051);
Assert.IsFalse(scrRef.Valid);
Assert.AreEqual(42023051, scrRef);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Test the MakeReferenceString() method.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void MakeReferenceString()
{
// The first test passes chap./vrs. separator and bridge characters that we know
// would never be hardcoded in order to make sure those characters are not hardcoded.
Assert.AreEqual("MAT 5#7", BCVRef.MakeReferenceString(new BCVRef(40, 5, 7),
new BCVRef(40, 5, 7), "#", "!"));
Assert.AreEqual("MAT 5:7-9", BCVRef.MakeReferenceString(
new BCVRef(40, 5, 7), new BCVRef(40, 5, 9), ":", "-"));
Assert.AreEqual("GEN 1:1", BCVRef.MakeReferenceString(
new BCVRef(1, 1, 1), new BCVRef(), ":", "-"));
Assert.AreEqual("GEN 5:5", BCVRef.MakeReferenceString(
new BCVRef(1, 5, 5), new BCVRef(1, 5, 5), ":", "-"));
Assert.AreEqual("REV 22:58", BCVRef.MakeReferenceString(
new BCVRef(66, 22, 58), new BCVRef(66, 22, 58), ":", "-"));
Assert.AreEqual("MRK 12:34-14:56", BCVRef.MakeReferenceString(
new BCVRef(41, 12, 34), new BCVRef(41, 14, 56), ":", "-"));
// Chapter-only references
Assert.AreEqual("MRK 10", BCVRef.MakeReferenceString(
new BCVRef(41, 10, 0), new BCVRef(), ":", "-", true));
Assert.AreEqual("MRK 10", BCVRef.MakeReferenceString(
new BCVRef(41, 10, 0), null, ":", "-", true));
Assert.AreEqual("MRK 1-2", BCVRef.MakeReferenceString(
new BCVRef(41, 1, 0), new BCVRef(41, 2, 0), ":", "-"));
Assert.AreEqual("MRK 5-10", BCVRef.MakeReferenceString(
new BCVRef(41, 5, 0), new BCVRef(41, 10, 0), ":", "-"));
// Bridges where once verse is 0 (ill-formed)
Assert.AreEqual("MRK 1:2-2:0", BCVRef.MakeReferenceString(
new BCVRef(41, 1, 2), new BCVRef(41, 2, 0), ":", "-"));
Assert.AreEqual("MRK 10:0-12:34", BCVRef.MakeReferenceString(
new BCVRef(41, 10, 0), new BCVRef(41, 12, 34), ":", "-"));
// Title references
Assert.AreEqual("MRK Title", BCVRef.MakeReferenceString(
new BCVRef(41, 0, 0), null, ":", "-", "Title", "Intro"));
Assert.AreEqual("MRK 0", BCVRef.MakeReferenceString(
new BCVRef(41, 0, 0), null, ":", "-", null, null));
// Intro references
Assert.AreEqual("MRK", BCVRef.MakeReferenceString(
new BCVRef(41, 1, 0), new BCVRef(41, 1, 0), ":", "-", true));
Assert.AreEqual("MRK", BCVRef.MakeReferenceString(
new BCVRef(41, 1, 0), new BCVRef(41, 1, 0), ":", "-", null, string.Empty));
Assert.AreEqual("MRK Intro", BCVRef.MakeReferenceString(
new BCVRef(41, 1, 0), new BCVRef(41, 1, 0), ":", "-", "Title", "Intro"));
Assert.AreEqual("MRK 1", BCVRef.MakeReferenceString(
new BCVRef(41, 1, 0), null, ":", "-", false));
Assert.AreEqual("MRK 1", BCVRef.MakeReferenceString(
new BCVRef(41, 1, 0), new BCVRef(41, 1, 0), ":", "-", null, null));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the LastBook property if we don't support deuterocanonical books
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void LastBook_NoDeuterocanon()
{
Assert.AreEqual(66, BCVRef.LastBook);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the LastBook property if we do support deuterocanonical books
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void LastBook_Deuterocanon()
{
BCVRef.SupportDeuterocanon = true;
Assert.AreEqual(92, BCVRef.LastBook);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BookToNumber method if we don't support deuterocanonical books
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void BookToNumber_NoDeuterocanon()
{
Assert.AreEqual(1, BCVRef.BookToNumber("GEN"));
Assert.AreEqual(66, BCVRef.BookToNumber("REV"));
Assert.AreEqual(-1, BCVRef.BookToNumber("TOB"));
Assert.AreEqual(-1, BCVRef.BookToNumber("BLT"));
Assert.AreEqual(0, BCVRef.BookToNumber("XYZ"));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BookToNumber method if we do support deuterocanonical books
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void BookToNumber_Deuterocanon()
{
BCVRef.SupportDeuterocanon = true;
Assert.AreEqual(1, BCVRef.BookToNumber("GEN"));
Assert.AreEqual(66, BCVRef.BookToNumber("REV"));
Assert.AreEqual(67, BCVRef.BookToNumber("TOB"));
Assert.AreEqual(92, BCVRef.BookToNumber("BLT"));
Assert.AreEqual(0, BCVRef.BookToNumber("XYZ"));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the NumberToBookCode method if we don't support deuterocanonical books
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void NumberToBookCode_NoDeuterocanon()
{
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(-1));
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(0));
Assert.AreEqual("GEN", BCVRef.NumberToBookCode(1));
Assert.AreEqual("REV", BCVRef.NumberToBookCode(66));
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(67));
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(92));
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(93));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the NumberToBookCode method if we do support deuterocanonical books
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void NumberToBookCode_Deuterocanon()
{
BCVRef.SupportDeuterocanon = true;
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(-1));
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(0));
Assert.AreEqual("GEN", BCVRef.NumberToBookCode(1));
Assert.AreEqual("REV", BCVRef.NumberToBookCode(66));
Assert.AreEqual("TOB", BCVRef.NumberToBookCode(67));
Assert.AreEqual("BLT", BCVRef.NumberToBookCode(92));
Assert.AreEqual(string.Empty, BCVRef.NumberToBookCode(93));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ToString method for a book title.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ToString_Title()
{
BCVRef genesisTitleRef = new BCVRef(1000000);
Assert.AreEqual("GEN 0:0", genesisTitleRef.ToString(BCVRef.RefStringFormat.General));
Assert.AreEqual("GEN Title", genesisTitleRef.ToString(BCVRef.RefStringFormat.Exchange));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ToString method for intro material.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ToString_Intro()
{
BCVRef genesisTitleRef = new BCVRef(1001000);
Assert.AreEqual("GEN 1:0", genesisTitleRef.ToString(BCVRef.RefStringFormat.General));
Assert.AreEqual("GEN Intro", genesisTitleRef.ToString(BCVRef.RefStringFormat.Exchange));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ToString method for a bogus reference (intro material on chapter 2?).
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ToString_BogusIntro()
{
BCVRef genesisTitleRef = new BCVRef(1002000);
Assert.AreEqual("GEN 2:0", genesisTitleRef.ToString(BCVRef.RefStringFormat.General));
Assert.AreEqual("GEN 2:0", genesisTitleRef.ToString(BCVRef.RefStringFormat.Exchange));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ToString method for a bogus reference (intro material on chapter 2?).
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ToString_NormalVerse()
{
BCVRef exodusTitleRef = new BCVRef(2004006);
Assert.AreEqual("EXO 4:6", exodusTitleRef.ToString(BCVRef.RefStringFormat.General));
Assert.AreEqual("EXO 4:6", exodusTitleRef.ToString(BCVRef.RefStringFormat.Exchange));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ability to instantiate a BCVRef from a string representation of a book
/// title that uses the Exchange format.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void Parse_Title()
{
BCVRef genesisTitleRef = new BCVRef("GEN Title");
Assert.AreEqual(1, genesisTitleRef.Book);
Assert.AreEqual(0, genesisTitleRef.Chapter);
Assert.AreEqual(0, genesisTitleRef.Verse);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ability to instantiate a BCVRef from a string representation of a book
/// introduction that uses the Exchange format.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void Parse_Intro()
{
BCVRef genesisTitleRef = new BCVRef("GEN Intro");
Assert.AreEqual(1, genesisTitleRef.Book);
Assert.AreEqual(1, genesisTitleRef.Chapter);
Assert.AreEqual(0, genesisTitleRef.Verse);
}
}
#endregion
#region Parsing Tests
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Tests for methods on BCVRef that parse references, chapter numbers, and verse numbers.
/// </summary>
/// ----------------------------------------------------------------------------------------
[TestFixture]
public class BCVRef_ParseChapterVerseNumberTests
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the VerseToScrRef method when dealing with large verse numbers
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void VerseToScrRefTest_LargeVerseNumber()
{
BCVRef startVerse = new BCVRef();
BCVRef endVerse = new BCVRef();
string literal, remaining;
bool convertSuccessful;
// Test a really large number that will pass the Int16.MaxValue
convertSuccessful = BCVRef.VerseToScrRef("5200000000000", out literal,
out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(0, startVerse.Verse);
Assert.AreEqual(0, endVerse.Verse);
Assert.IsFalse(convertSuccessful);
// Test a verse number just under the limit
convertSuccessful = BCVRef.VerseToScrRef("32766", out literal,
out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(32766, startVerse.Verse);
Assert.AreEqual(32766, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the Parse method
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseTest()
{
BCVRef bcvRef = new BCVRef();
// Note: Don't break into individual unit tests because this test also makes sure
// that the results of a previous parse don't have unintended consequences for a
// subsequent parse.
// Test a normal reference
bcvRef.Parse("EXO 9:32");
Assert.AreEqual(2, bcvRef.Book);
Assert.AreEqual(9, bcvRef.Chapter);
Assert.AreEqual(32, bcvRef.Verse);
// Test a bogus book
bcvRef.Parse("GYQ 8:12");
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(9, bcvRef.Chapter);
Assert.AreEqual(32, bcvRef.Verse);
// Test large chapter and verse numbers
bcvRef.Parse("MAT 1000:2500");
Assert.AreEqual(40, bcvRef.Book);
Assert.AreEqual(1000, bcvRef.Chapter);
Assert.AreEqual(2500, bcvRef.Verse);
// Test no chapter or verse number
bcvRef.Parse("REV");
Assert.AreEqual(66, bcvRef.Book);
Assert.AreEqual(1, bcvRef.Chapter);
Assert.AreEqual(1, bcvRef.Verse);
// Test empty string - should not crash
bcvRef.Parse("");
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(1, bcvRef.Chapter);
Assert.AreEqual(1, bcvRef.Verse);
// Test no verse number
bcvRef.Parse("LUK 5");
Assert.AreEqual(42, bcvRef.Book);
Assert.AreEqual(5, bcvRef.Chapter);
Assert.AreEqual(1, bcvRef.Verse);
// Test invalid format
bcvRef.Parse("ROM 5!3@4");
Assert.AreEqual(0, bcvRef.Book);
Assert.AreEqual(5, bcvRef.Chapter);
Assert.AreEqual(3, bcvRef.Verse);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests for converting verse number strings to BCVRefs. These are similar
/// scenarios tested in ExportUsfm:VerseNumParse. All of them are successfully parsed
/// there. The scenarios which have problems converting verse number strings, are
/// commented out with a description of the incorrect result.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void VerseToScrRefTest()
{
BCVRef startVerse = new BCVRef();
BCVRef endVerse = new BCVRef();
string literal, remaining = string.Empty;
bool convertSuccessful;
// Test invalid verse number strings
convertSuccessful = BCVRef.VerseToScrRef("-12", out literal, out remaining, ref startVerse, ref endVerse);
//Assert.AreEqual(12, startVerse.Verse); // start verse set to 0 instead of 12
Assert.AreEqual(12, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("12-", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(12, startVerse.Verse);
Assert.AreEqual(12, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("a3", out literal, out remaining, ref startVerse, ref endVerse);
//Assert.AreEqual(3, startVerse.Verse); // does not set starting verse value
//Assert.AreEqual(3, endVerse.Verse); // does not set end verse value
Assert.IsFalse(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef("15b-a", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(15, startVerse.Verse);
Assert.AreEqual(15, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("3bb", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(3, startVerse.Verse);
Assert.AreEqual(3, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("0", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(0, startVerse.Verse);
Assert.AreEqual(0, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef(" 12", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(12, startVerse.Verse);
Assert.AreEqual(12, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("12 ", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(12, startVerse.Verse);
Assert.AreEqual(12, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("12-10", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(12, startVerse.Verse); // out of order
//Assert.AreEqual(12, endVerse.Verse); // end verse set to 12 instead of 10
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("1-176", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(1, startVerse.Verse);
Assert.AreEqual(176, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef("139-1140", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(139, startVerse.Verse); // 1140 is out of range of valid verse numbers
//Assert.AreEqual(139, endVerse.Verse); // end verse set to 1140 instead of 139
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef("177-140", out literal, out remaining, ref startVerse, ref endVerse);
//Assert.AreEqual(140, startVerse.Verse); // 177 is out of range of valid verse numbers
Assert.AreEqual(140, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
//Review: should this be a requirement?
// convertSuccessful = BCVRef.VerseToScrRef("177", out literal, out remaining, ref startVerse, ref endVerse);
// Assert.AreEqual(0, startVerse.Verse); // 177 is out of range of valid verse numbers
// Assert.AreEqual(0, endVerse.Verse);
//Assert.IsFalse(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef(String.Empty, out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(0, startVerse.Verse);
Assert.AreEqual(0, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
convertSuccessful = BCVRef.VerseToScrRef(String.Empty, out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(0, startVerse.Verse);
Assert.AreEqual(0, endVerse.Verse);
//Assert.IsFalse(convertSuccessful); // Does not detect invalid verse number format.
// Test valid verse number strings
convertSuccessful = BCVRef.VerseToScrRef("1a", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(1, startVerse.Verse);
Assert.AreEqual(1, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef("2a-3b", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(2, startVerse.Verse);
Assert.AreEqual(3, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef("4-5d", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(4, startVerse.Verse);
Assert.AreEqual(5, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef("6", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(6, startVerse.Verse);
Assert.AreEqual(6, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef("66", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(66, startVerse.Verse);
Assert.AreEqual(66, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
convertSuccessful = BCVRef.VerseToScrRef("176", out literal, out remaining, ref startVerse, ref endVerse);
Assert.AreEqual(176, startVerse.Verse);
Assert.AreEqual(176, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
//We expect this test to pass
//RTL verse bridge should be valid syntax
convertSuccessful = BCVRef.VerseToScrRef("6" + '\u200f' + "-" + '\u200f' + "8", out literal, out remaining,
ref startVerse, ref endVerse);
Assert.AreEqual(6, startVerse.Verse);
Assert.AreEqual(8, endVerse.Verse);
Assert.IsTrue(convertSuccessful);
}
///// ------------------------------------------------------------------------------------
///// <summary>
///// Tests the BCVRef.ParseRefRange method when given a USFM-style chapter
///// range.
///// </summary>
///// ------------------------------------------------------------------------------------
//[Test]
//public void ParseRefRange_USFMStyleChapterRange()
//{
// BCVRef bcvRefStart = new BCVRef();
// BCVRef bcvRefEnd = new BCVRef();
// Assert.IsTrue(BCVRef.ParseRefRange("MRK 1--2", ref bcvRefStart, ref bcvRefEnd, Ver));
// Assert.AreEqual(new BCVRef(41, 1, 1), bcvRefStart);
// ScrReference refMax = new ScrReference(41, 2, 1, m_scr.Versification);
// refMax.Verse = refMax.LastVerse;
// Assert.AreEqual(refMax, bcvRef.LocationMax);
//}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range with the book ID
/// specified only in the first reference.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_NormalVerseRange_BookSpecifiedOnce()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsTrue(BCVRef.ParseRefRange("MRK 1:8-2:15", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 1, 8), bcvRefStart);
Assert.AreEqual(new BCVRef(41, 2, 15), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range that includes the
/// largest allowable verse number.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_NormalVerseRange_MaxVerseNumber()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsTrue(BCVRef.ParseRefRange("PSA 119:175-176", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(19, 119, 175), bcvRefStart);
Assert.AreEqual(new BCVRef(19, 119, 176), bcvRefEnd);
Assert.IsTrue(BCVRef.ParseRefRange("174-176", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(19, 119, 174), bcvRefStart);
Assert.AreEqual(new BCVRef(19, 119, 176), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range with the
/// book ID specified both references.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_NormalVerseRange_BookSpecifiedTwice()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsTrue(BCVRef.ParseRefRange("MRK 1:8-MRK 2:15", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 1, 8), bcvRefStart);
Assert.AreEqual(new BCVRef(41, 2, 15), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range consisting of two
/// BBCCCVVV-format integers
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_ValidBBCCCVVVRange()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsTrue(BCVRef.ParseRefRange("40001002-41002006", ref bcvRefStart, ref bcvRefEnd, true));
Assert.AreEqual(new BCVRef(40, 1, 2), bcvRefStart);
Assert.AreEqual(new BCVRef(41, 2, 6), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range consisting of two
/// BBCCCVVV-format integers that have values that are bogusly out of range.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_InvalidBBCCCVVVRange()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsFalse(BCVRef.ParseRefRange("40029001-67001001", ref bcvRefStart, ref bcvRefEnd, true));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range without a book ID.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_NormalVerseRange_BookNotSpecified()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(41, 2, 3);
Assert.IsTrue(BCVRef.ParseRefRange("1:8-2:15", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 1, 8), bcvRefStart, "Book of Mark is inferred from incoming reference.");
Assert.AreEqual(new BCVRef(41, 2, 15), bcvRefEnd, "Book of Mark is inferred from incoming reference.");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range without a book ID
/// and the incoming references are for different books.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_VerseRange_BookNotSpecified_BooksAreDifferent()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(66, 2, 3);
Assert.IsFalse(BCVRef.ParseRefRange("1:8-2:15", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefStart, "Since ParseRefRange failed, the reference should be unchanged");
Assert.AreEqual(new BCVRef(66, 2, 3), bcvRefEnd, "Since ParseRefRange failed, the reference should be unchanged");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range without
/// chapter numbers.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_NormalVerseRange_ChapterNotSpecified()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(41, 2, 3);
Assert.IsTrue(BCVRef.ParseRefRange("2-15", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 2), bcvRefStart);
Assert.AreEqual(new BCVRef(41, 2, 15), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range without chapter
/// numbers and the incoming references have chapter numbers that don't match.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_ChapterNotSpecified_ChaptersAreDifferent()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(41, 5, 3);
Assert.IsFalse(BCVRef.ParseRefRange("8-15", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefStart, "Since ParseRefRange failed, the reference should be unchanged");
Assert.AreEqual(new BCVRef(41, 5, 3), bcvRefEnd, "Since ParseRefRange failed, the reference should be unchanged");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range without chapter
/// numbers and the incoming references have book numbers that don't match.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_ChapterNotSpecified_BooksAreDifferent()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(43, 2, 9);
Assert.IsFalse(BCVRef.ParseRefRange("8-15", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefStart, "Since ParseRefRange failed, the reference should be unchanged");
Assert.AreEqual(new BCVRef(43, 2, 9), bcvRefEnd, "Since ParseRefRange failed, the reference should be unchanged");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a single verse.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_SingleReference()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(41, 2, 3);
Assert.IsTrue(BCVRef.ParseRefRange("MRK 2:3", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefStart);
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a bogus string consisting of a
/// single number (treat as a verse number).
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_BogusReferenceRange_SingleNumber()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(41, 2, 3);
Assert.IsTrue(BCVRef.ParseRefRange("7", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 7), bcvRefStart);
Assert.AreEqual(new BCVRef(41, 2, 7), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a bogus string.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_BogusReferenceRange_Unintelligible()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(41, 2, 3);
Assert.IsFalse(BCVRef.ParseRefRange("XYZ 3:4&6:7", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefStart, "Since ParseRefRange failed, the reference should be unchanged");
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefEnd, "Since ParseRefRange failed, the reference should be unchanged");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given more than two references.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_BogusReferenceRange_MoreThanTwoRefs()
{
BCVRef bcvRefStart = new BCVRef(41, 2, 3);
BCVRef bcvRefEnd = new BCVRef(41, 2, 3);
Assert.IsFalse(BCVRef.ParseRefRange("GEN 4:5 - MAT 6:8 - REV 1:9", ref bcvRefStart, ref bcvRefEnd));
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefStart, "Since ParseRefRange failed, the reference should be unchanged");
Assert.AreEqual(new BCVRef(41, 2, 3), bcvRefEnd, "Since ParseRefRange failed, the reference should be unchanged");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range that
/// covers multiple books and caller is okay with that.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_NormalReferenceRange_MultipleBooks()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsTrue(BCVRef.ParseRefRange("MAT 1:5-REV 12:2", ref bcvRefStart, ref bcvRefEnd, true));
Assert.AreEqual(new BCVRef(40, 1, 5), bcvRefStart);
Assert.AreEqual(new BCVRef(66, 12, 2), bcvRefEnd);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range that
/// covers multiple books but caller is requesting a range for a single book.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_BogusReferenceRange_MultipleBooks()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsFalse(BCVRef.ParseRefRange("MAT 1:5-REV 12:2", ref bcvRefStart, ref bcvRefEnd, false));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range whose
/// start is after its end (should be rejected).
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_BogusReferenceRange_Backwards()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsFalse(BCVRef.ParseRefRange("MRK 2:5-MRK 1:2", ref bcvRefStart, ref bcvRefEnd));
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the BCVRef.ParseRefRange method when given a verse range that includes a sub-
/// verse letter.
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ParseRefRange_NormalReferenceRange_SubVerseLetter()
{
BCVRef bcvRefStart = new BCVRef();
BCVRef bcvRefEnd = new BCVRef();
Assert.IsTrue(BCVRef.ParseRefRange("LUK 9.37-43a", ref bcvRefStart, ref bcvRefEnd, true));
Assert.AreEqual(new BCVRef(42, 9, 37), bcvRefStart);
Assert.AreEqual(new BCVRef(42, 9, 43), bcvRefEnd);
}
}
#endregion
}
| |
//
// XslOutput.cs
//
// Authors:
// Ben Maurer (bmaurer@users.sourceforge.net)
// Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
// Oleg Tkachenko (oleg@tkachenko.com)
//
// (C) 2003 Ben Maurer
// (C) 2003 Atsushi Enomoto
// (C) 2003 Oleg Tkachenko
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Text;
namespace Mono.Xml.Xsl
{
using QName = System.Xml.XmlQualifiedName;
internal enum OutputMethod {
XML,
HTML,
Text,
Custom,
Unknown
}
internal enum StandaloneType {
NONE,
YES,
NO
}
internal class XslOutput // also usable for xsl:result-document
{
string uri;
QName customMethod;
OutputMethod method = OutputMethod.Unknown;
string version;
Encoding encoding = System.Text.Encoding.UTF8;
bool omitXmlDeclaration;
StandaloneType standalone = StandaloneType.NONE;
string doctypePublic;
string doctypeSystem;
QName [] cdataSectionElements;
string indent;
string mediaType;
string stylesheetVersion;
// for compilation only.
ArrayList cdSectsList = new ArrayList ();
public XslOutput (string uri, string stylesheetVersion)
{
this.uri = uri;
this.stylesheetVersion = stylesheetVersion;
}
public OutputMethod Method { get { return method; }}
public QName CustomMethod { get { return customMethod; }}
public string Version {
get { return version; }
}
public Encoding Encoding {
get { return encoding; }
}
public string Uri {
get { return uri; }
}
public bool OmitXmlDeclaration {
get { return omitXmlDeclaration; }
}
public StandaloneType Standalone {
get { return standalone; }
}
public string DoctypePublic {
get { return doctypePublic; }
}
public string DoctypeSystem {
get { return doctypeSystem; }
}
public QName [] CDataSectionElements {
get {
if (cdataSectionElements == null)
cdataSectionElements = cdSectsList.ToArray (typeof (QName)) as QName [];
return cdataSectionElements;
}
}
public string Indent {
get { return indent; }
}
public string MediaType {
get { return mediaType; }
}
public void Fill (XPathNavigator nav)
{
if (nav.MoveToFirstAttribute ()) {
ProcessAttribute (nav);
while (nav.MoveToNextAttribute ()) {
ProcessAttribute (nav);
}
// move back to original position
nav.MoveToParent ();
}
}
private void ProcessAttribute (XPathNavigator nav)
{
// skip attributes from non-default namespace
if (nav.NamespaceURI != string.Empty) {
return;
}
string value = nav.Value;
switch (nav.LocalName) {
case "cdata-section-elements":
if (value.Length > 0) {
cdSectsList.AddRange (XslNameUtil.FromListString (value, nav));
}
break;
case "method":
if (value.Length == 0) {
break;
}
switch (value) {
case "xml":
method = OutputMethod.XML;
break;
case "html":
omitXmlDeclaration = true;
method = OutputMethod.HTML;
break;
case "text":
omitXmlDeclaration = true;
method = OutputMethod.Text;
break;
default:
method = OutputMethod.Custom;
customMethod = XslNameUtil.FromString (value, nav);
if (customMethod.Namespace == String.Empty) {
IXmlLineInfo li = nav as IXmlLineInfo;
throw new XsltCompileException (new ArgumentException (
"Invalid output method value: '" + value + "'. It" +
" must be either 'xml' or 'html' or 'text' or QName."),
nav.BaseURI,
li != null ? li.LineNumber : 0,
li != null ? li.LinePosition : 0);
}
break;
}
break;
case "version":
if (value.Length > 0) {
this.version = value;
}
break;
case "encoding":
if (value.Length > 0) {
try {
this.encoding = System.Text.Encoding.GetEncoding (value);
} catch (ArgumentException) {
// MS.NET just leaves the default encoding when encoding is unknown
} catch (NotSupportedException) {
// Workaround for a bug in System.Text, it throws invalid exception
}
}
break;
case "standalone":
switch (value) {
case "yes":
this.standalone = StandaloneType.YES;
break;
case "no":
this.standalone = StandaloneType.NO;
break;
default:
if (stylesheetVersion != "1.0")
break;
IXmlLineInfo li = nav as IXmlLineInfo;
throw new XsltCompileException (new XsltException (
"'" + value + "' is an invalid value for 'standalone'" +
" attribute.", (Exception) null),
nav.BaseURI,
li != null ? li.LineNumber : 0,
li != null ? li.LinePosition : 0);
}
break;
case "doctype-public":
this.doctypePublic = value;
break;
case "doctype-system":
this.doctypeSystem = value;
break;
case "media-type":
if (value.Length > 0) {
this.mediaType = value;
}
break;
case "omit-xml-declaration":
switch (value) {
case "yes":
this.omitXmlDeclaration = true;
break;
case "no":
this.omitXmlDeclaration = false;
break;
default:
if (stylesheetVersion != "1.0")
break;
IXmlLineInfo li = nav as IXmlLineInfo;
throw new XsltCompileException (new XsltException (
"'" + value + "' is an invalid value for 'omit-xml-declaration'" +
" attribute.", (Exception) null),
nav.BaseURI,
li != null ? li.LineNumber : 0,
li != null ? li.LinePosition : 0);
}
break;
case "indent":
indent = value;
if (stylesheetVersion != "1.0")
break;
switch (value) {
case "yes":
case "no":
break;
default:
switch (method) {
case OutputMethod.Custom:
break;
default:
throw new XsltCompileException (String.Format ("Unexpected 'indent' attribute value in 'output' element: '{0}'", value), null, nav);
}
break;
}
break;
default:
if (stylesheetVersion != "1.0")
break;
IXmlLineInfo xli = nav as IXmlLineInfo;
throw new XsltCompileException (new XsltException (
"'" + nav.LocalName + "' is an invalid attribute for 'output'" +
" element.", (Exception) null),
nav.BaseURI,
xli != null ? xli.LineNumber : 0,
xli != null ? xli.LinePosition : 0);
}
}
}
}
| |
// This file is part of Sdict2db.
//
// Sdict2db 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 3 of the License, or
// (at your option) any later version.
//
// Sdict2db 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 Sdict2db. if not, see <http://www.gnu.org/licenses/>.
//
// Copyright 2008 Alla Morgunova
using System;
using System.Windows.Forms;
using System.Data;
using Sdict2db.Helpers;
namespace Sdict2db.PagedGridView {
class DataPager : IDisposable {
#region Private members
private DataTable _sourceData;
private BindingSource _currentData;
private DataTable _page;
private int _pageSize;
private int _maxSelectionOffset;
private int _selection;
private SortOrder _sortOrder;
private string _sortField;
#endregion
#region Properties
public DataTable SourceData {
get {
return _sourceData;
}
set {
Clear();
_sourceData = value;
_currentData =
new BindingSource(_sourceData, _sourceData.TableName);
}
}
public DataTable CurrentData {
get {
if (_currentData == null) {
return SourceData;
}
DataView view = _currentData.List as DataView;
if (view == null) {
return null;
} else {
return view.ToTable();
}
}
}
public bool Empty {
get {
return (_sourceData == null) || (_currentData == null);
}
}
public DataTable Page {
get {
return _page;
}
}
public int Count {
get {
if ((_sourceData == null) ||
(_sourceData.Rows == null)) {
return 0;
}
return _sourceData.Rows.Count;
}
}
public int CurrentCount {
get {
if (_currentData == null) {
return 0;
}
return _currentData.CurrencyManager.Count;
}
}
public int Selection {
get {
return _selection;
}
set {
_selection = RangePosition(value);
_currentData.Position = _selection;
}
}
public int PageSize {
get {
return _pageSize;
}
set {
_pageSize = NumberHelper.GetValueInRange(value, 1, value);
}
}
public int MaxOffset {
get {
return _maxSelectionOffset;
}
}
public SortOrder SortOrder {
get {
return _sortOrder;
}
set {
_sortOrder = value;
}
}
public string SortField {
get {
return _sortField;
}
}
#endregion
#region Construction
public DataPager() {
}
public void Clear() {
if (_sourceData != null) {
_sourceData.Dispose();
_sourceData = null;
}
if (_currentData != null) {
_currentData.Dispose();
_currentData = null;
}
}
#endregion
#region Events
public event EventHandler<EventArgs> PageLoaded;
private void PageLoadedHandler(object sender, EventArgs e) {
if (PageLoaded != null) {
PageLoaded(this, e);
}
}
#endregion
#region Paging
public void SetPageSize(float pageSize) {
PageSize = (int)Math.Ceiling(pageSize);
_maxSelectionOffset = ((float)PageSize - pageSize) > 0.3 ?
PageSize - 2 : PageSize - 1;
}
public void LoadDataPage(int currentScrollPosition) {
if (Empty) {
return;
}
_page = _sourceData.Clone();
_page.Rows.Clear();
DataView view = _currentData.List as DataView;
if (view == null) {
return;
}
for (int i = currentScrollPosition;
i < currentScrollPosition + _pageSize; ++i) {
if ((i >= 0) && (i < view.Count)) {
_page.ImportRow(view[i].Row);
}
}
PageLoadedHandler(this, new EventArgs());
}
#endregion
#region Sorting/Filtering/Searching
#region Sorting
public void Sort(string field) {
if (Empty || (!_sourceData.Columns.Contains(field))) {
return;
}
ChooseSortMode();
if (_sortOrder == SortOrder.None) {
_currentData.RemoveSort();
_sortField = string.Empty;
} else {
_currentData.Sort =
StringHelper.CreateSortExpression(field, _sortOrder);
_sortField = field;
}
Selection = 0;
}
private void ChooseSortMode() {
if (_sortOrder == SortOrder.Ascending) {
_sortOrder = SortOrder.Descending;
} else if ((_sortOrder == SortOrder.Descending) &&
(CurrentCount == Count)) {
_sortOrder = SortOrder.None;
} else {
_sortOrder = SortOrder.Ascending;
}
}
#endregion
#region Filtering
public void Filter(string[] fields, string[] values) {
if (Empty || (!ContainsFields(_sourceData, fields))) {
return;
}
if (StringHelper.ConsistsOfEmptyStrings(values)) {
_currentData.RemoveFilter();
} else {
_currentData.Filter =
StringHelper.CreateFilterExpression(fields, values);
}
Selection = 0;
}
#endregion
#region Searching
public bool Find(string field, string value) {
if (Empty || (_sourceData.Rows.Count <= 0) ||
(!_sourceData.Columns.Contains(field)) ||
(string.IsNullOrEmpty(value))) {
return false;
}
if (!string.IsNullOrEmpty(_currentData.Sort)) {
_currentData.RemoveFilter();
}
int position = FindRecord(_currentData, field, value, false);
if (position >= 0) {
Selection = position;
return true;
}
return false;
}
private static int FindRecord(BindingSource data, string field,
string value, bool caseSensitive) {
if (data == null) {
return -1;
}
try {
DataView view = data.List as DataView;
if (view == null) {
return -1;
}
for (int i = 0; i < view.Count; ++i) {
if (StringHelper.BeginsWith(view[i].Row[field].ToString(),
value, caseSensitive)) {
return i;
}
}
} catch (ArgumentException ex) {
MessageHelper.ShowErrorMessage(ex.Message);
}
return -1;
}
#endregion
#endregion
#region Editing
public void SubmitEditCurrentRow(DataGridViewCellEventArgs e) {
DataRowView rowToBeEdited = _currentData.Current as DataRowView;
if ((rowToBeEdited == null) ||
(rowToBeEdited.Row.ItemArray.Length != _page.Columns.Count)) {
return;
}
for (int i = 0; i < _page.Columns.Count; ++i) {
rowToBeEdited.Row[i] = _page.Rows[e.RowIndex][i];
}
}
#endregion
#region Helpers
private int RangePosition(int value) {
return NumberHelper.GetValueInRange(value, 0, CurrentCount - 1);
}
private static bool ContainsFields(DataTable data, string[] fields) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (fields == null) {
throw new ArgumentNullException("fields");
}
for (int i = 0; i < fields.Length; ++i) {
if (!data.Columns.Contains(fields[i])) {
return false;
}
}
return true;
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
// dispose managed resources
_currentData.Dispose();
}
// free native resources
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;
using NUnit.Framework;
namespace SJP.Schematic.Graphviz.Tests
{
public class DotSvgRendererTests
{
private GraphvizTemporaryExecutable GraphvizExe { get; set; }
private DotSvgRenderer Renderer => new DotSvgRenderer(GraphvizExe.DotExecutablePath);
[OneTimeSetUp]
public void Init()
{
GraphvizExe = new GraphvizTemporaryExecutable();
}
[OneTimeTearDown]
public void CleanUp()
{
GraphvizExe.Dispose();
}
[Test]
public void DotRenderer_GivenNullExecutablePath_ThrowsArgumentNullException()
{
Assert.That(() => new DotSvgRenderer(null), Throws.ArgumentNullException);
}
[Test]
public void DotRenderer_GivenEmptyExecutablePath_ThrowsArgumentNullException()
{
Assert.That(() => new DotSvgRenderer(string.Empty), Throws.ArgumentNullException);
}
[Test]
public void DotRenderer_GivenWhiteSpaceExecutablePath_ThrowsArgumentNullException()
{
Assert.That(() => new DotSvgRenderer(" "), Throws.ArgumentNullException);
}
[Test]
public void DotRenderer_GivenMissingExecutablePath_ThrowsFileNotFoundException()
{
Assert.That(() => new DotSvgRenderer("path_not_existing"), Throws.TypeOf<FileNotFoundException>());
}
[Test]
public void RenderToSvg_GivenNullDotDiagram_ThrowsArgumentNullException()
{
Assert.That(() => Renderer.RenderToSvg(null), Throws.ArgumentNullException);
}
[Test]
public void RenderToSvg_GivenEmptyDotDiagram_ThrowsArgumentNullException()
{
Assert.That(() => Renderer.RenderToSvg(string.Empty), Throws.ArgumentNullException);
}
[Test]
public void RenderToSvg_GivenWhiteSpaceDotDiagram_ThrowsArgumentNullException()
{
Assert.That(() => Renderer.RenderToSvg(" "), Throws.ArgumentNullException);
}
[Test]
public void RenderToSvg_GivenInvalidDot_ThrowsGraphvizException()
{
Assert.That(() => Renderer.RenderToSvg("this is not dot"), Throws.TypeOf<GraphvizException>());
}
[Test]
public void RenderToSvg_GivenValidDot_ReturnsValidSvgXml()
{
var svg = Renderer.RenderToSvg("digraph g { a -> b }");
Assert.That(() => _ = XDocument.Parse(svg, LoadOptions.PreserveWhitespace), Throws.Nothing);
}
// Note, this is fragile only because it contains date/version comments.
// It should be very stable otherwise.
[Test]
public void RenderToSvg_GivenValidDot_ReturnsExpectedSvg()
{
var svg = Renderer.RenderToSvg("digraph g { a -> b }");
Assert.That(svg, Is.EqualTo(SimpleGraphExpectedSvg));
}
[Test]
public void RenderToSvg_GivenVizJsGraphExample_ReturnsValidSvgXml()
{
var svg = Renderer.RenderToSvg(VizJsExample);
Assert.That(() => _ = XDocument.Parse(svg, LoadOptions.PreserveWhitespace), Throws.Nothing);
}
[Test]
public void RenderToSvgAsync_GivenNullDotDiagram_ThrowsArgumentNullException()
{
Assert.That(() => Renderer.RenderToSvgAsync(null), Throws.ArgumentNullException);
}
[Test]
public void RenderToSvgAsync_GivenEmptyDotDiagram_ThrowsArgumentNullException()
{
Assert.That(() => Renderer.RenderToSvgAsync(string.Empty), Throws.ArgumentNullException);
}
[Test]
public void RenderToSvgAsync_GivenWhiteSpaceDotDiagram_ThrowsArgumentNullException()
{
Assert.That(() => Renderer.RenderToSvgAsync(" "), Throws.ArgumentNullException);
}
[Test]
public void RenderToSvgAsync_GivenInvalidDot_ThrowsGraphvizException()
{
Assert.That(async () => await Renderer.RenderToSvgAsync("this is not dot").ConfigureAwait(false), Throws.TypeOf<GraphvizException>());
}
[Test]
public async Task RenderToSvgAsync_GivenValidDot_ReturnsValidSvgXml()
{
var svg = await Renderer.RenderToSvgAsync("digraph g { a -> b }").ConfigureAwait(false);
Assert.That(() => _ = XDocument.Parse(svg, LoadOptions.PreserveWhitespace), Throws.Nothing);
}
// Note, this is fragile only because it contains date/version comments.
// It should be very stable otherwise.
[Test]
public async Task RenderToSvgAsync_GivenValidDot_ReturnsExpectedSvg()
{
var svg = await Renderer.RenderToSvgAsync("digraph g { a -> b }").ConfigureAwait(false);
Assert.That(svg, Is.EqualTo(SimpleGraphExpectedSvg));
}
[Test]
public async Task RenderToSvgAsync_GivenVizJsGraphExample_ReturnsValidSvgXml()
{
var svg = await Renderer.RenderToSvgAsync(VizJsExample).ConfigureAwait(false);
Assert.That(() => _ = XDocument.Parse(svg, LoadOptions.PreserveWhitespace), Throws.Nothing);
}
private const string VizJsExample = @"digraph G {
subgraph cluster_0 {
style=filled;
color=lightgrey;
node [style=filled,color=white];
a0 -> a1 -> a2 -> a3;
label = ""process #1"";
}
subgraph cluster_1
{
node [style=filled];
b0 -> b1 -> b2 -> b3;
label = ""process #2"";
color=blue
}
start -> a0;
start -> b0;
a1 -> b3;
b2 -> a3;
a3 -> a0;
a3 -> end;
b3 -> end;
start[shape = Mdiamond];
end[shape = Msquare];
}";
private const string SimpleGraphExpectedSvg = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no""?>
<!DOCTYPE svg PUBLIC ""-//W3C//DTD SVG 1.1//EN""
""http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"">
<!-- Generated by graphviz version 2.38.0 (20140413.2041)
-->
<!-- Title: g Pages: 1 -->
<svg width=""62pt"" height=""116pt""
viewBox=""0.00 0.00 62.00 116.00"" xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/1999/xlink"">
<g id=""graph0"" class=""graph"" transform=""scale(1 1) rotate(0) translate(4 112)"">
<title>g</title>
<polygon fill=""white"" stroke=""none"" points=""-4,4 -4,-112 58,-112 58,4 -4,4""/>
<!-- a -->
<g id=""node1"" class=""node""><title>a</title>
<ellipse fill=""none"" stroke=""black"" cx=""27"" cy=""-90"" rx=""27"" ry=""18""/>
<text text-anchor=""middle"" x=""27"" y=""-86.3"" font-family=""Times New Roman,serif"" font-size=""14.00"">a</text>
</g>
<!-- b -->
<g id=""node2"" class=""node""><title>b</title>
<ellipse fill=""none"" stroke=""black"" cx=""27"" cy=""-18"" rx=""27"" ry=""18""/>
<text text-anchor=""middle"" x=""27"" y=""-14.3"" font-family=""Times New Roman,serif"" font-size=""14.00"">b</text>
</g>
<!-- a->b -->
<g id=""edge1"" class=""edge""><title>a->b</title>
<path fill=""none"" stroke=""black"" d=""M27,-71.6966C27,-63.9827 27,-54.7125 27,-46.1124""/>
<polygon fill=""black"" stroke=""black"" points=""30.5001,-46.1043 27,-36.1043 23.5001,-46.1044 30.5001,-46.1043""/>
</g>
</g>
</svg>
";
}
}
| |
/*
* 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 directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DirectConnect.Model
{
/// <summary>
/// A virtual interface (VLAN) transmits the traffic between the AWS Direct Connect location
/// and the customer.
/// </summary>
public partial class CreatePublicVirtualInterfaceResponse : AmazonWebServiceResponse
{
private string _amazonAddress;
private int? _asn;
private string _authKey;
private string _connectionId;
private string _customerAddress;
private string _customerRouterConfig;
private string _location;
private string _ownerAccount;
private List<RouteFilterPrefix> _routeFilterPrefixes = new List<RouteFilterPrefix>();
private string _virtualGatewayId;
private string _virtualInterfaceId;
private string _virtualInterfaceName;
private VirtualInterfaceState _virtualInterfaceState;
private string _virtualInterfaceType;
private int? _vlan;
/// <summary>
/// Gets and sets the property AmazonAddress.
/// </summary>
public string AmazonAddress
{
get { return this._amazonAddress; }
set { this._amazonAddress = value; }
}
// Check to see if AmazonAddress property is set
internal bool IsSetAmazonAddress()
{
return this._amazonAddress != null;
}
/// <summary>
/// Gets and sets the property Asn.
/// </summary>
public int Asn
{
get { return this._asn.GetValueOrDefault(); }
set { this._asn = value; }
}
// Check to see if Asn property is set
internal bool IsSetAsn()
{
return this._asn.HasValue;
}
/// <summary>
/// Gets and sets the property AuthKey.
/// </summary>
public string AuthKey
{
get { return this._authKey; }
set { this._authKey = value; }
}
// Check to see if AuthKey property is set
internal bool IsSetAuthKey()
{
return this._authKey != null;
}
/// <summary>
/// Gets and sets the property ConnectionId.
/// </summary>
public string ConnectionId
{
get { return this._connectionId; }
set { this._connectionId = value; }
}
// Check to see if ConnectionId property is set
internal bool IsSetConnectionId()
{
return this._connectionId != null;
}
/// <summary>
/// Gets and sets the property CustomerAddress.
/// </summary>
public string CustomerAddress
{
get { return this._customerAddress; }
set { this._customerAddress = value; }
}
// Check to see if CustomerAddress property is set
internal bool IsSetCustomerAddress()
{
return this._customerAddress != null;
}
/// <summary>
/// Gets and sets the property CustomerRouterConfig.
/// <para>
/// Information for generating the customer router configuration.
/// </para>
/// </summary>
public string CustomerRouterConfig
{
get { return this._customerRouterConfig; }
set { this._customerRouterConfig = value; }
}
// Check to see if CustomerRouterConfig property is set
internal bool IsSetCustomerRouterConfig()
{
return this._customerRouterConfig != null;
}
/// <summary>
/// Gets and sets the property Location.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
// Check to see if Location property is set
internal bool IsSetLocation()
{
return this._location != null;
}
/// <summary>
/// Gets and sets the property OwnerAccount.
/// </summary>
public string OwnerAccount
{
get { return this._ownerAccount; }
set { this._ownerAccount = value; }
}
// Check to see if OwnerAccount property is set
internal bool IsSetOwnerAccount()
{
return this._ownerAccount != null;
}
/// <summary>
/// Gets and sets the property RouteFilterPrefixes.
/// </summary>
public List<RouteFilterPrefix> RouteFilterPrefixes
{
get { return this._routeFilterPrefixes; }
set { this._routeFilterPrefixes = value; }
}
// Check to see if RouteFilterPrefixes property is set
internal bool IsSetRouteFilterPrefixes()
{
return this._routeFilterPrefixes != null && this._routeFilterPrefixes.Count > 0;
}
/// <summary>
/// Gets and sets the property VirtualGatewayId.
/// </summary>
public string VirtualGatewayId
{
get { return this._virtualGatewayId; }
set { this._virtualGatewayId = value; }
}
// Check to see if VirtualGatewayId property is set
internal bool IsSetVirtualGatewayId()
{
return this._virtualGatewayId != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceId.
/// </summary>
public string VirtualInterfaceId
{
get { return this._virtualInterfaceId; }
set { this._virtualInterfaceId = value; }
}
// Check to see if VirtualInterfaceId property is set
internal bool IsSetVirtualInterfaceId()
{
return this._virtualInterfaceId != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceName.
/// </summary>
public string VirtualInterfaceName
{
get { return this._virtualInterfaceName; }
set { this._virtualInterfaceName = value; }
}
// Check to see if VirtualInterfaceName property is set
internal bool IsSetVirtualInterfaceName()
{
return this._virtualInterfaceName != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceState.
/// </summary>
public VirtualInterfaceState VirtualInterfaceState
{
get { return this._virtualInterfaceState; }
set { this._virtualInterfaceState = value; }
}
// Check to see if VirtualInterfaceState property is set
internal bool IsSetVirtualInterfaceState()
{
return this._virtualInterfaceState != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceType.
/// </summary>
public string VirtualInterfaceType
{
get { return this._virtualInterfaceType; }
set { this._virtualInterfaceType = value; }
}
// Check to see if VirtualInterfaceType property is set
internal bool IsSetVirtualInterfaceType()
{
return this._virtualInterfaceType != null;
}
/// <summary>
/// Gets and sets the property Vlan.
/// </summary>
public int Vlan
{
get { return this._vlan.GetValueOrDefault(); }
set { this._vlan = value; }
}
// Check to see if Vlan property is set
internal bool IsSetVlan()
{
return this._vlan.HasValue;
}
}
}
| |
// 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.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// RuntimeHelpers
// This class defines a set of static methods that provide support for compilers.
//
using Internal.Reflection.Augments;
using Internal.Reflection.Core.NonPortable;
using Internal.Runtime.Augments;
using System.Runtime;
using System.Runtime.Serialization;
using System.Threading;
using Debug = System.Diagnostics.Debug;
namespace System.Runtime.CompilerServices
{
public static class RuntimeHelpers
{
[Intrinsic]
public static void InitializeArray(Array array, RuntimeFieldHandle fldHandle)
{
// We only support this intrinsic when it occurs within a well-defined IL sequence.
// If a call to this method occurs within the recognized sequence, codegen must expand the IL sequence completely.
// For any other purpose, the API is currently unsupported.
// https://github.com/dotnet/corert/issues/364
throw new PlatformNotSupportedException();
}
public static void RunClassConstructor(RuntimeTypeHandle type)
{
if (type.IsNull)
throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized);
IntPtr pStaticClassConstructionContext = RuntimeAugments.Callbacks.TryGetStaticClassConstructionContext(type);
if (pStaticClassConstructionContext == IntPtr.Zero)
return;
unsafe
{
ClassConstructorRunner.EnsureClassConstructorRun((StaticClassConstructionContext*)pStaticClassConstructionContext);
}
}
public static void RunModuleConstructor(ModuleHandle module)
{
if (module.AssociatedModule == null)
throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized);
ReflectionAugments.ReflectionCoreCallbacks.RunModuleConstructor(module.AssociatedModule);
}
public static object GetObjectValue(object obj)
{
if (obj == null)
return null;
EETypePtr eeType = obj.EETypePtr;
if ((!eeType.IsValueType) || eeType.IsPrimitive)
return obj;
return RuntimeImports.RhMemberwiseClone(obj);
}
public new static bool Equals(object o1, object o2)
{
if (o1 == o2)
return true;
if ((o1 == null) || (o2 == null))
return false;
// If it's not a value class, don't compare by value
if (!o1.EETypePtr.IsValueType)
return false;
// Make sure they are the same type.
if (o1.EETypePtr != o2.EETypePtr)
return false;
return RuntimeImports.RhCompareObjectContentsAndPadding(o1, o2);
}
#if !FEATURE_SYNCTABLE
private const int HASHCODE_BITS = 26;
private const int MASK_HASHCODE = (1 << HASHCODE_BITS) - 1;
#endif
[ThreadStatic]
private static int t_hashSeed;
internal static int GetNewHashCode()
{
int multiplier = Environment.CurrentManagedThreadId * 4 + 5;
// Every thread has its own generator for hash codes so that we won't get into a situation
// where two threads consistently give out the same hash codes.
// Choice of multiplier guarantees period of 2**32 - see Knuth Vol 2 p16 (3.2.1.2 Theorem A).
t_hashSeed = t_hashSeed * multiplier + 1;
return t_hashSeed;
}
public static unsafe int GetHashCode(object o)
{
#if FEATURE_SYNCTABLE
return ObjectHeader.GetHashCode(o);
#else
if (o == null)
return 0;
fixed (IntPtr* pEEType = &o.m_pEEType)
{
int* pSyncBlockIndex = (int*)((byte*)pEEType - 4); // skipping exactly 4 bytes for the SyncTableEntry (exactly 4 bytes not a pointer size).
int hash = *pSyncBlockIndex & MASK_HASHCODE;
if (hash == 0)
return MakeHashCode(o, pSyncBlockIndex);
else
return hash;
}
#endif
}
#if !FEATURE_SYNCTABLE
private static unsafe int MakeHashCode(Object o, int* pSyncBlockIndex)
{
int hash = GetNewHashCode() & MASK_HASHCODE;
if (hash == 0)
hash = 1;
while (true)
{
int oldIndex = Volatile.Read(ref *pSyncBlockIndex);
int currentHash = oldIndex & MASK_HASHCODE;
if (currentHash != 0)
{
// Someone else set the hash code.
hash = currentHash;
break;
}
int newIndex = oldIndex | hash;
if (Interlocked.CompareExchange(ref *pSyncBlockIndex, newIndex, oldIndex) == oldIndex)
break;
// If we get here someone else modified the header. They may have set the hash code, or maybe some
// other bits. Let's try again.
}
return hash;
}
#endif
public static int OffsetToStringData
{
get
{
// Number of bytes from the address pointed to by a reference to
// a String to the first 16-bit character in the String.
// This property allows C#'s fixed statement to work on Strings.
return string.FIRST_CHAR_OFFSET;
}
}
[ThreadStatic]
private static unsafe byte* t_sufficientStackLimit;
public static unsafe void EnsureSufficientExecutionStack()
{
byte* limit = t_sufficientStackLimit;
if (limit == null)
limit = GetSufficientStackLimit();
byte* currentStackPtr = (byte*)(&limit);
if (currentStackPtr < limit)
throw new InsufficientExecutionStackException();
}
public static unsafe bool TryEnsureSufficientExecutionStack()
{
byte* limit = t_sufficientStackLimit;
if (limit == null)
limit = GetSufficientStackLimit();
byte* currentStackPtr = (byte*)(&limit);
return (currentStackPtr >= limit);
}
[MethodImpl(MethodImplOptions.NoInlining)] // Only called once per thread, no point in inlining.
private static unsafe byte* GetSufficientStackLimit()
{
IntPtr lower, upper;
RuntimeImports.RhGetCurrentThreadStackBounds(out lower, out upper);
// Compute the limit used by EnsureSufficientExecutionStack and cache it on the thread. This minimum
// stack size should be sufficient to allow a typical non-recursive call chain to execute, including
// potential exception handling and garbage collection.
#if BIT64
const int MinExecutionStackSize = 128 * 1024;
#else
const int MinExecutionStackSize = 64 * 1024;
#endif
byte* limit = (((byte*)upper - (byte*)lower > MinExecutionStackSize)) ?
((byte*)lower + MinExecutionStackSize) : ((byte*)upper);
return (t_sufficientStackLimit = limit);
}
[Intrinsic]
public static bool IsReferenceOrContainsReferences<T>()
{
var pEEType = EETypePtr.EETypePtrOf<T>();
return !pEEType.IsValueType || pEEType.HasPointers;
}
[Intrinsic]
public static bool IsReference<T>()
{
var pEEType = EETypePtr.EETypePtrOf<T>();
return !pEEType.IsValueType;
}
// Returns true iff the object has a component size;
// i.e., is variable length like System.String or Array.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool ObjectHasComponentSize(object obj)
{
Debug.Assert(obj != null);
return obj.EETypePtr.ComponentSize != 0;
}
// Constrained Execution Regions APIs are NOP's because we do not support CERs in .NET Core at all.
public static void ProbeForSufficientStack() { }
public static void PrepareConstrainedRegions() { }
public static void PrepareConstrainedRegionsNoOP() { }
public static void PrepareMethod(RuntimeMethodHandle method) { }
public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) { }
public static void PrepareContractedDelegate(Delegate d) { }
public static void PrepareDelegate(Delegate d)
{
if (d == null)
throw new ArgumentNullException(nameof(d));
}
public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object userData)
{
if (code == null)
throw new ArgumentNullException(nameof(code));
if (backoutCode == null)
throw new ArgumentNullException(nameof(backoutCode));
bool exceptionThrown = false;
try
{
code(userData);
}
catch
{
exceptionThrown = true;
throw;
}
finally
{
backoutCode(userData, exceptionThrown);
}
}
public delegate void TryCode(object userData);
public delegate void CleanupCode(object userData, bool exceptionThrown);
public static object GetUninitializedObject(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type), SR.ArgumentNull_Type);
}
if(!type.IsRuntimeImplemented())
{
throw new SerializationException(SR.Format(SR.Serialization_InvalidType, type.ToString()));
}
if (type.HasElementType || type.IsGenericParameter)
{
throw new ArgumentException(SR.Argument_InvalidValue);
}
if (type.ContainsGenericParameters)
{
throw new MemberAccessException(SR.Acc_CreateGeneric);
}
if (type.IsCOMObject)
{
throw new NotSupportedException(SR.NotSupported_ManagedActivation);
}
EETypePtr eeTypePtr = type.TypeHandle.ToEETypePtr();
if (eeTypePtr == EETypePtr.EETypePtrOf<string>())
{
throw new ArgumentException(SR.Argument_NoUninitializedStrings);
}
if (eeTypePtr.IsAbstract)
{
throw new MemberAccessException(SR.Acc_CreateAbst);
}
if (eeTypePtr.IsByRefLike)
{
throw new NotSupportedException(SR.NotSupported_ByRefLike);
}
if (eeTypePtr.IsNullable)
{
return GetUninitializedObject(RuntimeTypeUnifier.GetRuntimeTypeForEEType(eeTypePtr.NullableType));
}
// Triggering the .cctor here is slightly different than desktop/CoreCLR, which
// decide based on BeforeFieldInit, but we don't want to include BeforeFieldInit
// in EEType just for this API to behave slightly differently.
RunClassConstructor(type.TypeHandle);
return RuntimeImports.RhNewObject(eeTypePtr);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyBoolean
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// BoolModel operations.
/// </summary>
public partial class BoolModel : IServiceOperations<AutoRestBoolTestService>, IBoolModel
{
/// <summary>
/// Initializes a new instance of the BoolModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public BoolModel(AutoRestBoolTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestBoolTestService
/// </summary>
public AutoRestBoolTestService Client { get; private set; }
/// <summary>
/// Get true Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetTrueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetTrue", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/true").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Set Boolean value true
/// </summary>
/// <param name='boolBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutTrueWithHttpMessagesAsync(bool boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("boolBody", boolBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutTrue", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/true").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(boolBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get false Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetFalseWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetFalse", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/false").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Set Boolean value false
/// </summary>
/// <param name='boolBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutFalseWithHttpMessagesAsync(bool boolBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("boolBody", boolBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutFalse", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/false").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(boolBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get null Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/null").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get invalid Boolean value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<bool?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bool/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<bool?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<bool?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: error.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace CloudFoundry.Dropsonde.Events {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Error {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_events_Error__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::CloudFoundry.Dropsonde.Events.Error, global::CloudFoundry.Dropsonde.Events.Error.Builder> internal__static_events_Error__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static Error() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgtlcnJvci5wcm90bxIGZXZlbnRzIjYKBUVycm9yEg4KBnNvdXJjZRgBIAIo",
"CRIMCgRjb2RlGAIgAigFEg8KB21lc3NhZ2UYAyACKAlCUQohb3JnLmNsb3Vk",
"Zm91bmRyeS5kcm9wc29uZGUuZXZlbnRzQgxFcnJvckZhY3RvcnmqAh1DbG91",
"ZEZvdW5kcnkuRHJvcHNvbmRlLkV2ZW50cw=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_events_Error__Descriptor = Descriptor.MessageTypes[0];
internal__static_events_Error__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::CloudFoundry.Dropsonde.Events.Error, global::CloudFoundry.Dropsonde.Events.Error.Builder>(internal__static_events_Error__Descriptor,
new string[] { "Source", "Code", "Message", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Error : pb::GeneratedMessage<Error, Error.Builder> {
private Error() { }
private static readonly Error defaultInstance = new Error().MakeReadOnly();
private static readonly string[] _errorFieldNames = new string[] { "code", "message", "source" };
private static readonly uint[] _errorFieldTags = new uint[] { 16, 26, 10 };
public static Error DefaultInstance {
get { return defaultInstance; }
}
public override Error DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override Error ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::CloudFoundry.Dropsonde.Events.Proto.Error.internal__static_events_Error__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<Error, Error.Builder> InternalFieldAccessors {
get { return global::CloudFoundry.Dropsonde.Events.Proto.Error.internal__static_events_Error__FieldAccessorTable; }
}
public const int SourceFieldNumber = 1;
private bool hasSource;
private string source_ = "";
public bool HasSource {
get { return hasSource; }
}
public string Source {
get { return source_; }
}
public const int CodeFieldNumber = 2;
private bool hasCode;
private int code_;
public bool HasCode {
get { return hasCode; }
}
public int Code {
get { return code_; }
}
public const int MessageFieldNumber = 3;
private bool hasMessage;
private string message_ = "";
public bool HasMessage {
get { return hasMessage; }
}
public string Message {
get { return message_; }
}
public override bool IsInitialized {
get {
if (!hasSource) return false;
if (!hasCode) return false;
if (!hasMessage) return false;
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _errorFieldNames;
if (hasSource) {
output.WriteString(1, field_names[2], Source);
}
if (hasCode) {
output.WriteInt32(2, field_names[0], Code);
}
if (hasMessage) {
output.WriteString(3, field_names[1], Message);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasSource) {
size += pb::CodedOutputStream.ComputeStringSize(1, Source);
}
if (hasCode) {
size += pb::CodedOutputStream.ComputeInt32Size(2, Code);
}
if (hasMessage) {
size += pb::CodedOutputStream.ComputeStringSize(3, Message);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static Error ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Error ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Error ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Error ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Error ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Error ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Error ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static Error ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static Error ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Error ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private Error MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(Error prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<Error, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(Error cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private Error result;
private Error PrepareBuilder() {
if (resultIsReadOnly) {
Error original = result;
result = new Error();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override Error MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::CloudFoundry.Dropsonde.Events.Error.Descriptor; }
}
public override Error DefaultInstanceForType {
get { return global::CloudFoundry.Dropsonde.Events.Error.DefaultInstance; }
}
public override Error BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is Error) {
return MergeFrom((Error) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(Error other) {
if (other == global::CloudFoundry.Dropsonde.Events.Error.DefaultInstance) return this;
PrepareBuilder();
if (other.HasSource) {
Source = other.Source;
}
if (other.HasCode) {
Code = other.Code;
}
if (other.HasMessage) {
Message = other.Message;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_errorFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _errorFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasSource = input.ReadString(ref result.source_);
break;
}
case 16: {
result.hasCode = input.ReadInt32(ref result.code_);
break;
}
case 26: {
result.hasMessage = input.ReadString(ref result.message_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasSource {
get { return result.hasSource; }
}
public string Source {
get { return result.Source; }
set { SetSource(value); }
}
public Builder SetSource(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasSource = true;
result.source_ = value;
return this;
}
public Builder ClearSource() {
PrepareBuilder();
result.hasSource = false;
result.source_ = "";
return this;
}
public bool HasCode {
get { return result.hasCode; }
}
public int Code {
get { return result.Code; }
set { SetCode(value); }
}
public Builder SetCode(int value) {
PrepareBuilder();
result.hasCode = true;
result.code_ = value;
return this;
}
public Builder ClearCode() {
PrepareBuilder();
result.hasCode = false;
result.code_ = 0;
return this;
}
public bool HasMessage {
get { return result.hasMessage; }
}
public string Message {
get { return result.Message; }
set { SetMessage(value); }
}
public Builder SetMessage(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasMessage = true;
result.message_ = value;
return this;
}
public Builder ClearMessage() {
PrepareBuilder();
result.hasMessage = false;
result.message_ = "";
return this;
}
}
static Error() {
object.ReferenceEquals(global::CloudFoundry.Dropsonde.Events.Proto.Error.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
using DotNetStarter.Abstractions;
using DotNetStarter.Abstractions.Internal;
using DotNetStarter.Configure;
using DotNetStarter.Locators;
using DotNetStarter.StartupBuilderTests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Text;
namespace DotNetStarter.StartupBuilderTests
{
[TestClass]
public class StartupBuilderTests
{
[TestMethod]
public void ShouldChangeRegistrationLifecycle()
{
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(assemblies =>
{
assemblies
.WithAssemblyFromType<RegistrationConfiguration>()
.WithAssembliesFromTypes(typeof(StartupBuilder), typeof(TestFooImport));
})
.ConfigureStartupModules(modules =>
{
modules
.RemoveStartupModule<BadStartupModule>()
.RemoveConfigureModule<BadConfigureModule>();
})
.OverrideDefaults(defaults =>
{
defaults
.UseRegistrationModifier(new MockRegistrationModifier())
.UseLogger(new StringLogger(LogLevel.Info));
})
.Build(useApplicationContext: false)
.Run();
var sut1 = builder.StartupContext.Locator.Get<TestFooImport>();
var sut2 = builder.StartupContext.Locator.Get<TestFooImport>();
Assert.AreSame(sut1, sut2);
Assert.AreEqual(sut1.DateTime, sut2.DateTime);
}
[TestMethod]
public void ShouldRegisterDescriptorCollection()
{
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(a => a.WithNoAssemblyScanning())
.ConfigureRegistrations(r =>
{
r.TryAddSingleton(new TestFooImport());
r.AddSingleton<TestFooImport, TestFooImport>();
//todo: test more usages
})
.Build(useApplicationContext: false)
.Run();
var sut1 = builder.StartupContext.Locator.Get<TestFooImport>();
var sut2 = builder.StartupContext.Locator.Get<TestFooImport>();
Assert.AreSame(sut1, sut2);
}
[TestMethod]
public void ShouldExecuteFromDefaults()
{
// only using discoverable assemblies to remove bad modules for unit testing
StartupBuilder.Create().Build(useDiscoverableAssemblies: true).Run();
Assert.IsNotNull(ApplicationContext.Default);
Internal.UnitTestHelper.ResetApplication();
}
[TestMethod]
public void ShouldRegisterConfigureModuleViaConfiguration()
{
var sut = new ManualLocatorConfigure();
var builder = StartupBuilder.Create();
builder
.ConfigureAssemblies(assemblies =>
{
assemblies
.WithAssembliesFromTypes(typeof(StringLogger), typeof(RegistrationConfiguration))
.WithAssemblyFromType<DryIocLocatorFactory>();
})
.ConfigureStartupModules(modules =>
{
modules
.ConfigureLocatorModuleCollection(configureModules =>
{
configureModules.Add(sut);
})
.RemoveConfigureModule<BadConfigureModule>();
})
.Build(useApplicationContext: false)
.Run();
Assert.IsTrue(sut.Executed);
}
[TestMethod]
public void ShouldRegisterModuleViaConfiguration()
{
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(assemblies =>
{
assemblies
.WithDiscoverableAssemblies(new[] { typeof(StringLogger).Assembly(), typeof(RegistrationConfiguration).Assembly() })
.WithAssemblyFromType<DryIocLocatorFactory>()
.WithAssemblyFromType<BadConfigureModule>();
})
.ConfigureStartupModules(modules =>
{
modules
.ConfigureStartupModuleCollection(collection =>
{
collection.AddType<TestStartupModule>();
})
.RemoveConfigureModule<BadConfigureModule>()
.RemoveStartupModule<BadStartupModule>()
;
})
.Build(useApplicationContext: false)
.Run();
var sut = builder.StartupContext.Locator.GetAll<IStartupModule>().OfType<TestStartupModule>().FirstOrDefault();
Assert.IsTrue(sut.Executed);
}
[TestMethod]
public void ShouldRunWithNoScanning()
{
var sut = new ManualLocatorConfigure();
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(a => a.WithNoAssemblyScanning())
.ConfigureStartupModules(modules =>
{
modules
.ConfigureLocatorModuleCollection(configureModules =>
{
configureModules.Add(sut);
});
})
.Build(useApplicationContext: false)
.Run();
Assert.IsTrue(sut.Executed);
Assert.IsFalse(builder.StartupContext.Configuration.Assemblies.Any());
}
[TestMethod]
public void ShouldStartupAndResolveType()
{
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(assemblies =>
{
assemblies
.WithAssemblyFromType<RegistrationConfiguration>()
.WithAssembliesFromTypes(typeof(StartupBuilder), typeof(BadStartupModule));
})
.ConfigureStartupModules(modules =>
{
modules
.RemoveStartupModule<BadStartupModule>()
.RemoveConfigureModule<BadConfigureModule>();
})
.OverrideDefaults(defaults =>
{
defaults
.UseLogger(new StringLogger(LogLevel.Info));
})
.Build(useApplicationContext: false)
.Run();
builder.Build(useApplicationContext: false).Run();
var logger = builder.StartupContext.Locator.Get<IStartupLogger>();
Assert.IsTrue(builder.StartupContext.Configuration.Environment.IsEnvironment("UnitTest1"));
Assert.IsNotNull(logger);
//Assert.IsNotNull(new TestFooImport().FooImport.Service);
// ran when test assembly is initialized
Assert.IsTrue(SetupTests.TestImport is NullReferenceException);
}
[TestMethod]
public void ShouldStartupUsingAppContext()
{
Assert.IsFalse(ApplicationContext.Started);
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(assemblies =>
{
assemblies
.WithAssemblyFromType<RegistrationConfiguration>()
.WithAssembly(typeof(StartupBuilderTests).Assembly())
.WithAssembliesFromTypes(typeof(StartupBuilder));
})
.ConfigureStartupModules(modules =>
{
modules
.RemoveStartupModule<BadStartupModule>()
.RemoveConfigureModule<BadConfigureModule>()
.RemoveConfigureModule<ConfigureTestFooService>();
})
.OverrideDefaults(defaults =>
{
defaults
.UseLogger(new StringLogger(LogLevel.Info));
})
.Run(); // omitting build for default
builder.Build().Run(); // 2nd pass shouldn't do anything
var logger = builder.StartupContext.Locator.Get<IStartupLogger>();
Assert.IsNotNull(logger);
Assert.IsNotNull(ApplicationContext.Default);
Assert.IsTrue(ApplicationContext.Started);
Assert.AreEqual(builder.StartupContext, ApplicationContext.Default);
Internal.UnitTestHelper.ResetApplication();
}
[TestMethod]
public void ShouldThrowErrorAccessingStaticContextDuringInit()
{
string sut = string.Empty;
try
{
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(assemblies => assemblies.WithNoAssemblyScanning())
.ConfigureStartupModules(modules =>
{
modules
.ConfigureLocatorModuleCollection(c => c.Add(new FaultyAccessStaticDuringStartup()))
.RemoveStartupModule<BadStartupModule>()
.RemoveConfigureModule<BadConfigureModule>();
})
.Run();
}
catch (Exception e)
{
sut = e.Message;
}
Assert.IsTrue(sut.StartsWith("Do not access"));
Internal.UnitTestHelper.ResetApplication();
}
[TestMethod]
public void ShouldThrowNoHandlerException()
{
string sut = string.Empty;
try
{
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(a => a.WithNoAssemblyScanning())
.OverrideDefaults(d => d.UseStartupHandler(c => null))
.Build(useApplicationContext: false)
.Run();
}
catch (Exception e)
{
sut = e.Message;
}
Assert.IsTrue(sut.Contains("was called but no startup handler was defined"));
}
[TestMethod]
public void ShouldUseEnvironmentItemsAcrossModules()
{
var builder = CreateTestBuilder();
builder
.ConfigureAssemblies(a => a.WithNoAssemblyScanning())
.ConfigureStartupModules(modules =>
{
modules
.ConfigureLocatorModuleCollection(l => l.Add(new ConfigureModuleAddEnvironmentItem()))
.ConfigureStartupModuleCollection(s => s.AddType<StartupModuleUseEnvironmentItem>());
})
.OverrideDefaults(defaults =>
{
defaults
.UseRegistrationModifier(new MockRegistrationModifier())
.UseLogger(new StringLogger(LogLevel.Info));
})
.Build(useApplicationContext: false)
.Run();
var sut = builder.StartupContext.Configuration.Environment.Items.Get<StringBuilder>().ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
Assert.IsTrue(sut.Count == 2);
Assert.IsTrue(sut[0] == "Configured Item!");
Assert.IsTrue(sut[1] == "Started Item!");
}
private StartupBuilder CreateTestBuilder() => StartupBuilder.Create()
.UseEnvironment(new StartupEnvironment("UnitTest1", ""))
.OverrideDefaults(d => d.UseLocatorRegistryFactory(new DryIocLocatorFactory()));
}
}
| |
#pragma warning disable 1591
namespace Braintree
{
public enum ValidationErrorCode
{
GOOGLE_WALLET_CARD_EXPIRATION_MONTH_IS_REQUIRED = 83701,
GOOGLE_WALLET_CARD_EXPIRATION_YEAR_IS_REQUIRED = 83702,
GOOGLE_WALLET_CARD_NUMBER_IS_REQUIRED = 83703,
GOOGLE_WALLET_CARD_NUMBER_IS_INVALID = 83704,
GOOGLE_WALLET_CARD_GOOGLE_TRANSACTION_ID_IS_REQUIRED = 83705,
GOOGLE_WALLET_CARD_SOURCE_CARD_TYPE_IS_REQUIRED = 83706,
GOOGLE_WALLET_CARD_SOURCE_CARD_LAST_FOUR_IS_REQUIRED = 83707,
ADDRESS_CANNOT_BE_BLANK = 81801,
ADDRESS_COMPANY_IS_INVALID = 91821,
ADDRESS_COMPANY_IS_TOO_LONG = 81802,
ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED = 91814,
ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED = 91816,
ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED = 91817,
ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED = 91803,
ADDRESS_EXTENDED_ADDRESS_IS_INVALID = 91823,
ADDRESS_EXTENDED_ADDRESS_IS_TOO_LONG = 81804,
ADDRESS_FIRST_NAME_IS_INVALID = 91819,
ADDRESS_FIRST_NAME_IS_TOO_LONG = 81805,
ADDRESS_INCONSISTENT_COUNTRY = 91815,
ADDRESS_IS_INVALID = 91828,
ADDRESS_LAST_NAME_IS_INVALID = 91820,
ADDRESS_LAST_NAME_IS_TOO_LONG = 81806,
ADDRESS_LOCALITY_IS_INVALID = 91824,
ADDRESS_LOCALITY_IS_TOO_LONG = 81807,
ADDRESS_POSTAL_CODE_INVALID_CHARACTERS = 81813,
ADDRESS_POSTAL_CODE_IS_INVALID = 91826,
ADDRESS_POSTAL_CODE_IS_REQUIRED = 81808,
ADDRESS_POSTAL_CODE_IS_REQUIRED_FOR_CARD_BRAND_AND_PROCESSOR = 81828,
ADDRESS_POSTAL_CODE_IS_TOO_LONG = 81809,
ADDRESS_REGION_IS_INVALID = 91825,
ADDRESS_REGION_IS_TOO_LONG = 81810,
ADDRESS_STATE_IS_INVALID_FOR_SELLER_PROTECTION = 81827,
ADDRESS_STREET_ADDRESS_IS_INVALID = 91822,
ADDRESS_STREET_ADDRESS_IS_REQUIRED = 81811,
ADDRESS_STREET_ADDRESS_IS_TOO_LONG = 81812,
ADDRESS_TOO_MANY_ADDRESSES_PER_CUSTOMER = 91818,
APPLE_PAY_CARDS_ARE_NOT_ACCEPTED = 83501,
APPLE_PAY_CUSTOMER_ID_IS_REQUIRED_FOR_VAULTING = 83502,
APPLE_PAY_TOKEN_IS_IN_USE = 93503,
APPLE_PAY_PAYMENT_METHOD_NONCE_CONSUMED = 93504,
APPLE_PAY_PAYMENT_METHOD_NONCE_UNKNOWN = 93505,
APPLE_PAY_PAYMENT_METHOD_NONCE_LOCKED = 93506,
APPLE_PAY_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 83518,
APPLE_PAY_CANNOT_UPDATE_APPLE_PAY_CARD_USING_PAYMENT_METHOD_NONCE = 93507,
APPLE_PAY_NUMBER_IS_REQUIRED = 93508,
APPLE_PAY_EXPIRATION_MONTH_IS_REQUIRED = 93509,
APPLE_PAY_EXPIRATION_YEAR_IS_REQUIRED = 93510,
APPLE_PAY_CRYPTOGRAM_IS_REQUIRED = 93511,
APPLE_PAY_DECRYPTION_FAILED = 83512,
APPLE_PAY_DISABLED = 93513,
APPLE_PAY_MERCHANT_NOT_CONFIGURED = 93514,
APPLE_PAY_MERCHANT_KEYS_ALREADY_CONFIGURED = 93515,
APPLE_PAY_MERCHANT_KEYS_NOT_CONFIGURED = 93516,
APPLE_PAY_CERTIFICATE_INVALID = 93517,
APPLE_PAY_CERTIFICATE_MISMATCH = 93519,
APPLE_PAY_INVALID_TOKEN = 83520,
APPLE_PAY_PRIVATE_KEY_MISMATCH = 93521,
APPLE_PAY_KEY_MISMATCH_STORING_CERTIFICATE = 93522,
AUTHORIZATION_FINGERPRINT_INVALID_CREATED_AT = 93204,
AUTHORIZATION_FINGERPRINT_INVALID_FORMAT = 93202,
AUTHORIZATION_FINGERPRINT_INVALID_PUBLIC_KEY = 93205,
AUTHORIZATION_FINGERPRINT_INVALID_SIGNATURE = 93206,
AUTHORIZATION_FINGERPRINT_MISSING_FINGERPRINT = 93201,
AUTHORIZATION_FINGERPRINT_OPTIONS_NOT_ALLOWED_WITHOUT_CUSTOMER = 93207,
AUTHORIZATION_FINGERPRINT_SIGNATURE_REVOKED = 93203,
CLIENT_TOKEN_CUSTOMER_DOES_NOT_EXIST = 92804,
CLIENT_TOKEN_FAIL_ON_DUPLICATE_PAYMENT_METHOD_REQUIRES_CUSTOMER_ID = 92803,
CLIENT_TOKEN_MAKE_DEFAULT_REQUIRES_CUSTOMER_ID = 92801,
CLIENT_TOKEN_MERCHANT_ACCOUNT_DOES_NOT_EXIST = 92807,
CLIENT_TOKEN_PROXY_MERCHANT_DOES_NOT_EXIST = 92805,
CLIENT_TOKEN_UNSUPPORTED_VERSION = 92806,
CLIENT_TOKEN_VERIFY_CARD_REQUIRES_CUSTOMER_ID = 92802,
CREDIT_CARD_BILLING_ADDRESS_CONFLICT = 91701,
CREDIT_CARD_BILLING_ADDRESS_FORMAT_IS_INVALID = 91744,
CREDIT_CARD_BILLING_ADDRESS_ID_IS_INVALID = 91702,
CREDIT_CARD_CANNOT_UPDATE_CARD_USING_PAYMENT_METHOD_NONCE = 91735,
CREDIT_CARD_CARDHOLDER_NAME_IS_TOO_LONG = 81723,
CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED = 81703,
CREDIT_CARD_CREDIT_CARD_TYPE_IS_NOT_ACCEPTED_BY_SUBSCRIPTION_MERCHANT_ACCOUNT = 81718,
CREDIT_CARD_CUSTOMER_ID_IS_INVALID = 91705,
CREDIT_CARD_CUSTOMER_ID_IS_REQUIRED = 91704,
CREDIT_CARD_CVV_IS_INVALID = 81707,
CREDIT_CARD_CVV_IS_REQUIRED = 81706,
CREDIT_CARD_CVV_VERIFICATION_FAILED = 81736,
CREDIT_CARD_DUPLICATE_CARD_EXISTS = 81724,
CREDIT_CARD_EXPIRATION_DATE_CONFLICT = 91708,
CREDIT_CARD_EXPIRATION_DATE_IS_INVALID = 81710,
CREDIT_CARD_EXPIRATION_DATE_IS_REQUIRED = 81709,
CREDIT_CARD_EXPIRATION_DATE_YEAR_IS_INVALID = 81711,
CREDIT_CARD_EXPIRATION_MONTH_IS_INVALID = 81712,
CREDIT_CARD_EXPIRATION_YEAR_IS_INVALID = 81713,
CREDIT_CARD_INVALID_PARAMS_FOR_CREDIT_CARD_UPDATE = 91745,
CREDIT_CARD_INVALID_VENMO_SDK_PAYMENT_METHOD_CODE = 91727,
CREDIT_CARD_NUMBER_HAS_INVALID_LENGTH = 81716,
CREDIT_CARD_NUMBER_IS_INVALID = 81715,
CREDIT_CARD_NUMBER_IS_PROHIBITED = 81750,
CREDIT_CARD_NUMBER_IS_REQUIRED = 81714,
CREDIT_CARD_NUMBER_LENGTH_IS_INVALID = 81716,
CREDIT_CARD_NUMBER_MUST_BE_TEST_NUMBER = 81717,
CREDIT_CARD_OPTIONS_UPDATE_EXISTING_TOKEN_IS_INVALID = 91723,
CREDIT_CARD_OPTIONS_UPDATE_EXISTING_TOKEN_NOT_ALLOWED = 91729,
CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_CANNOT_BE_NEGATIVE = 91739,
CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_FORMAT_IS_INVALID = 91740,
CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_IS_TOO_LARGE = 91752,
CREDIT_CARD_OPTIONS_VERIFICATION_AMOUNT_NOT_SUPPORTED_BY_PROCESSOR = 91741,
CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_ID_IS_INVALID = 91728,
CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_IS_FORBIDDEN = 91743,
CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_IS_SUSPENDED = 91742,
CREDIT_CARD_OPTIONS_VERIFICATION_MERCHANT_ACCOUNT_CANNOT_BE_SUB_MERCHANT_ACCOUNT = 91755,
CREDIT_CARD_OPTIONS_VERIFICATION_ACCOUNT_TYPE_IS_INVALID = 91757,
CREDIT_CARD_OPTIONS_VERIFICATION_ACCOUNT_TYPE_NOT_SUPPORTED = 91758,
CREDIT_CARD_OPTIONS_VERIFICATION_INVALID_PRESENTMENT_CURRENCY = 91760,
CREDIT_CARD_PAYMENT_METHOD_CONFLICT = 81725,
CREDIT_CARD_PAYMENT_METHOD_IS_NOT_A_CREDIT_CARD = 91738,
CREDIT_CARD_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 91734,
CREDIT_CARD_PAYMENT_METHOD_NONCE_CONSUMED = 91731,
CREDIT_CARD_PAYMENT_METHOD_NONCE_LOCKED = 91733,
CREDIT_CARD_PAYMENT_METHOD_NONCE_UNKNOWN = 91732,
CREDIT_CARD_POSTAL_CODE_VERIFICATION_FAILED = 81737,
CREDIT_CARD_TOKEN_FORMAT_IS_INVALID = 91718,
CREDIT_CARD_TOKEN_INVALID = 91718,
CREDIT_CARD_TOKEN_IS_IN_USE = 91719,
CREDIT_CARD_TOKEN_IS_NOT_ALLOWED = 91721,
CREDIT_CARD_TOKEN_IS_REQUIRED = 91722,
CREDIT_CARD_TOKEN_IS_TOO_LONG = 91720,
CREDIT_CARD_VENMO_SDK_PAYMENT_METHOD_CODE_CARD_TYPE_IS_NOT_ACCEPTED = 91726,
CREDIT_CARD_VERIFICATION_NOT_SUPPORTED_ON_THIS_MERCHANT_ACCOUNT = 91730,
CUSTOMER_COMPANY_IS_TOO_LONG = 81601,
CUSTOMER_CUSTOM_FIELD_IS_INVALID = 91602,
CUSTOMER_CUSTOM_FIELD_IS_TOO_LONG = 81603,
CUSTOMER_EMAIL_FORMAT_IS_INVALID = 81604,
CUSTOMER_EMAIL_IS_INVALID = 81604,
CUSTOMER_EMAIL_IS_REQUIRED = 81606,
CUSTOMER_EMAIL_IS_TOO_LONG = 81605,
CUSTOMER_FAX_IS_TOO_LONG = 81607,
CUSTOMER_FIRST_NAME_IS_TOO_LONG = 81608,
CUSTOMER_ID_IS_INVALID = 91610,
CUSTOMER_ID_IS_IN_USE = 91609,
CUSTOMER_ID_IS_NOT_ALLOWED = 91611,
CUSTOMER_ID_IS_REQUIRED = 91613,
CUSTOMER_ID_IS_TOO_LONG = 91612,
CUSTOMER_LAST_NAME_IS_TOO_LONG = 81613,
CUSTOMER_PHONE_IS_TOO_LONG = 81614,
CUSTOMER_VAULTED_PAYMENT_INSTRUMENT_NONCE_BELONGS_TO_DIFFERENT_CUSTOMER = 91617,
CUSTOMER_WEBSITE_FORMAT_IS_INVALID = 81616,
CUSTOMER_WEBSITE_IS_INVALID = 81616,
CUSTOMER_WEBSITE_IS_TOO_LONG = 81615,
DESCRIPTOR_DYNAMIC_DESCRIPTORS_DISABLED = 92203,
DESCRIPTOR_INTERNATIONAL_NAME_FORMAT_IS_INVALID = 92204,
DESCRIPTOR_INTERNATIONAL_PHONE_FORMAT_IS_INVALID = 92205,
DESCRIPTOR_NAME_FORMAT_IS_INVALID = 92201,
DESCRIPTOR_PHONE_FORMAT_IS_INVALID = 92202,
DESCRIPTOR_URL_FORMAT_IS_INVALID = 92206,
DISPUTE_CAN_ONLY_ADD_EVIDENCE_TO_OPEN_DISPUTE = 95701,
DISPUTE_CAN_ONLY_REMOVE_EVIDENCE_FROM_OPEN_DISPUTE = 95702,
DISPUTE_CAN_ONLY_ADD_EVIDENCE_DOCUMENT_TO_DISPUTE = 95703,
DISPUTE_CAN_ONLY_ACCEPT_OPEN_DISPUTE = 95704,
DISPUTE_CAN_ONLY_FINALIZE_OPEN_DISPUTE = 95705,
DISPUTE_CAN_ONLY_CREATE_EVIDENCE_WITH_VALID_CATEGORY = 95706,
DISPUTE_EVIDENCE_CONTENT_DATE_INVALID = 95707,
DISPUTE_EVIDENCE_CONTENT_TOO_LONG = 95708,
DISPUTE_EVIDENCE_CONTENT_ARN_TOO_LONG = 95709,
DISPUTE_EVIDENCE_CONTENT_PHONE_TOO_LONG = 95710,
DISPUTE_EVIDENCE_CATEGORY_TEXT_ONLY = 95711,
DISPUTE_EVIDENCE_CATEGORY_DOCUMENT_ONLY = 95712,
DISPUTE_EVIDENCE_CATEGORY_NOT_FOR_REASON_CODE = 95713,
DISPUTE_EVIDENCE_CATEGORY_DUPLICATE = 95714,
DISPUTE_EVIDENCE_CONTENT_EMAIL_INVALID = 95715,
DISPUTE_DIGITAL_GOODS_MISSING_EVIDENCE = 95720,
DISPUTE_DIGITAL_GOODS_MISSING_DOWNLOAD_DATE = 95721,
DISPUTE_NON_DISPUTED_PRIOR_TRANSACTION_EVIDENCE_MISSING_ARN = 95722,
DISPUTE_NON_DISPUTED_PRIOR_TRANSACTION_EVIDENCE_MISSING_DATE = 95723,
DISPUTE_RECURRING_TRANSACTION_EVIDENCE_MISSING_DATE = 95724,
DISPUTE_RECURRING_TRANSACTION_EVIDENCE_MISSING_ARN = 95725,
DISPUTE_VALID_EVIDENCE_REQUIRED_TO_FINALIZE = 95726,
DOCUMENT_UPLOAD_KIND_IS_INVALID = 84901,
DOCUMENT_UPLOAD_FILE_IS_TOO_LARGE = 84902,
DOCUMENT_UPLOAD_FILE_TYPE_IS_INVALID = 84903,
DOCUMENT_UPLOAD_FILE_IS_MALFORMED_OR_ENCRYPTED = 84904,
DOCUMENT_UPLOAD_FILE_IS_TOO_LONG = 84905,
DOCUMENT_UPLOAD_FILE_IS_EMPTY = 84906,
EXCHANGE_RATE_QUOTE_ID_IS_TOO_LONG = 915229,
FAILED_AUTH_ADJUSTMENT_ALLOW_RETRY = 95603,
FAILED_AUTH_ADJUSTMENT_HARD_DECLINE = 95602,
FINAL_AUTH_SUBMIT_FOR_SETTLEMENT_FOR_DIFFERENT_AMOUNT = 95601,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_ARRIVAL_AIRPORT_CODE_IS_TOO_LONG = 96301,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_ARRIVAL_TIME_FORMAT_IS_INVALID = 96302,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_CARRIER_CODE_IS_TOO_LONG = 96303,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_CONJUNCTION_TICKET_IS_TOO_LONG = 96304,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_COUPON_NUMBER_IS_TOO_LONG = 96305,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_DEPARTURE_AIRPORT_CODE_IS_TOO_LONG = 96306,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_DEPARTURE_TIME_FORMAT_IS_INVALID = 96307,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_EXCHANGE_TICKET_IS_TOO_LONG = 96308,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_FARE_AMOUNT_CANNOT_BE_NEGATIVE = 96309,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_FARE_AMOUNT_FORMAT_IS_INVALID = 96310,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_FARE_AMOUNT_IS_TOO_LARGE = 96311,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_FARE_BASIS_CODE_IS_TOO_LONG = 96312,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_FEE_AMOUNT_CANNOT_BE_NEGATIVE = 96313,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_FEE_AMOUNT_FORMAT_IS_INVALID = 96314,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_FEE_AMOUNT_IS_TOO_LARGE = 96315,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_SERVICE_CLASS_IS_TOO_LONG = 96316,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_TAX_AMOUNT_CANNOT_BE_NEGATIVE = 96317,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_TAX_AMOUNT_FORMAT_IS_INVALID = 96318,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_TAX_AMOUNT_IS_TOO_LARGE = 96319,
INDUSTRY_DATA_LEG_TRAVEL_FLIGHT_TICKET_NUMBER_IS_TOO_LONG = 96320,
INDUSTRY_DATA_INDUSTRY_TYPE_IS_INVALID = 93401,
INDUSTRY_DATA_LODGING_EMPTY_DATA = 93402,
INDUSTRY_DATA_LODGING_FOLIO_NUMBER_IS_INVALID = 93403,
INDUSTRY_DATA_LODGING_CHECK_IN_DATE_IS_INVALID = 93404,
INDUSTRY_DATA_LODGING_CHECK_OUT_DATE_IS_INVALID = 93405,
INDUSTRY_DATA_LODGING_CHECK_OUT_DATE_MUST_FOLLOW_CHECK_IN_DATE = 93406,
INDUSTRY_DATA_LODGING_UNKNOWN_DATA_FIELD = 93407,
INDUSTRY_DATA_LODGING_ROOM_RATE_MUST_BE_GREATER_THAN_ZERO = 93433,
INDUSTRY_DATA_LODGING_ROOM_RATE_FORMAT_IS_INVALID = 93434,
INDUSTRY_DATA_LODGING_ROOM_RATE_IS_TOO_LARGE = 93435,
INDUSTRY_DATA_LODGING_ROOM_TAX_MUST_BE_GREATER_THAN_ZERO = 93436,
INDUSTRY_DATA_LODGING_ROOM_TAX_FORMAT_IS_INVALID = 93437,
INDUSTRY_DATA_LODGING_ROOM_TAX_IS_TOO_LARGE = 93438,
INDUSTRY_DATA_LODGING_NO_SHOW_INDICATOR_IS_INVALID = 93439,
INDUSTRY_DATA_LODGING_ADVANCED_DEPOSIT_INDICATOR_IS_INVALID = 93440,
INDUSTRY_DATA_LODGING_FIRE_SAFETY_INDICATOR_IS_INVALID = 93441,
INDUSTRY_DATA_LODGING_PROPERTY_PHONE_IS_INVALID = 93442,
INDUSTRY_DATA_TRAVEL_CRUISE_EMPTY_DATA = 93408,
INDUSTRY_DATA_TRAVEL_CRUISE_UNKNOWN_DATA_FIELD = 93409,
INDUSTRY_DATA_TRAVEL_CRUISE_TRAVEL_PACKAGE_IS_INVALID = 93410,
INDUSTRY_DATA_TRAVEL_CRUISE_DEPARTURE_DATE_IS_INVALID = 93411,
INDUSTRY_DATA_TRAVEL_CRUISE_LODGING_CHECK_IN_DATE_IS_INVALID = 93412,
INDUSTRY_DATA_TRAVEL_CRUISE_LODGING_CHECK_OUT_DATE_IS_INVALID = 93413,
INDUSTRY_DATA_TRAVEL_FLIGHT_EMPTY_DATA = 93414,
INDUSTRY_DATA_TRAVEL_FLIGHT_UNKNOWN_DATA_FIELD = 93415,
INDUSTRY_DATA_TRAVEL_FLIGHT_CUSTOMER_CODE_IS_TOO_LONG = 93416,
INDUSTRY_DATA_TRAVEL_FLIGHT_FARE_AMOUNT_CANNOT_BE_NEGATIVE = 93417,
INDUSTRY_DATA_TRAVEL_FLIGHT_FARE_AMOUNT_FORMAT_IS_INVALID = 93418,
INDUSTRY_DATA_TRAVEL_FLIGHT_FARE_AMOUNT_IS_TOO_LARGE = 93419,
INDUSTRY_DATA_TRAVEL_FLIGHT_FEE_AMOUNT_CANNOT_BE_NEGATIVE = 93420,
INDUSTRY_DATA_TRAVEL_FLIGHT_FEE_AMOUNT_FORMAT_IS_INVALID = 93421,
INDUSTRY_DATA_TRAVEL_FLIGHT_FEE_AMOUNT_IS_TOO_LARGE = 93422,
INDUSTRY_DATA_TRAVEL_FLIGHT_ISSUED_DATE_FORMAT_IS_INVALID = 93423,
INDUSTRY_DATA_TRAVEL_FLIGHT_ISSUING_CARRIER_CODE_IS_TOO_LONG = 93424,
INDUSTRY_DATA_TRAVEL_FLIGHT_PASSENGER_MIDDLE_INITIAL_IS_TOO_LONG = 93425,
INDUSTRY_DATA_TRAVEL_FLIGHT_RESTRICTED_TICKET_IS_REQUIRED = 93426,
INDUSTRY_DATA_TRAVEL_FLIGHT_TAX_AMOUNT_CANNOT_BE_NEGATIVE = 93427,
INDUSTRY_DATA_TRAVEL_FLIGHT_TAX_AMOUNT_FORMAT_IS_INVALID = 93428,
INDUSTRY_DATA_TRAVEL_FLIGHT_TAX_AMOUNT_IS_TOO_LARGE = 93429,
INDUSTRY_DATA_TRAVEL_FLIGHT_TICKET_NUMBER_IS_TOO_LONG = 93430,
INDUSTRY_DATA_TRAVEL_FLIGHT_LEGS_EXPECTED = 93431,
INDUSTRY_DATA_TRAVEL_FLIGHT_TOO_MANY_LEGS = 93432,
INDUSTRY_DATA_ADDITIONAL_CHARGE_KIND_IS_INVALID = 96601,
INDUSTRY_DATA_ADDITIONAL_CHARGE_KIND_MUST_BE_UNIQUE = 96602,
INDUSTRY_DATA_ADDITIONAL_CHARGE_AMOUNT_MUST_BE_GREATER_THAN_ZERO = 96603,
INDUSTRY_DATA_ADDITIONAL_CHARGE_AMOUNT_FORMAT_IS_INVALID = 96604,
INDUSTRY_DATA_ADDITIONAL_CHARGE_AMOUNT_IS_TOO_LARGE = 96605,
INDUSTRY_DATA_ADDITIONAL_CHARGE_AMOUNT_IS_REQUIRED = 96606,
TRANSACTION_DISCOUNT_AMOUNT_FORMAT_IS_INVALID = 915159,
TRANSACTION_DISCOUNT_AMOUNT_CANNOT_BE_NEGATIVE = 915160,
TRANSACTION_DISCOUNT_AMOUNT_IS_TOO_LARGE = 915161,
TRANSACTION_SHIPPING_AMOUNT_FORMAT_IS_INVALID = 915162,
TRANSACTION_SHIPPING_AMOUNT_CANNOT_BE_NEGATIVE = 915163,
TRANSACTION_SHIPPING_AMOUNT_IS_TOO_LARGE = 915164,
TRANSACTION_SHIPPING_PHONE_NUMBER_IS_INVALID = 915204,
TRANSACTION_SHIPS_FROM_POSTAL_CODE_IS_TOO_LONG = 915165,
TRANSACTION_SHIPS_FROM_POSTAL_CODE_IS_INVALID = 915166,
TRANSACTION_SHIPS_FROM_POSTAL_CODE_INVALID_CHARACTERS = 915167,
TRANSACTION_SCA_EXEMPTION_REQUEST_INVALID = 915213,
TRANSACTION_LINE_ITEM_COMMODITY_CODE_IS_TOO_LONG = 95801,
TRANSACTION_LINE_ITEM_DESCRIPTION_IS_TOO_LONG = 95803,
TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_FORMAT_IS_INVALID = 95804,
TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_IS_TOO_LARGE = 95805,
TRANSACTION_LINE_ITEM_DISCOUNT_AMOUNT_CANNOT_BE_NEGATIVE = 95806,
TRANSACTION_LINE_ITEM_KIND_IS_INVALID = 95807,
TRANSACTION_LINE_ITEM_KIND_IS_REQUIRED = 95808,
TRANSACTION_LINE_ITEM_NAME_IS_REQUIRED = 95822,
TRANSACTION_LINE_ITEM_NAME_IS_TOO_LONG = 95823,
TRANSACTION_LINE_ITEM_PRODUCT_CODE_IS_TOO_LONG = 95809,
TRANSACTION_LINE_ITEM_QUANTITY_FORMAT_IS_INVALID = 95810,
TRANSACTION_LINE_ITEM_QUANTITY_IS_REQUIRED = 95811,
TRANSACTION_LINE_ITEM_QUANTITY_IS_TOO_LARGE = 95812,
TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_FORMAT_IS_INVALID = 95813,
TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_IS_REQUIRED = 95814,
TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_IS_TOO_LARGE = 95815,
TRANSACTION_LINE_ITEM_TOTAL_AMOUNT_MUST_BE_GREATER_THAN_ZERO = 95816,
TRANSACTION_LINE_ITEM_UNIT_AMOUNT_FORMAT_IS_INVALID = 95817,
TRANSACTION_LINE_ITEM_UNIT_AMOUNT_IS_REQUIRED = 95818,
TRANSACTION_LINE_ITEM_UNIT_AMOUNT_IS_TOO_LARGE = 95819,
TRANSACTION_LINE_ITEM_UNIT_AMOUNT_MUST_BE_GREATER_THAN_ZERO = 95820,
TRANSACTION_LINE_ITEM_UNIT_OF_MEASURE_IS_TOO_LONG = 95821,
TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_FORMAT_IS_INVALID = 95824,
TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_IS_TOO_LARGE = 95825,
TRANSACTION_LINE_ITEM_UNIT_TAX_AMOUNT_CANNOT_BE_NEGATIVE = 95826,
TRANSACTION_LINE_ITEM_TAX_AMOUNT_FORMAT_IS_INVALID = 95827,
TRANSACTION_LINE_ITEM_TAX_AMOUNT_IS_TOO_LARGE = 95828,
TRANSACTION_LINE_ITEM_TAX_AMOUNT_CANNOT_BE_NEGATIVE = 95829,
TRANSACTION_EXTERNAL_VAULT_STATUS_IS_INVALID = 915175,
TRANSACTION_EXTERNAL_VAULT_STATUS_WITH_PREVIOUS_NETWORK_TRANSACTION_ID_IS_INVALID = 915177,
TRANSACTION_EXTERNAL_VAULT_PREVIOUS_NETWORK_TRANSACTION_ID_IS_INVALID = 915179,
// NEXT_MAJOR_VERSION remove invalid card type error, the API no longer returns this error
TRANSACTION_EXTERNAL_VAULT_CARD_TYPE_IS_INVALID = 915178,
MERCHANT_COUNTRY_CANNOT_BE_BLANK = 83603,
MERCHANT_COUNTRY_CODE_ALPHA2_IS_INVALID = 93607,
MERCHANT_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED = 93606,
MERCHANT_COUNTRY_CODE_ALPHA3_IS_INVALID = 93605,
MERCHANT_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED = 93604,
MERCHANT_COUNTRY_CODE_NUMERIC_IS_INVALID = 93609,
MERCHANT_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED = 93608,
MERCHANT_COUNTRY_NAME_IS_INVALID = 93611,
MERCHANT_COUNTRY_NAME_IS_NOT_ACCEPTED = 93610,
MERCHANT_CURRENCIES_ARE_INVALID = 93614,
MERCHANT_EMAIL_FORMAT_IS_INVALID = 93602,
MERCHANT_EMAIL_IS_REQUIRED = 83601,
MERCHANT_INCONSISTENT_COUNTRY = 93612,
MERCHANT_PAYMENT_METHODS_ARE_INVALID = 93613,
MERCHANT_PAYMENT_METHODS_ARE_NOT_ALLOWED = 93615,
MERCHANT_MERCHANT_ACCOUNT_EXISTS_FOR_CURRENCY = 93616,
MERCHANT_CURRENCY_IS_REQUIRED = 93617,
MERCHANT_CURRENCY_IS_INVALID = 93618,
MERCHANT_NO_MERCHANT_ACCOUNTS = 93619,
MERCHANT_MERCHANT_ACCOUNT_EXISTS_FOR_ID = 93620,
MERCHANT_MERCHANT_ACCOUNT_NOT_AUTH_ONBOARDED = 93621,
MERCHANT_ACCOUNT_CANNOT_BE_UPDATED = 82674,
MERCHANT_ACCOUNT_ID_CANNOT_BE_UPDATED = 82675,
MERCHANT_ACCOUNT_ID_FORMAT_IS_INVALID = 82603,
MERCHANT_ACCOUNT_ID_IS_IN_USE = 82604,
MERCHANT_ACCOUNT_ID_IS_NOT_ALLOWED = 82605,
MERCHANT_ACCOUNT_ID_IS_TOO_LONG = 82602,
MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_CANNOT_BE_UPDATED = 82676,
MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_INVALID = 82607,
MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_ID_IS_REQUIRED = 82606,
MERCHANT_ACCOUNT_MASTER_MERCHANT_ACCOUNT_MUST_BE_ACTIVE = 82608,
MERCHANT_ACCOUNT_TOS_ACCEPTED_IS_REQUIRED = 82610,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ACCOUNT_NUMBER_IS_INVALID = 82670,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ACCOUNT_NUMBER_IS_REQUIRED = 82614,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_COMPANY_NAME_IS_INVALID = 82631,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_COMPANY_NAME_IS_REQUIRED_WITH_TAX_ID = 82633,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DATE_OF_BIRTH_IS_INVALID = 82663,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DATE_OF_BIRTH_IS_REQUIRED = 82612,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED = 82626,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_MASTER_CARD_MATCH = 82622,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_OFAC = 82621,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_FAILED_KYC = 82623,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_SSN_INVALID = 82624,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_DECLINED_SSN_MATCHES_DECEASED = 82625,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_EMAIL_ADDRESS_IS_INVALID = 82616,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_EMAIL_ADDRESS_IS_REQUIRED = 82665,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_FIRST_NAME_IS_INVALID = 82627,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_FIRST_NAME_IS_REQUIRED = 82609,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_LAST_NAME_IS_INVALID = 82628,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_LAST_NAME_IS_REQUIRED = 82611,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_PHONE_IS_INVALID = 82636,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ROUTING_NUMBER_IS_INVALID = 82635,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ROUTING_NUMBER_IS_REQUIRED = 82613,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_SSN_IS_INVALID = 82615,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_IS_INVALID = 82632,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_IS_REQUIRED_WITH_COMPANY_NAME = 82634,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_TAX_ID_MUST_BE_BLANK = 82673,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_LOCALITY_IS_REQUIRED = 82618,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_POSTAL_CODE_IS_INVALID = 82630,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_POSTAL_CODE_IS_REQUIRED = 82619,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_REGION_IS_INVALID = 82664,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_REGION_IS_REQUIRED = 82620,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_STREET_ADDRESS_IS_INVALID = 82629,
MERCHANT_ACCOUNT_APPLICANT_DETAILS_ADDRESS_STREET_ADDRESS_IS_REQUIRED = 82617,
MERCHANT_ACCOUNT_BUSINESS_DBA_NAME_IS_INVALID = 82646,
MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_INVALID = 82677,
MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_INVALID = 82647,
MERCHANT_ACCOUNT_BUSINESS_LEGAL_NAME_IS_REQUIRED_WITH_TAX_ID = 82669,
MERCHANT_ACCOUNT_BUSINESS_TAX_ID_IS_REQUIRED_WITH_LEGAL_NAME = 82648,
MERCHANT_ACCOUNT_BUSINESS_TAX_ID_MUST_BE_BLANK = 82672,
MERCHANT_ACCOUNT_BUSINESS_ADDRESS_STREET_ADDRESS_IS_INVALID = 82685,
MERCHANT_ACCOUNT_BUSINESS_ADDRESS_POSTAL_CODE_IS_INVALID = 82686,
MERCHANT_ACCOUNT_BUSINESS_ADDRESS_REGION_IS_INVALID = 82684,
MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_INVALID = 82671,
MERCHANT_ACCOUNT_FUNDING_ACCOUNT_NUMBER_IS_REQUIRED = 82641,
MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_INVALID = 82649,
MERCHANT_ACCOUNT_FUNDING_ROUTING_NUMBER_IS_REQUIRED = 82640,
MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_INVALID = 82679,
MERCHANT_ACCOUNT_FUNDING_DESTINATION_IS_REQUIRED = 82678,
MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_INVALID = 82681,
MERCHANT_ACCOUNT_FUNDING_EMAIL_IS_REQUIRED = 82680,
MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_INVALID = 82683,
MERCHANT_ACCOUNT_FUNDING_MOBILE_PHONE_IS_REQUIRED = 82682,
MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_INVALID = 82644,
MERCHANT_ACCOUNT_INDIVIDUAL_FIRST_NAME_IS_REQUIRED = 82637,
MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_INVALID = 82645,
MERCHANT_ACCOUNT_INDIVIDUAL_LAST_NAME_IS_REQUIRED = 82638,
MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_INVALID = 82666,
MERCHANT_ACCOUNT_INDIVIDUAL_DATE_OF_BIRTH_IS_REQUIRED = 82639,
MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_INVALID = 82643,
MERCHANT_ACCOUNT_INDIVIDUAL_EMAIL_IS_REQUIRED = 82667,
MERCHANT_ACCOUNT_INDIVIDUAL_PHONE_IS_INVALID = 82656,
MERCHANT_ACCOUNT_INDIVIDUAL_SSN_IS_INVALID = 82642,
MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_REQUIRED = 82657,
MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_STREET_ADDRESS_IS_INVALID = 82661,
MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_LOCALITY_IS_REQUIRED = 82658,
MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_INVALID = 82662,
MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_POSTAL_CODE_IS_REQUIRED = 82659,
MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_INVALID = 82668,
MERCHANT_ACCOUNT_INDIVIDUAL_ADDRESS_REGION_IS_REQUIRED = 82660,
NO_NET_AMOUNT_TO_PERFORM_AUTH_ADJUSTMENT = 95606,
OAUTH_INVALID_GRANT = 93801,
OAUTH_INVALID_CREDENTIALS = 93802,
OAUTH_INVALID_SCOPE = 93803,
OAUTH_INVALID_REQUEST = 93804,
OAUTH_UNSUPPORTED_GRANT_TYPE = 93805,
PAYMENT_METHOD_CANNOT_FORWARD_PAYMENT_METHOD_TYPE = 93106,
PAYMENT_METHOD_CUSTOMER_ID_IS_INVALID = 93105,
PAYMENT_METHOD_CUSTOMER_ID_IS_REQUIRED = 93104,
PAYMENT_METHOD_NONCE_IS_INVALID = 93102,
PAYMENT_METHOD_NONCE_IS_REQUIRED = 93103,
PAYMENT_METHOD_PAYMENT_METHOD_PARAMS_ARE_REQUIRED = 93101,
PAYMENT_METHOD_PAYMENT_METHOD_NONCE_CONSUMED = 93107,
PAYMENT_METHOD_PAYMENT_METHOD_NONCE_UNKNOWN = 93108,
PAYMENT_METHOD_PAYMENT_METHOD_NONCE_LOCKED = 93109,
PAYMENT_METHOD_NO_LONGER_SUPPORTED = 93117,
PAYMENT_METHOD_OPTIONS_INVALID_US_BANK_ACCOUNT_VERIFICATION_METHOD = 93121,
PAYPAL_ACCOUNT_AUTH_EXPIRED = 92911,
PAYPAL_ACCOUNT_CANNOT_HAVE_BOTH_ACCESS_TOKEN_AND_CONSENT_CODE = 82903,
PAYPAL_ACCOUNT_CANNOT_HAVE_FUNDING_SOURCE_WITHOUT_ACCESS_TOKEN = 92912,
PAYPAL_ACCOUNT_CANNOT_UPDATE_PAYPAL_ACCOUNT_USING_PAYMENT_METHOD_NONCE = 92914,
PAYPAL_ACCOUNT_CANNOT_VAULT_ONE_TIME_USE_PAYPAL_ACCOUNT = 82902,
PAYPAL_ACCOUNT_CONSENT_CODE_OR_ACCESS_TOKEN_IS_REQUIRED = 82901,
PAYPAL_ACCOUNT_CUSTOMER_ID_IS_REQUIRED_FOR_VAULTING = 82905,
PAYPAL_ACCOUNT_INVALID_FUNDING_SOURCE_SELECTION = 92913,
PAYPAL_ACCOUNT_INVALID_PARAMS_FOR_PAYPAL_ACCOUNT_UPDATE = 92915,
PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_CONSUMED = 92907,
PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_LOCKED = 92909,
PAYPAL_ACCOUNT_PAYMENT_METHOD_NONCE_UNKNOWN = 92908,
PAYPAL_ACCOUNT_PAYPAL_ACCOUNTS_ARE_NOT_ACCEPTED = 82904,
PAYPAL_ACCOUNT_PAYPAL_COMMUNICATION_ERROR = 92910,
PAYPAL_ACCOUNT_TOKEN_IS_IN_USE = 92906,
PROCESSOR_DOES_NOT_SUPPORT_AUTH_ADJUSTMENT = 915222,
PROCESSOR_DOES_NOT_SUPPORT_INCREMENTAL_AUTH = 915220,
PROCESSOR_DOES_NOT_SUPPORT_PARTIAL_AUTH_REVERSAL = 915221,
SETTLEMENT_BATCH_SUMMARY_CUSTOM_FIELD_IS_INVALID = 82303,
SETTLEMENT_BATCH_SUMMARY_SETTLEMENT_DATE_IS_INVALID = 82302,
SETTLEMENT_BATCH_SUMMARY_SETTLEMENT_DATE_IS_REQUIRED = 82301,
SUBSCRIPTION_BILLING_DAY_OF_MONTH_CANNOT_BE_UPDATED = 91918,
SUBSCRIPTION_BILLING_DAY_OF_MONTH_IS_INVALID = 91914,
SUBSCRIPTION_BILLING_DAY_OF_MONTH_MUST_BE_NUMERIC = 91913,
SUBSCRIPTION_CANNOT_ADD_DUPLICATE_ADDON_OR_DISCOUNT = 91911,
SUBSCRIPTION_CANNOT_EDIT_CANCELED_SUBSCRIPTION = 81901,
SUBSCRIPTION_CANNOT_EDIT_EXPIRED_SUBSCRIPTION = 81910,
SUBSCRIPTION_CANNOT_EDIT_PRICE_CHANGING_FIELDS_ON_PAST_DUE_SUBSCRIPTION = 91920,
SUBSCRIPTION_FIRST_BILLING_DATE_CANNOT_BE_IN_THE_PAST = 91916,
SUBSCRIPTION_FIRST_BILLING_DATE_CANNOT_BE_UPDATED = 91919,
SUBSCRIPTION_FIRST_BILLING_DATE_IS_INVALID = 91915,
SUBSCRIPTION_ID_IS_IN_USE = 81902,
SUBSCRIPTION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES = 91908,
SUBSCRIPTION_INCONSISTENT_START_DATE = 91917,
SUBSCRIPTION_INVALID_REQUEST_FORMAT = 91921,
SUBSCRIPTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_INSTRUMENT_TYPE = 91930,
SUBSCRIPTION_MERCHANT_ACCOUNT_ID_IS_INVALID = 91901,
SUBSCRIPTION_MISMATCH_CURRENCY_ISO_CODE = 91923,
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK = 91912,
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_IS_TOO_SMALL = 91909,
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO = 91907,
SUBSCRIPTION_NUMBER_OF_BILLING_CYCLES_MUST_BE_NUMERIC = 91906,
SUBSCRIPTION_PAYMENT_METHOD_NONCE_INSTRUMENT_TYPE_DOES_NOT_SUPPORT_SUBSCRIPTIONS = 91929,
SUBSCRIPTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED = 91902,
SUBSCRIPTION_PAYMENT_METHOD_TOKEN_INSTRUMENT_TYPE_DOES_NOT_SUPPORT_SUBSCRIPTIONS = 91928,
SUBSCRIPTION_PAYMENT_METHOD_TOKEN_IS_INVALID = 91903,
SUBSCRIPTION_PAYMENT_METHOD_TOKEN_NOT_ASSOCIATED_WITH_CUSTOMER = 91905,
SUBSCRIPTION_PLAN_BILLING_FREQUENCY_CANNOT_BE_UPDATED = 91922,
SUBSCRIPTION_PLAN_ID_IS_INVALID = 91904,
SUBSCRIPTION_PRICE_CANNOT_BE_BLANK = 81903,
SUBSCRIPTION_PRICE_FORMAT_IS_INVALID = 81904,
SUBSCRIPTION_PRICE_IS_TOO_LARGE = 81923,
SUBSCRIPTION_STATUS_IS_CANCELED = 81905,
SUBSCRIPTION_TOKEN_FORMAT_IS_INVALID = 81906,
SUBSCRIPTION_TRIAL_DURATION_FORMAT_IS_INVALID = 81907,
SUBSCRIPTION_TRIAL_DURATION_IS_REQUIRED = 81908,
SUBSCRIPTION_TRIAL_DURATION_UNIT_IS_INVALID = 81909,
SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_INVALID = 92025,
SUBSCRIPTION_MODIFICATION_AMOUNT_CANNOT_BE_BLANK = 92003,
SUBSCRIPTION_MODIFICATION_AMOUNT_IS_INVALID = 92002,
SUBSCRIPTION_MODIFICATION_AMOUNT_IS_TOO_LARGE = 92023,
SUBSCRIPTION_MODIFICATION_CANNOT_EDIT_MODIFICATIONS_ON_PAST_DUE_SUBSCRIPTION = 92022,
SUBSCRIPTION_MODIFICATION_CANNOT_UPDATE_AND_REMOVE = 92015,
SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INCORRECT_KIND = 92020,
SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_INVALID = 92011,
SUBSCRIPTION_MODIFICATION_EXISTING_ID_IS_REQUIRED = 92012,
SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_INCORRECT_KIND = 92021,
SUBSCRIPTION_MODIFICATION_ID_TO_REMOVE_IS_NOT_PRESENT = 92016,
SUBSCRIPTION_MODIFICATION_INCONSISTENT_NUMBER_OF_BILLING_CYCLES = 92018,
SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_INVALID = 92013,
SUBSCRIPTION_MODIFICATION_INHERITED_FROM_ID_IS_REQUIRED = 92014,
SUBSCRIPTION_MODIFICATION_MISSING = 92024,
SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_CANNOT_BE_BLANK = 92017,
SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_IS_INVALID = 92005,
SUBSCRIPTION_MODIFICATION_NUMBER_OF_BILLING_CYCLES_MUST_BE_GREATER_THAN_ZERO = 92019,
SUBSCRIPTION_MODIFICATION_QUANTITY_CANNOT_BE_BLANK = 92004,
SUBSCRIPTION_MODIFICATION_QUANTITY_IS_INVALID = 92001,
SUBSCRIPTION_MODIFICATION_QUANTITY_MUST_BE_GREATER_THAN_ZERO = 92010,
SUBSCRIPTION_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 91924,
SUBSCRIPTION_PAYMENT_METHOD_NONCE_IS_INVALID = 91925,
SUBSCRIPTION_PAYMENT_METHOD_NONCE_NOT_ASSOCIATED_WITH_CUSTOMER = 91926,
SUBSCRIPTION_PAYMENT_METHOD_NONCE_UNVAULTED_CARD_IS_NOT_ACCEPTED = 91927,
TRANSACTION_AMOUNT_CANNOT_BE_NEGATIVE = 81501,
TRANSACTION_AMOUNT_DOES_NOT_MATCH3_D_SECURE_AMOUNT = 91585,
TRANSACTION_AMOUNT_FORMAT_IS_INVALID = 81503,
TRANSACTION_AMOUNT_IS_INVALID = 81503,
TRANSACTION_AMOUNT_IS_REQUIRED = 81502,
TRANSACTION_AMOUNT_IS_TOO_LARGE = 81528,
TRANSACTION_AMOUNT_MUST_BE_GREATER_THAN_ZERO = 81531,
TRANSACTION_AMOUNT_NOT_SUPPORTED_BY_PROCESSOR = 815193,
TRANSACTION_BILLING_ADDRESS_CONFLICT = 91530,
TRANSACTION_BILLING_PHONE_NUMBER_IS_INVALID = 915206,
TRANSACTION_CANNOT_BE_VOIDED = 91504,
TRANSACTION_CANNOT_CANCEL_RELEASE = 91562,
TRANSACTION_CANNOT_CLONE_CREDIT = 91543,
TRANSACTION_CANNOT_CLONE_MARKETPLACE_TRANSACTION = 915137,
TRANSACTION_CANNOT_CLONE_TRANSACTION_WITH_PAYPAL_ACCOUNT = 91573,
TRANSACTION_CANNOT_CLONE_TRANSACTION_WITH_VAULT_CREDIT_CARD = 91540,
TRANSACTION_CANNOT_CLONE_UNSUCCESSFUL_TRANSACTION = 91542,
TRANSACTION_CANNOT_CLONE_VOICE_AUTHORIZATIONS = 91541,
TRANSACTION_CANNOT_HOLD_IN_ESCROW = 91560,
TRANSACTION_CANNOT_PARTIALLY_REFUND_ESCROWED_TRANSACTION = 91563,
TRANSACTION_CANNOT_REFUND_CREDIT = 91505,
TRANSACTION_CANNOT_REFUND_SETTLING_TRANSACTION = 91574,
TRANSACTION_CANNOT_REFUND_UNLESS_SETTLED = 91506,
TRANSACTION_CANNOT_REFUND_WITH_PENDING_MERCHANT_ACCOUNT = 91559,
TRANSACTION_CANNOT_REFUND_WITH_SUSPENDED_MERCHANT_ACCOUNT = 91538,
TRANSACTION_CANNOT_RELEASE_FROM_ESCROW = 91561,
TRANSACTION_CANNOT_SIMULATE_SETTLEMENT = 91575,
TRANSACTION_CANNOT_SUBMIT_FOR_PARTIAL_SETTLEMENT = 915103,
TRANSACTION_CANNOT_SUBMIT_FOR_SETTLEMENT = 91507,
TRANSACTION_CANNOT_UPDATE_DETAILS_NOT_SUBMITTED_FOR_SETTLEMENT = 915129,
TRANSACTION_CHANNEL_IS_TOO_LONG = 91550,
TRANSACTION_CREDIT_CARD_IS_REQUIRED = 91508,
TRANSACTION_CUSTOM_FIELD_IS_INVALID = 91526,
TRANSACTION_CUSTOM_FIELD_IS_TOO_LONG = 81527,
TRANSACTION_CUSTOMER_DEFAULT_PAYMENT_METHOD_CARD_TYPE_IS_NOT_ACCEPTED = 81509,
TRANSACTION_CUSTOMER_DOES_NOT_HAVE_CREDIT_CARD = 91511,
TRANSACTION_CUSTOMER_ID_IS_INVALID = 91510,
TRANSACTION_HAS_ALREADY_BEEN_REFUNDED = 91512,
TRANSACTION_IS_NOT_ELIGIBLE_FOR_ADJUSTMENT = 915219,
TRANSACTION_TOO_MANY_LINE_ITEMS = 915157,
TRANSACTION_LINE_ITEMS_EXPECTED = 915158,
TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_MATCH3_D_SECURE_MERCHANT_ACCOUNT = 91584,
TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_MOTO = 91558,
TRANSACTION_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_REFUNDS = 91547,
TRANSACTION_MERCHANT_ACCOUNT_ID_DOES_NOT_MATCH_SUBSCRIPTION = 915180,
TRANSACTION_MERCHANT_ACCOUNT_ID_IS_INVALID = 91513,
TRANSACTION_MERCHANT_ACCOUNT_IS_SUSPENDED = 91514,
TRANSACTION_MUST_BE_IN_STATE_AUTHORIZED = 915218,
TRANSACTION_OPTIONS_PAY_PAL_CUSTOM_FIELD_TOO_LONG = 91580,
TRANSACTION_OPTIONS_SUBMIT_FOR_SETTLEMENT_IS_REQUIRED_FOR_CLONING = 91544,
TRANSACTION_OPTIONS_SUBMIT_FOR_SETTLEMENT_IS_REQUIRED_FOR_PAYPAL_UNILATERAL = 91582,
TRANSACTION_OPTIONS_USE_BILLING_FOR_SHIPPING_DISABLED = 91572,
TRANSACTION_OPTIONS_VAULT_IS_DISABLED = 91525,
TRANSACTION_OPTIONS_CREDIT_CARD_ACCOUNT_TYPE_IS_INVALID = 915184,
TRANSACTION_OPTIONS_CREDIT_CARD_ACCOUNT_TYPE_NOT_SUPPORTED = 915185,
TRANSACTION_OPTIONS_CREDIT_CARD_ACCOUNT_TYPE_DEBIT_DOES_NOT_SUPPORT_AUTHS = 915186,
TRANSACTION_INVALID_PRESENTMENT_CURRENCY = 915214,
TRANSACTION_ORDER_ID_IS_TOO_LONG = 91501,
TRANSACTION_PAY_PAL_AUTH_EXPIRED = 91579,
TRANSACTION_PAY_PAL_VAULT_RECORD_MISSING_DATA = 91583,
TRANSACTION_PAYMENT_INSTRUMENT_NOT_SUPPORTED_BY_MERCHANT_ACCOUNT = 91577,
TRANSACTION_PAYMENT_INSTRUMENT_TYPE_IS_NOT_ACCEPTED = 915101,
TRANSACTION_PAYMENT_METHOD_CONFLICT = 91515,
TRANSACTION_PAYMENT_METHOD_CONFLICT_WITH_VENMO_SDK = 91549,
TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_CUSTOMER = 91516,
TRANSACTION_PAYMENT_METHOD_DOES_NOT_BELONG_TO_SUBSCRIPTION = 91527,
TRANSACTION_PAYMENT_METHOD_NONCE_CARD_TYPE_IS_NOT_ACCEPTED = 91567,
TRANSACTION_PAYMENT_METHOD_NONCE_CONSUMED = 91564,
TRANSACTION_PAYMENT_METHOD_NONCE_HAS_NO_VALID_PAYMENT_INSTRUMENT_TYPE = 91569,
TRANSACTION_PAYMENT_METHOD_NONCE_LOCKED = 91566,
TRANSACTION_PAYMENT_METHOD_NONCE_UNKNOWN = 91565,
TRANSACTION_PAYMENT_METHOD_TOKEN_CARD_TYPE_IS_NOT_ACCEPTED = 91517,
TRANSACTION_PAYMENT_METHOD_TOKEN_IS_INVALID = 91518,
TRANSACTION_PAYPAL_NOT_ENABLED = 91576,
TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_CANNOT_BE_SET = 91519,
TRANSACTION_PROCESSOR_AUTHORIZATION_CODE_IS_INVALID = 81520,
TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_AUTHS = 915104,
TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_CREDITS = 91546,
TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_MOTO_FOR_CARD_TYPE = 915195,
TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_PARTIAL_SETTLEMENT = 915102,
TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_UPDATING_DETAILS = 915130,
TRANSACTION_PROCESSOR_DOES_NOT_SUPPORT_VOICE_AUTHORIZATIONS = 91545,
TRANSACTION_PRODUCT_SKU_IS_INVALID = 915202,
TRANSACTION_PURCHASE_ORDER_NUMBER_IS_INVALID = 91548,
TRANSACTION_PURCHASE_ORDER_NUMBER_IS_TOO_LONG = 91537,
TRANSACTION_REFUND_AMOUNT_IS_TOO_LARGE = 91521,
TRANSACTION_REFUND_AUTH_HARD_DECLINED = 915200,
TRANSACTION_REFUND_AUTH_SOFT_DECLINED = 915201,
TRANSACTION_SERVICE_FEE_AMOUNT_CANNOT_BE_NEGATIVE = 91554,
TRANSACTION_SERVICE_FEE_AMOUNT_FORMAT_IS_INVALID = 91555,
TRANSACTION_SERVICE_FEE_AMOUNT_IS_TOO_LARGE = 91556,
TRANSACTION_SERVICE_FEE_AMOUNT_NOT_ALLOWED_ON_MASTER_MERCHANT_ACCOUNT = 91557,
TRANSACTION_SERVICE_FEE_IS_NOT_ALLOWED_ON_CREDITS = 91552,
TRANSACTION_SERVICE_FEE_NOT_ACCEPTED_FOR_PAYPAL = 91578,
TRANSACTION_SETTLEMENT_AMOUNT_IS_LESS_THAN_SERVICE_FEE_AMOUNT = 91551,
TRANSACTION_SETTLEMENT_AMOUNT_IS_TOO_LARGE = 91522,
TRANSACTION_SHIPPING_ADDRESS_DOESNT_MATCH_CUSTOMER = 91581,
TRANSACTION_SUB_MERCHANT_ACCOUNT_REQUIRES_SERVICE_FEE_AMOUNT = 91553,
TRANSACTION_SUBSCRIPTION_DOES_NOT_BELONG_TO_CUSTOMER = 91529,
TRANSACTION_SUBSCRIPTION_ID_IS_INVALID = 91528,
TRANSACTION_SUBSCRIPTION_STATUS_MUST_BE_PAST_DUE = 91531,
TRANSACTION_TAX_AMOUNT_CANNOT_BE_NEGATIVE = 81534,
TRANSACTION_TAX_AMOUNT_FORMAT_IS_INVALID = 81535,
TRANSACTION_TAX_AMOUNT_IS_REQUIRED_FOR_AIB_SWEDISH = 815224,
TRANSACTION_TAX_AMOUNT_IS_TOO_LARGE = 81536,
TRANSACTION_THREE_D_SECURE_AUTHENTICATION_FAILED = 81571,
TRANSACTION_THREE_D_SECURE_AUTHENTICATION_ID_DOES_NOT_MATCH_NONCE_THREE_D_SECURE_AUTHENTICATION = 915198,
TRANSACTION_THREE_D_SECURE_AUTHENTICATION_ID_IS_INVALID = 915196,
TRANSACTION_THREE_D_SECURE_AUTHENTICATION_ID_WITH_THREE_D_SECURE_PASS_THRU_IS_INVALID = 915199,
TRANSACTION_THREE_D_SECURE_PASS_THRU_AUTHENTICATION_RESPONSE_IS_INVALID = 915120,
TRANSACTION_THREE_D_SECURE_PASS_THRU_CAVV_ALGORITHM_IS_INVALID = 915122,
TRANSACTION_THREE_D_SECURE_PASS_THRU_CAVV_IS_REQUIRED = 915116,
TRANSACTION_THREE_D_SECURE_PASS_THRU_DIRECTORY_RESPONSE_IS_INVALID = 915121,
TRANSACTION_THREE_D_SECURE_PASS_THRU_ECI_FLAG_IS_INVALID = 915114,
TRANSACTION_THREE_D_SECURE_PASS_THRU_ECI_FLAG_IS_REQUIRED = 915113,
TRANSACTION_THREE_D_SECURE_PASS_THRU_MERCHANT_ACCOUNT_DOES_NOT_SUPPORT_CARD_TYPE = 915131,
TRANSACTION_THREE_D_SECURE_PASS_THRU_THREE_D_SECURE_VERSION_IS_INVALID = 915119,
TRANSACTION_THREE_D_SECURE_PASS_THRU_XID_IS_REQUIRED = 915115,
TRANSACTION_THREE_D_SECURE_TRANSACTION_DATA_DOESNT_MATCH_VERIFY = 91570,
TRANSACTION_THREE_D_SECURE_TRANSACTION_PAYMENT_METHOD_DOES_NOT_MATCH_THREE_D_SECURE_AUTHENTICATION_PAYMENT_METHOD = 915197,
TRANSACTION_THREE_D_SECURE_TOKEN_IS_INVALID = 91568,
TRANSACTION_TRANSACTION_SOURCE_IS_INVALID = 915133,
TRANSACTION_TYPE_IS_INVALID = 91523,
TRANSACTION_TYPE_IS_REQUIRED = 91524,
TRANSACTION_PAYMENT_INSTRUMENT_WITH_EXTERNAL_VAULT_IS_INVALID = 915176,
TRANSACTION_UNSUPPORTED_VOICE_AUTHORIZATION = 91539,
TRANSACTION_US_BANK_ACCOUNT_NONCE_MUST_BE_PLAID_VERIFIED = 915171,
TRANSACTION_US_BANK_ACCOUNT_MUST_BE_VERIFIED = 915172,
US_BANK_ACCOUNT_VERIFICATION_NOT_CONFIRMABLE = 96101,
US_BANK_ACCOUNT_VERIFICATION_MUST_BE_MICRO_TRANSFERS_VERIFICATION = 96102,
US_BANK_ACCOUNT_VERIFICATION_AMOUNTS_DO_NOT_MATCH = 96103,
US_BANK_ACCOUNT_VERIFICATION_TOO_MANY_CONFIRMATION_ATTEMPTS = 96104,
US_BANK_ACCOUNT_VERIFICATION_UNABLE_TO_CONFIRM_DEPOSIT_AMOUNTS = 96105,
US_BANK_ACCOUNT_VERIFICATION_INVALID_DEPOSIT_AMOUNTS = 96106,
VERIFICATION_OPTIONS_AMOUNT_CANNOT_BE_NEGATIVE = 94201,
VERIFICATION_OPTIONS_AMOUNT_FORMAT_IS_INVALID = 94202,
VERIFICATION_OPTIONS_AMOUNT_IS_TOO_LARGE = 94207,
VERIFICATION_OPTIONS_AMOUNT_NOT_SUPPORTED_BY_PROCESSOR = 94203,
VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_ID_IS_INVALID = 94204,
VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_IS_SUSPENDED = 94205,
VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_IS_FORBIDDEN = 94206,
VERIFICATION_OPTIONS_MERCHANT_ACCOUNT_CANNOT_BE_SUB_MERCHANT_ACCOUNT = 94208,
VERIFICATION_OPTIONS_ACCOUNT_TYPE_IS_INVALID = 942184,
VERIFICATION_OPTIONS_ACCOUNT_TYPE_NOT_SUPPORTED = 942185,
VERIFICATION_THREE_D_SECURE_ECI_FLAG_IS_REQUIRED = 942113,
VERIFICATION_THREE_D_SECURE_ECI_FLAG_IS_INVALID = 942114,
VERIFICATION_THREE_D_SECURE_CAVV_IS_REQUIRED = 942116,
VERIFICATION_THREE_D_SECURE_THREE_D_SECURE_VERSION_IS_REQUIRED = 942117,
VERIFICATION_THREE_D_SECURE_THREE_D_SECURE_VERSION_IS_INVALID = 942119,
VERIFICATION_THREE_D_SECURE_AUTHENTICATION_RESPONSE_IS_INVALID = 942120,
VERIFICATION_THREE_D_SECURE_DIRECTORY_RESPONSE_IS_INVALID = 942121,
VERIFICATION_THREE_D_SECURE_CAVV_ALGORITHM_IS_INVALID = 942122,
THREE_D_SECURE_AUTHENTICATION_ID_IS_INVALID = 942196,
THREE_D_SECURE_AUTHENTICATION_ID_DOESNT_MATCH_NONCE_THREE_D_SECURE_AUTHENTICATION = 942198,
THREE_D_SECURE_TRANSACTION_PAYMENT_METHOD_DOESNT_MATCH_THREE_D_SECURE_AUTHENTICATION_PAYMENT_METHOD = 942197,
THREE_D_SECURE_AUTHENTICATION_ID_WITH_THREE_D_SECURE_PASS_THRU_IS_INVALID = 942199,
THREE_D_SECURE_AUTHENTICATION_FAILED = 94271,
THREE_D_SECURE_TOKEN_IS_INVALID = 94268,
THREE_D_SECURE_VERIFICATION_DATA_DOESNT_MATCH_VERIFY = 94270,
MERCHANT_ACCOUNT_DOES_NOT_SUPPORT3_D_SECURE = 942169,
MERCHANT_ACOUNT_DOES_NOT_MATCH3_D_SECURE_MERCHANT_ACCOUNT = 94284,
AMOUNT_DOES_NOT_MATCH3_D_SECURE_AMOUNT = 94285,
// NEXT_MAJOR_VERSION Remove CustomerBrowserIsTooLong code as it is no longer returned from the gateway
RISK_DATA_CUSTOMER_BROWSER_IS_TOO_LONG = 94701,
RISK_DATA_CUSTOMER_DEVICE_ID_IS_TOO_LONG = 94702,
RISK_DATA_CUSTOMER_LOCATION_ZIP_INVALID_CHARACTERS = 94703,
RISK_DATA_CUSTOMER_LOCATION_ZIP_IS_INVALID = 94704,
RISK_DATA_CUSTOMER_LOCATION_ZIP_IS_TOO_LONG = 94705,
RISK_DATA_CUSTOMER_TENURE_IS_TOO_LONG = 94706
}
}
| |
/*! Achordeon - MIT License
Copyright (c) 2017 tiamatix / Wolf Robben
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.Diagnostics;
using System.Windows;
using Achordeon.Common.Extensions;
using Achordeon.Common.Helpers;
using Achordeon.Lib.SongOptions;
namespace Achordeon.Shell.Wpf.Contents
{
public class LinkedSongOptionsViewModel : SongOptionsViewModel
{
private readonly ISongOptions m_LinkedOptions;
private bool? m_TwoUp;
private bool? m_FourUp;
private string m_ChordFont;
private int? m_ChordSizePt;
private int? m_ChordGridSizeMm;
private bool? m_ChordGridSorted;
private bool? m_EvenPageNumberLeft;
private bool? m_LyricsOnly;
private bool? m_PageNumberLogical;
private string m_PageSize;
private bool? m_SingleSpace;
private int? m_StartPageNumber;
private string m_TextFont;
private int? m_TextSizePt;
private bool? m_CreateToc;
private int? m_TransposeByHalftones;
private int? m_VerticalSpace;
private bool? m_DrawChordGrids;
private bool? m_UseMusicalSymbols;
public LinkedSongOptionsViewModel(CoreViewModel ACore, ISongOptions ALinkedOptions) : base(ACore, ALinkedOptions)
{
ALinkedOptions.ThrowIfNullEx(nameof(ALinkedOptions));
m_LinkedOptions = ALinkedOptions;
Reset();
}
protected override void LoadFrom(ISongOptions AOtherOptions)
{
}
public void Reset()
{
m_TwoUp = null;
m_FourUp = null;
m_ChordFont = null;
m_ChordSizePt = null;
m_ChordGridSizeMm = null;
m_ChordGridSorted = null;
m_EvenPageNumberLeft = null;
m_LyricsOnly = null;
m_PageNumberLogical = null;
m_PageSize = null;
m_SingleSpace = null;
m_StartPageNumber = null;
m_TextFont = null;
m_TextSizePt = null;
m_CreateToc = null;
m_TransposeByHalftones = null;
m_VerticalSpace = null;
m_DrawChordGrids = null;
m_UseMusicalSymbols = null;
}
public override SongOptionsViewModel Clone()
{
var res = new LinkedSongOptionsViewModel(CoreViewModel, m_LinkedOptions);
res.m_TwoUp = m_TwoUp;
res.m_FourUp = m_FourUp;
res.m_ChordFont = m_ChordFont;
res.m_ChordSizePt = m_ChordSizePt;
res.m_ChordGridSizeMm = m_ChordGridSizeMm;
res.m_ChordGridSorted = m_ChordGridSorted;
res.m_EvenPageNumberLeft = m_EvenPageNumberLeft;
res.m_LyricsOnly = m_LyricsOnly;
res.m_PageNumberLogical = m_PageNumberLogical;
res.m_PageSize = m_PageSize;
res.m_SingleSpace = m_SingleSpace;
res.m_StartPageNumber = m_StartPageNumber;
res.m_TextFont = m_TextFont;
res.m_TextSizePt = m_TextSizePt;
res.m_CreateToc = m_CreateToc;
res.m_TransposeByHalftones = m_TransposeByHalftones;
res.m_VerticalSpace = m_VerticalSpace;
res.m_DrawChordGrids = m_DrawChordGrids;
res.m_UseMusicalSymbols = m_UseMusicalSymbols;
return res;
}
public override bool UseMusicalSymbols
{
get { return m_UseMusicalSymbols ?? m_LinkedOptions.UseMusicalSymbols; }
set { SetProperty(ref m_UseMusicalSymbols, value, nameof(UseMusicalSymbols)); }
}
public override bool DrawChordGrids
{
get { return m_DrawChordGrids ?? m_LinkedOptions.DrawChordGrids; }
set { SetProperty(ref m_DrawChordGrids, value, nameof(DrawChordGrids)); }
}
public override bool TwoUp
{
get { return m_TwoUp ?? m_LinkedOptions.TwoUp; }
set { SetProperty(ref m_TwoUp, value, nameof(TwoUp)); }
}
public override bool FourUp
{
get { return m_FourUp ?? m_LinkedOptions.FourUp; }
set { SetProperty(ref m_FourUp, value, nameof(FourUp)); }
}
public override string ChordFont
{
get { return m_ChordFont ?? m_LinkedOptions.ChordFont; }
set { SetProperty(ref m_ChordFont, value, nameof(ChordFont)); }
}
public override int ChordSizePt
{
get { return m_ChordSizePt ?? m_LinkedOptions.ChordSizePt; }
set { SetProperty(ref m_ChordSizePt, value, nameof(ChordSizePt)); }
}
public override int ChordGridSizeMm
{
get { return m_ChordGridSizeMm ?? m_LinkedOptions.ChordGridSizeMm; }
set { SetProperty(ref m_ChordGridSizeMm, value, nameof(ChordGridSizeMm)); }
}
public override bool ChordGridSorted
{
get { return m_ChordGridSorted ?? m_LinkedOptions.ChordGridSorted; }
set { SetProperty(ref m_ChordGridSorted, value, nameof(ChordGridSorted)); }
}
public override bool EvenPageNumberLeft
{
get { return m_EvenPageNumberLeft ?? m_LinkedOptions.EvenPageNumberLeft; }
set { SetProperty(ref m_EvenPageNumberLeft, value, nameof(EvenPageNumberLeft)); }
}
public override bool LyricsOnly
{
get { return m_LyricsOnly ?? m_LinkedOptions.LyricsOnly; }
set { SetProperty(ref m_LyricsOnly, value, nameof(LyricsOnly)); }
}
public override bool PageNumberLogical
{
get { return m_PageNumberLogical ?? m_LinkedOptions.PageNumberLogical; }
set { SetProperty(ref m_PageNumberLogical, value, nameof(PageNumberLogical)); }
}
public override string PageSize
{
get { return m_PageSize ?? m_LinkedOptions.PageSize; }
set { SetProperty(ref m_PageSize, value, nameof(PageSize)); }
}
public override bool SingleSpace
{
get { return m_SingleSpace ?? m_LinkedOptions.SingleSpace; }
set { SetProperty(ref m_SingleSpace, value, nameof(SingleSpace)); }
}
public override int StartPageNumber
{
get { return m_StartPageNumber ?? m_LinkedOptions.StartPageNumber; }
set { SetProperty(ref m_StartPageNumber, value, nameof(StartPageNumber)); }
}
public override string TextFont
{
get { return m_TextFont ?? m_LinkedOptions.TextFont; }
set { SetProperty(ref m_TextFont, value, nameof(TextFont)); }
}
public override int TextSizePt
{
get { return m_TextSizePt ?? m_LinkedOptions.TextSizePt; }
set { SetProperty(ref m_TextSizePt, value, nameof(TextSizePt)); }
}
public override bool CreateToc
{
get { return m_CreateToc ?? m_LinkedOptions.CreateToc; }
set { SetProperty(ref m_CreateToc, value, nameof(CreateToc)); }
}
public override int TransposeByHalftones
{
get { return m_TransposeByHalftones ?? m_LinkedOptions.TransposeByHalftones; }
set { SetProperty(ref m_TransposeByHalftones, value, nameof(TransposeByHalftones)); }
}
public override int VerticalSpace
{
get { return m_VerticalSpace ?? m_LinkedOptions.VerticalSpace; }
set { SetProperty(ref m_VerticalSpace, value, nameof(VerticalSpace)); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore.IO;
using SFML;
using SFML.Audio;
namespace NetGore.Audio
{
/// <summary>
/// Manages the game music.
/// </summary>
public class MusicManager : IMusicManager
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
const string _fileName = "music";
const string _rootNodeName = "Music";
readonly Dictionary<string, IMusicInfo> _infosByName = new Dictionary<string, IMusicInfo>(StringComparer.OrdinalIgnoreCase);
IMusicInfo[] _infos;
bool _loop = true;
Music _playing;
IMusicInfo _playingInfo;
float _volume = 100;
/// <summary>
/// Initializes a new instance of the <see cref="MusicManager"/> class.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "MusicInfos")]
public MusicManager()
{
ReloadData();
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposeManaged"><c>true</c> to release both managed and unmanaged resources;
/// <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposeManaged)
{
if (!disposeManaged)
return;
Stop();
if (_playing != null && !_playing.IsDisposed)
_playing.Dispose();
}
/// <summary>
/// Gets the file path for a music file.
/// </summary>
/// <param name="musicInfo">The <see cref="IMusicInfo"/> to get the file path for.</param>
/// <returns>The file path for the <paramref name="musicInfo"/>.</returns>
protected static string GetFilePath(IMusicInfo musicInfo)
{
return ContentPaths.Build.Music.Join(musicInfo.Name + ContentPaths.ContentFileSuffix);
}
#region IMusicManager Members
/// <summary>
/// Gets or sets if music will loop. Default is true.
/// </summary>
public bool Loop
{
get { return _loop; }
set
{
if (_loop == value)
return;
// Store the new value
_loop = value;
// If music is currently playing, update the loop value on it
if (_playing != null)
_playing.Loop = _loop;
}
}
/// <summary>
/// Gets the <see cref="IMusicInfo"/>s for all music tracks.
/// </summary>
public IEnumerable<IMusicInfo> MusicInfos
{
get { return _infosByName.Values; }
}
/// <summary>
/// Gets the <see cref="IMusicInfo"/> for the music track currently playing. Will be null if no music
/// is playing.
/// </summary>
public IMusicInfo Playing
{
get { return _playingInfo; }
}
/// <summary>
/// Gets or sets the global volume of all music. This value must be in a range of 0 to 100, where 0 is
/// silence and 100 is the full volume. If a value is specified that does not fall into this range, it will be
/// altered to fit this range. Default is 100.
/// </summary>
public float Volume
{
get { return _volume; }
set
{
// Keep in a valid range
if (value < 0)
value = 0;
else if (value > 100)
value = 100;
if (_volume == value)
return;
// Store the new value
_volume = value;
// If music is currently playing, update the volume value on it
if (_playing != null)
_playing.Volume = _volume;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Gets the <see cref="IMusicInfo"/> for a music track.
/// </summary>
/// <param name="id">The id of the <see cref="IMusicInfo"/> to get.</param>
/// <returns>The <see cref="IMusicInfo"/> for the given <paramref name="id"/>, or null if the value
/// was invalid.</returns>
public IMusicInfo GetMusicInfo(MusicID id)
{
var i = (int)id;
if (i < 0 || i >= _infos.Length)
return null;
return _infos[i];
}
/// <summary>
/// Gets the <see cref="IMusicInfo"/> for a music track.
/// </summary>
/// <param name="name">The name of the <see cref="IMusicInfo"/> to get.</param>
/// <returns>The <see cref="IMusicInfo"/> for the given <paramref name="name"/>, or null if the value
/// was invalid.</returns>
public IMusicInfo GetMusicInfo(string name)
{
IMusicInfo ret;
if (!_infosByName.TryGetValue(name, out ret))
return null;
return ret;
}
/// <summary>
/// Pauses the currently playing music, if any music is playing.
/// </summary>
public void Pause()
{
if (_playing != null)
_playing.Pause();
}
/// <summary>
/// Plays a music track by the given <see cref="MusicID"/>.
/// </summary>
/// <param name="id">The ID of the music to play.</param>
/// <returns>
/// True if the music played successfully; otherwise false.
/// </returns>
public bool Play(MusicID id)
{
try
{
// If the music is already playing, continue to play it
if (_playingInfo != null && _playingInfo.ID == id)
{
if (_playing.Status != SoundStatus.Playing)
_playing.Play();
return true;
}
// Stop the old music
Stop();
// Get the info for the music to play
var info = GetMusicInfo(id);
if (info == null)
return false;
// Start the new music
_playingInfo = info;
var file = GetFilePath(info);
try
{
_playing = new Music(file);
}
catch (LoadingFailedException ex)
{
const string errmsg = "Failed to load music `{0}`: {1}";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, info, ex);
Debug.Fail(string.Format(errmsg, info, ex));
_playing = null;
_playingInfo = null;
return false;
}
// Set the values for the music and start playing it
_playing.Volume = Volume;
_playing.Loop = Loop;
_playing.RelativeToListener = true;
_playing.Play();
}
catch (Exception ex)
{
const string errmsg = "Failed to play music with ID `{0}`. Exception: {1}";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, id, ex);
Debug.Fail(string.Format(errmsg, id, ex));
}
return true;
}
/// <summary>
/// Reloads the music information.
/// </summary>
public void ReloadData()
{
var values = AudioManager.LoadValues(_fileName, _rootNodeName);
var musicInfos = values.Select(x => new MusicInfo(x.Key, new MusicID(x.Value)));
ReloadData(musicInfos);
}
/// <summary>
/// Reloads the music information.
/// </summary>
/// <param name="values">All of the <see cref="IMusicInfo"/>s to load.</param>
/// <exception cref="DuplicateKeyException">Two or more <see cref="MusicInfo"/>s found with the same ID.</exception>
/// <exception cref="DuplicateKeyException">Two or more <see cref="MusicInfo"/>s found with the same name.</exception>
public void ReloadData(IEnumerable<IMusicInfo> values)
{
_infosByName.Clear();
values = values.OrderBy(x => x.ID);
// Create the _infos array large enough to hold all values
var max = values.Max(x => (int)x.ID);
_infos = new IMusicInfo[max + 1];
// Populate both collections
foreach (var mi in values)
{
// Ensure no duplicates
if (_infos[(int)mi.ID] != null)
throw new DuplicateKeyException(string.Format("Two or more MusicInfos found with the ID `{0}`!", mi.ID));
if (_infosByName.ContainsKey(mi.Name))
throw new DuplicateKeyException(string.Format("Two or more MusicInfos found with the name `{0}`!", mi.Name));
// Add
_infosByName.Add(mi.Name, mi);
_infos[(int)mi.ID] = mi;
}
}
/// <summary>
/// Resumes the currently paused music, if there is any paused music.
/// </summary>
public void Resume()
{
if (_playing != null && (_playing.Status == SoundStatus.Paused || _playing.Status == SoundStatus.Stopped))
_playing.Play();
}
/// <summary>
/// Saves the <see cref="IMusicInfo"/>s in this <see cref="IMusicManager"/> to file.
/// </summary>
public void Save()
{
AudioManager.WriteValues(_fileName, _rootNodeName,
MusicInfos.Select(x => new KeyValuePair<string, int>(x.Name, (int)x.ID)));
}
/// <summary>
/// Stops the currently playing music.
/// </summary>
public void Stop()
{
if (_playing == null)
return;
try
{
_playing.Dispose();
}
catch (InvalidOperationException ex)
{
const string errmsg = "Failed to dispose music `{0}` [`{1}`] (can potentially ignore). Exception: {2}";
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, _playing, _playingInfo, ex);
}
catch (Exception ex)
{
const string errmsg = "Failed to dispose music `{0}` [`{1}`]. Exception {2}";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, _playing, _playingInfo, ex);
Debug.Fail(string.Format(errmsg, _playing, _playingInfo, ex));
}
finally
{
_playing = null;
_playingInfo = null;
}
}
/// <summary>
/// Updates the <see cref="IMusicManager"/>.
/// </summary>
void IMusicManager.Update()
{
// Not needed by this implementation
}
#endregion
}
}
| |
/**
* @copyright
*
* Copyright 2013-2015 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Splunk.Logging
{
/// <summary>
/// HTTP event collector client side implementation that collects, serializes and send
/// events to Splunk HTTP event collector endpoint. This class shouldn't be used directly
/// by user applications.
/// </summary>
/// <remarks>
/// * HttpEventCollectorSender is thread safe and Send(...) method may be called from
/// different threads.
/// * Events are sending asynchronously and Send(...) method doesn't
/// block the caller code.
/// * HttpEventCollectorSender has an ability to plug middleware components that act
/// before posting data.
/// For example:
/// <code>
/// new HttpEventCollectorSender(uri: ..., token: ...,
/// middleware: (request, next) => {
/// // preprocess request
/// var response = next(request); // post data
/// // process response
/// return response;
/// }
/// ...
/// )
/// </code>
/// Middleware components can apply additional logic before and after posting
/// the data to Splunk server. See HttpEventCollectorResendMiddleware.
/// </remarks>
public class HttpEventCollectorSender : IDisposable
{
/// <summary>
/// Post request delegate.
/// </summary>
/// <param name="request">HTTP request.</param>
/// <returns>Server HTTP response.</returns>
public delegate Task<HttpResponseMessage> HttpEventCollectorHandler(
string token, List<HttpEventCollectorEventInfo> events);
/// <summary>
/// HTTP event collector middleware plugin.
/// </summary>
/// <param name="request">HTTP request.</param>
/// <param name="next">A handler that posts data to the server.</param>
/// <returns>Server HTTP response.</returns>
public delegate Task<HttpResponseMessage> HttpEventCollectorMiddleware(
string token, List<HttpEventCollectorEventInfo> events, HttpEventCollectorHandler next);
/// <summary>
/// Override the default event format.
/// </summary>
/// <returns>A dynamic type to be serialized.</returns>
public delegate dynamic HttpEventCollectorFormatter(HttpEventCollectorEventInfo eventInfo);
/// <summary>
/// Recommended default values for events batching
/// </summary>
public const int DefaultBatchInterval = 10 * 1000; // 10 seconds
public const int DefaultBatchSize = 10 * 1024; // 10KB
public const int DefaultBatchCount = 10;
/// <summary>
/// Sender operation mode. Parallel means that all HTTP requests are
/// asynchronous and may be indexed out of order. Sequential mode guarantees
/// sequential order of the indexed events.
/// </summary>
public enum SendMode
{
Parallel,
Sequential
};
private const string HttpContentTypeMedia = "application/json";
private const string HttpEventCollectorPath = "/services/collector/event/1.0";
private const string AuthorizationHeaderScheme = "Splunk";
private Uri httpEventCollectorEndpointUri; // HTTP event collector endpoint full uri
private HttpEventCollectorEventInfo.Metadata metadata; // logger metadata
private string token; // authorization token
private JsonSerializer serializer;
// events batching properties and collection
private int batchInterval = 0;
private int batchSizeBytes = 0;
private int batchSizeCount = 0;
private SendMode sendMode = SendMode.Parallel;
private Task activePostTask = null;
private object eventsBatchLock = new object();
private List<HttpEventCollectorEventInfo> eventsBatch = new List<HttpEventCollectorEventInfo>();
private StringBuilder serializedEventsBatch = new StringBuilder();
private Timer timer;
private HttpClient httpClient = null;
private HttpEventCollectorMiddleware middleware = null;
private HttpEventCollectorFormatter formatter = null;
// counter for bookkeeping the async tasks
private long activeAsyncTasksCount = 0;
/// <summary>
/// On error callbacks.
/// </summary>
public event Action<HttpEventCollectorException> OnError = (e) => { };
/// <param name="uri">Splunk server uri, for example https://localhost:8088.</param>
/// <param name="token">HTTP event collector authorization token.</param>
/// <param name="metadata">Logger metadata.</param>
/// <param name="sendMode">Send mode of the events.</param>
/// <param name="batchInterval">Batch interval in milliseconds.</param>
/// <param name="batchSizeBytes">Batch max size.</param>
/// <param name="batchSizeCount">Max number of individual events in batch.</param>
/// <param name="middleware">
/// HTTP client middleware. This allows to plug an HttpClient handler that
/// intercepts logging HTTP traffic.
/// </param>
/// <remarks>
/// Zero values for the batching params mean that batching is off.
/// </remarks>
public HttpEventCollectorSender(
Uri uri, string token, HttpEventCollectorEventInfo.Metadata metadata,
SendMode sendMode,
int batchInterval, int batchSizeBytes, int batchSizeCount,
HttpEventCollectorMiddleware middleware,
HttpEventCollectorFormatter formatter = null)
{
this.serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
this.httpEventCollectorEndpointUri = new Uri(uri, HttpEventCollectorPath);
this.sendMode = sendMode;
this.batchInterval = batchInterval;
this.batchSizeBytes = batchSizeBytes;
this.batchSizeCount = batchSizeCount;
this.metadata = metadata;
this.token = token;
this.middleware = middleware;
this.formatter = formatter;
// special case - if batch interval is specified without size and count
// they are set to "infinity", i.e., batch may have any size
if (this.batchInterval > 0 && this.batchSizeBytes == 0 && this.batchSizeCount == 0)
{
this.batchSizeBytes = this.batchSizeCount = int.MaxValue;
}
// when size configuration setting is missing it's treated as "infinity",
// i.e., any value is accepted.
if (this.batchSizeCount == 0 && this.batchSizeBytes > 0)
{
this.batchSizeCount = int.MaxValue;
}
else if (this.batchSizeBytes == 0 && this.batchSizeCount > 0)
{
this.batchSizeBytes = int.MaxValue;
}
// setup the timer
if (batchInterval != 0) // 0 means - no timer
{
timer = new Timer(OnTimer, null, batchInterval, batchInterval);
}
// setup HTTP client
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(AuthorizationHeaderScheme, token);
}
/// <summary>
/// Send an event to Splunk HTTP endpoint. Actual event send is done
/// asynchronously and this method doesn't block client application.
/// </summary>
/// <param name="id">Event id.</param>
/// <param name="severity">Event severity info.</param>
/// <param name="message">Event message text.</param>
/// <param name="data">Additional event data.</param>
/// <param name="metadataOverride">Metadata to use for this send.</param>
public void Send(
string id = null,
string severity = null,
string message = null,
object data = null,
HttpEventCollectorEventInfo.Metadata metadataOverride = null)
{
HttpEventCollectorEventInfo ei =
new HttpEventCollectorEventInfo(id, severity, message, data, metadataOverride ?? metadata);
DoSerialization(ei);
}
/// <summary>
/// Send an event to Splunk HTTP endpoint. Actual event send is done
/// asynchronously and this method doesn't block client application.
/// </summary>
/// <param name="timestamp">Timestamp to use.</param>
/// <param name="id">Event id.</param>
/// <param name="severity">Event severity info.</param>
/// <param name="message">Event message text.</param>
/// <param name="data">Additional event data.</param>
/// <param name="metadataOverride">Metadata to use for this send.</param>
public void Send(
DateTime timestamp,
string id = null,
string severity = null,
string message = null,
object data = null,
HttpEventCollectorEventInfo.Metadata metadataOverride = null)
{
HttpEventCollectorEventInfo ei =
new HttpEventCollectorEventInfo(timestamp, id, severity, message, data, metadataOverride ?? metadata);
DoSerialization(ei);
}
private void DoSerialization(HttpEventCollectorEventInfo ei)
{
string serializedEventInfo;
if (formatter == null)
{
serializedEventInfo = SerializeEventInfo(ei);
}
else
{
var formattedEvent = formatter(ei);
ei.Event = formattedEvent;
serializedEventInfo = JsonConvert.SerializeObject(ei);
}
// we use lock serializedEventsBatch to synchronize both
// serializedEventsBatch and serializedEvents
lock (eventsBatchLock)
{
eventsBatch.Add(ei);
serializedEventsBatch.Append(serializedEventInfo);
if (eventsBatch.Count >= batchSizeCount ||
serializedEventsBatch.Length >= batchSizeBytes)
{
// there are enough events in the batch
FlushInternal();
}
}
}
/// <summary>
/// Flush all events synchronously, i.e., flush and wait until all events
/// are sent.
/// </summary>
public void FlushSync()
{
Flush();
// wait until all pending tasks are done
while(Interlocked.CompareExchange(ref activeAsyncTasksCount, 0, 0) != 0)
{
// wait for 100ms - not CPU intensive and doesn't delay process
// exit too much
Thread.Sleep(100);
}
}
/// <summary>
/// Flush all event.
/// </summary>
public Task FlushAsync()
{
return new Task(() =>
{
FlushSync();
});
}
/// <summary>
/// Serialize event info into a json string
/// </summary>
/// <param name="eventInfo"></param>
/// <returns></returns>
public static string SerializeEventInfo(HttpEventCollectorEventInfo eventInfo)
{
return JsonConvert.SerializeObject(eventInfo);
}
/// <summary>
/// Flush all batched events immediately.
/// </summary>
private void Flush()
{
lock (eventsBatchLock)
{
FlushInternal();
}
}
private void FlushInternal()
{
// FlushInternal method is called only in contexts locked on eventsBatchLock
// therefore it's thread safe and doesn't need additional synchronization.
if (serializedEventsBatch.Length == 0)
return; // there is nothing to send
// flush events according to the system operation mode
if (this.sendMode == SendMode.Sequential)
FlushInternalSequentialMode(this.eventsBatch, this.serializedEventsBatch.ToString());
else
FlushInternalSingleBatch(this.eventsBatch, this.serializedEventsBatch.ToString());
// we explicitly create new objects instead to clear and reuse
// the old ones because Flush works in async mode
// and can use "previous" containers
this.serializedEventsBatch = new StringBuilder();
this.eventsBatch = new List<HttpEventCollectorEventInfo>();
}
private void FlushInternalSequentialMode(
List<HttpEventCollectorEventInfo> events,
String serializedEvents)
{
// post events only after the current post task is done
if (this.activePostTask == null)
{
this.activePostTask = Task.Factory.StartNew(() =>
{
FlushInternalSingleBatch(events, serializedEvents).Wait();
});
}
else
{
this.activePostTask = this.activePostTask.ContinueWith((_) =>
{
FlushInternalSingleBatch(events, serializedEvents).Wait();
});
}
}
private Task<HttpStatusCode> FlushInternalSingleBatch(
List<HttpEventCollectorEventInfo> events,
String serializedEvents)
{
// post data and update tasks counter
Interlocked.Increment(ref activeAsyncTasksCount);
Task<HttpStatusCode> task = PostEvents(events, serializedEvents);
task.ContinueWith((_) =>
{
Interlocked.Decrement(ref activeAsyncTasksCount);
});
return task;
}
private async Task<HttpStatusCode> PostEvents(
List<HttpEventCollectorEventInfo> events,
String serializedEvents)
{
// encode data
HttpResponseMessage response = null;
string serverReply = null;
HttpStatusCode responseCode = HttpStatusCode.OK;
try
{
// post data
HttpEventCollectorHandler next = (t, e) =>
{
HttpContent content = new StringContent(serializedEvents, Encoding.UTF8, HttpContentTypeMedia);
return httpClient.PostAsync(httpEventCollectorEndpointUri, content);
};
HttpEventCollectorHandler postEvents = (t, e) =>
{
return middleware == null ?
next(t, e) : middleware(t, e, next);
};
response = await postEvents(token, events);
responseCode = response.StatusCode;
if (responseCode != HttpStatusCode.OK && response.Content != null)
{
// record server reply
serverReply = await response.Content.ReadAsStringAsync();
OnError(new HttpEventCollectorException(
code: responseCode,
webException: null,
reply: serverReply,
response: response,
events: events
));
}
}
catch (HttpEventCollectorException e)
{
e.Events = events;
OnError(e);
}
catch (Exception e)
{
OnError(new HttpEventCollectorException(
code: responseCode,
webException: e,
reply: serverReply,
response: response,
events: events
));
}
return responseCode;
}
private void OnTimer(object state)
{
Flush();
}
#region HttpClientHandler.IDispose
private bool disposed = false;
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
if (timer != null)
{
timer.Dispose();
}
httpClient.Dispose();
}
disposed = true;
}
~HttpEventCollectorSender()
{
Dispose(false);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System.Buffers;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace System.MemoryTests
{
public static partial class ReadOnlyMemoryTests
{
public static IEnumerable<object[]> StringInputs()
{
yield return new object[] { "" };
yield return new object[] { "a" };
yield return new object[] { "a\0bcdefghijklmnopqrstuvwxyz" };
}
[Theory]
[MemberData(nameof(StringInputs))]
public static void AsReadOnlyMemory_ToArray_Roundtrips(string input)
{
ReadOnlyMemory<char> m = input.AsReadOnlyMemory();
Assert.Equal(input, new string(m.ToArray()));
}
[Theory]
[MemberData(nameof(StringInputs))]
public static void AsReadOnlyMemory_Span_Roundtrips(string input)
{
ReadOnlyMemory<char> m = input.AsReadOnlyMemory();
ReadOnlySpan<char> s = m.Span;
Assert.Equal(input, new string(s.ToArray()));
}
[Theory]
[InlineData("", 0, 0)]
[InlineData("0123456789", 0, 0)]
[InlineData("0123456789", 10, 0)]
[InlineData("0123456789", 0, 10)]
[InlineData("0123456789", 1, 9)]
[InlineData("0123456789", 2, 8)]
[InlineData("0123456789", 9, 1)]
[InlineData("0123456789", 1, 8)]
[InlineData("0123456789", 5, 3)]
public static void AsReadOnlyMemory_Slice_MatchesSubstring(string input, int offset, int count)
{
ReadOnlyMemory<char> m = input.AsReadOnlyMemory();
Assert.Equal(input.Substring(offset, count), new string(m.Slice(offset, count).ToArray()));
Assert.Equal(input.Substring(offset, count), new string(m.Slice(offset, count).Span.ToArray()));
Assert.Equal(input.Substring(offset), new string(m.Slice(offset).ToArray()));
}
[Fact]
public static void AsReadOnlyMemory_NullString_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("text", () => ((string)null).AsReadOnlyMemory());
AssertExtensions.Throws<ArgumentNullException>("text", () => ((string)null).AsReadOnlyMemory(0));
AssertExtensions.Throws<ArgumentNullException>("text", () => ((string)null).AsReadOnlyMemory(0, 0));
}
[Fact]
public static void AsReadOnlyMemory_TryGetString_Roundtrips()
{
string input = "0123456789";
ReadOnlyMemory<char> m = input.AsReadOnlyMemory();
Assert.False(m.IsEmpty);
Assert.True(m.TryGetString(out string text, out int start, out int length));
Assert.Same(input, text);
Assert.Equal(0, start);
Assert.Equal(input.Length, length);
m = m.Slice(1);
Assert.True(m.TryGetString(out text, out start, out length));
Assert.Same(input, text);
Assert.Equal(1, start);
Assert.Equal(input.Length - 1, length);
m = m.Slice(1);
Assert.True(m.TryGetString(out text, out start, out length));
Assert.Same(input, text);
Assert.Equal(2, start);
Assert.Equal(input.Length - 2, length);
m = m.Slice(3, 2);
Assert.True(m.TryGetString(out text, out start, out length));
Assert.Same(input, text);
Assert.Equal(5, start);
Assert.Equal(2, length);
m = m.Slice(m.Length);
Assert.True(m.TryGetString(out text, out start, out length));
Assert.Same(input, text);
Assert.Equal(7, start);
Assert.Equal(0, length);
m = m.Slice(0);
Assert.True(m.TryGetString(out text, out start, out length));
Assert.Same(input, text);
Assert.Equal(7, start);
Assert.Equal(0, length);
m = m.Slice(0, 0);
Assert.True(m.TryGetString(out text, out start, out length));
Assert.Same(input, text);
Assert.Equal(7, start);
Assert.Equal(0, length);
Assert.True(m.IsEmpty);
}
[Fact]
public static void Array_TryGetString_ReturnsFalse()
{
ReadOnlyMemory<char> m = new char[10];
Assert.False(m.TryGetString(out string text, out int start, out int length));
Assert.Null(text);
Assert.Equal(0, start);
Assert.Equal(0, length);
}
[Fact]
public static void AsReadOnlyMemory_TryGetArray_ReturnsFalse()
{
ReadOnlyMemory<char> m = "0123456789".AsReadOnlyMemory();
Assert.False(MemoryMarshal.TryGetArray(m, out ArraySegment<char> array));
Assert.Null(array.Array);
Assert.Equal(0, array.Offset);
Assert.Equal(0, array.Count);
}
[Fact]
public static unsafe void AsReadOnlyMemory_Retain_ExpectedPointerValue()
{
string input = "0123456789";
ReadOnlyMemory<char> m = input.AsReadOnlyMemory();
using (MemoryHandle h = m.Retain(pin: false))
{
Assert.Equal(IntPtr.Zero, (IntPtr)h.Pointer);
}
using (MemoryHandle h = m.Retain(pin: true))
{
GC.Collect();
fixed (char* ptr = input)
{
Assert.Equal((IntPtr)ptr, (IntPtr)h.Pointer);
}
}
}
[Theory]
[MemberData(nameof(TestHelpers.StringSliceTestData), MemberType = typeof(TestHelpers))]
public static unsafe void AsReadOnlyMemory_PointerAndLength(string text, int start, int length)
{
ReadOnlyMemory<char> m;
if (start == -1)
{
start = 0;
length = text.Length;
m = text.AsReadOnlyMemory();
}
else if (length == -1)
{
length = text.Length - start;
m = text.AsReadOnlyMemory(start);
}
else
{
m = text.AsReadOnlyMemory(start, length);
}
Assert.Equal(length, m.Length);
using (MemoryHandle h = m.Retain(pin: true))
{
fixed (char* pText = text)
{
char* expected = pText + start;
void* actual = h.Pointer;
Assert.Equal((IntPtr)expected, (IntPtr)actual);
}
}
}
[Theory]
[MemberData(nameof(TestHelpers.StringSlice2ArgTestOutOfRangeData), MemberType = typeof(TestHelpers))]
public static unsafe void AsReadOnlyMemory_2Arg_OutOfRange(string text, int start)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => text.AsReadOnlyMemory(start));
}
[Theory]
[MemberData(nameof(TestHelpers.StringSlice3ArgTestOutOfRangeData), MemberType = typeof(TestHelpers))]
public static unsafe void AsReadOnlyMemory_3Arg_OutOfRange(string text, int start, int length)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("start", () => text.AsReadOnlyMemory(start, length));
}
[Fact]
public static void AsReadOnlyMemory_EqualsAndGetHashCode_ExpectedResults()
{
ReadOnlyMemory<char> m1 = new string('a', 4).AsReadOnlyMemory();
ReadOnlyMemory<char> m2 = new string('a', 4).AsReadOnlyMemory();
Assert.True(m1.Span.SequenceEqual(m2.Span));
Assert.True(m1.Equals(m1));
Assert.True(m1.Equals((object)m1));
Assert.False(m1.Equals(m2));
Assert.False(m1.Equals((object)m2));
Assert.Equal(m1.GetHashCode(), m1.GetHashCode());
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AIPlatform.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedIndexServiceClientTest
{
[xunit::FactAttribute]
public void GetIndexRequestObject()
{
moq::Mock<IndexService.IndexServiceClient> mockGrpcClient = new moq::Mock<IndexService.IndexServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
MetadataSchemaUri = "metadata_schema_uric874bf0a",
Metadata = new wkt::Value(),
DeployedIndexes =
{
new DeployedIndexRef(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexServiceClient client = new IndexServiceClientImpl(mockGrpcClient.Object, null);
Index response = client.GetIndex(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexRequestObjectAsync()
{
moq::Mock<IndexService.IndexServiceClient> mockGrpcClient = new moq::Mock<IndexService.IndexServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
MetadataSchemaUri = "metadata_schema_uric874bf0a",
Metadata = new wkt::Value(),
DeployedIndexes =
{
new DeployedIndexRef(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Index>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexServiceClient client = new IndexServiceClientImpl(mockGrpcClient.Object, null);
Index responseCallSettings = await client.GetIndexAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Index responseCancellationToken = await client.GetIndexAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIndex()
{
moq::Mock<IndexService.IndexServiceClient> mockGrpcClient = new moq::Mock<IndexService.IndexServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
MetadataSchemaUri = "metadata_schema_uric874bf0a",
Metadata = new wkt::Value(),
DeployedIndexes =
{
new DeployedIndexRef(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexServiceClient client = new IndexServiceClientImpl(mockGrpcClient.Object, null);
Index response = client.GetIndex(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexAsync()
{
moq::Mock<IndexService.IndexServiceClient> mockGrpcClient = new moq::Mock<IndexService.IndexServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
MetadataSchemaUri = "metadata_schema_uric874bf0a",
Metadata = new wkt::Value(),
DeployedIndexes =
{
new DeployedIndexRef(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Index>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexServiceClient client = new IndexServiceClientImpl(mockGrpcClient.Object, null);
Index responseCallSettings = await client.GetIndexAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Index responseCancellationToken = await client.GetIndexAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIndexResourceNames()
{
moq::Mock<IndexService.IndexServiceClient> mockGrpcClient = new moq::Mock<IndexService.IndexServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
MetadataSchemaUri = "metadata_schema_uric874bf0a",
Metadata = new wkt::Value(),
DeployedIndexes =
{
new DeployedIndexRef(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIndex(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexServiceClient client = new IndexServiceClientImpl(mockGrpcClient.Object, null);
Index response = client.GetIndex(request.IndexName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexResourceNamesAsync()
{
moq::Mock<IndexService.IndexServiceClient> mockGrpcClient = new moq::Mock<IndexService.IndexServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexRequest request = new GetIndexRequest
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
};
Index expectedResponse = new Index
{
IndexName = IndexName.FromProjectLocationIndex("[PROJECT]", "[LOCATION]", "[INDEX]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
MetadataSchemaUri = "metadata_schema_uric874bf0a",
Metadata = new wkt::Value(),
DeployedIndexes =
{
new DeployedIndexRef(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetIndexAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Index>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexServiceClient client = new IndexServiceClientImpl(mockGrpcClient.Object, null);
Index responseCallSettings = await client.GetIndexAsync(request.IndexName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Index responseCancellationToken = await client.GetIndexAsync(request.IndexName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using J2N;
using Lucene.Net.Codecs.Lucene40;
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Support;
using Lucene.Net.Util;
using Lucene.Net.Util.Packed;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using Document = Lucene.Net.Documents.Document;
namespace Lucene.Net.Codecs.Compressing
{
/*
* 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>
/// <see cref="StoredFieldsWriter"/> impl for <see cref="CompressingStoredFieldsFormat"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class CompressingStoredFieldsWriter : StoredFieldsWriter
{
// hard limit on the maximum number of documents per chunk
internal const int MAX_DOCUMENTS_PER_CHUNK = 128;
internal const int STRING = 0x00;
internal const int BYTE_ARR = 0x01;
/// <summary>
/// NOTE: This was NUMERIC_INT in Lucene
/// </summary>
internal const int NUMERIC_INT32 = 0x02;
/// <summary>
/// NOTE: This was NUMERIC_FLOAT in Lucene
/// </summary>
internal const int NUMERIC_SINGLE = 0x03;
/// <summary>
/// NOTE:This was NUMERIC_LONG in Lucene
/// </summary>
internal const int NUMERIC_INT64 = 0x04;
internal const int NUMERIC_DOUBLE = 0x05;
internal static readonly int TYPE_BITS = PackedInt32s.BitsRequired(NUMERIC_DOUBLE);
internal static readonly int TYPE_MASK = (int)PackedInt32s.MaxValue(TYPE_BITS);
internal const string CODEC_SFX_IDX = "Index";
internal const string CODEC_SFX_DAT = "Data";
internal const int VERSION_START = 0;
internal const int VERSION_BIG_CHUNKS = 1;
internal const int VERSION_CHECKSUM = 2;
internal const int VERSION_CURRENT = VERSION_CHECKSUM;
private readonly Directory directory;
private readonly string segment;
private readonly string segmentSuffix;
private CompressingStoredFieldsIndexWriter indexWriter;
private IndexOutput fieldsStream;
private readonly CompressionMode compressionMode;
private readonly Compressor compressor;
private readonly int chunkSize;
private readonly GrowableByteArrayDataOutput bufferedDocs;
private int[] numStoredFields; // number of stored fields
private int[] endOffsets; // end offsets in bufferedDocs
private int docBase; // doc ID at the beginning of the chunk
private int numBufferedDocs; // docBase + numBufferedDocs == current doc ID
/// <summary>
/// Sole constructor. </summary>
public CompressingStoredFieldsWriter(Directory directory, SegmentInfo si, string segmentSuffix, IOContext context, string formatName, CompressionMode compressionMode, int chunkSize)
{
if (Debugging.AssertsEnabled) Debugging.Assert(directory != null);
this.directory = directory;
this.segment = si.Name;
this.segmentSuffix = segmentSuffix;
this.compressionMode = compressionMode;
this.compressor = compressionMode.NewCompressor();
this.chunkSize = chunkSize;
this.docBase = 0;
this.bufferedDocs = new GrowableByteArrayDataOutput(chunkSize);
this.numStoredFields = new int[16];
this.endOffsets = new int[16];
this.numBufferedDocs = 0;
bool success = false;
IndexOutput indexStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_INDEX_EXTENSION), context);
try
{
fieldsStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_EXTENSION), context);
string codecNameIdx = formatName + CODEC_SFX_IDX;
string codecNameDat = formatName + CODEC_SFX_DAT;
CodecUtil.WriteHeader(indexStream, codecNameIdx, VERSION_CURRENT);
CodecUtil.WriteHeader(fieldsStream, codecNameDat, VERSION_CURRENT);
if (Debugging.AssertsEnabled)
{
Debugging.Assert(CodecUtil.HeaderLength(codecNameDat) == fieldsStream.GetFilePointer());
Debugging.Assert(CodecUtil.HeaderLength(codecNameIdx) == indexStream.GetFilePointer());
}
indexWriter = new CompressingStoredFieldsIndexWriter(indexStream);
indexStream = null;
fieldsStream.WriteVInt32(chunkSize);
fieldsStream.WriteVInt32(PackedInt32s.VERSION_CURRENT);
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(indexStream);
Abort();
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
IOUtils.Dispose(fieldsStream, indexWriter);
}
finally
{
fieldsStream = null;
indexWriter = null;
}
}
}
public override void StartDocument(int numStoredFields)
{
if (numBufferedDocs == this.numStoredFields.Length)
{
int newLength = ArrayUtil.Oversize(numBufferedDocs + 1, 4);
this.numStoredFields = Arrays.CopyOf(this.numStoredFields, newLength);
endOffsets = Arrays.CopyOf(endOffsets, newLength);
}
this.numStoredFields[numBufferedDocs] = numStoredFields;
++numBufferedDocs;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void FinishDocument()
{
endOffsets[numBufferedDocs - 1] = bufferedDocs.Length;
if (TriggerFlush())
{
Flush();
}
}
/// <summary>
/// NOTE: This was saveInts() in Lucene.
/// </summary>
private static void SaveInt32s(int[] values, int length, DataOutput @out)
{
if (Debugging.AssertsEnabled) Debugging.Assert(length > 0);
if (length == 1)
{
@out.WriteVInt32(values[0]);
}
else
{
bool allEqual = true;
for (int i = 1; i < length; ++i)
{
if (values[i] != values[0])
{
allEqual = false;
break;
}
}
if (allEqual)
{
@out.WriteVInt32(0);
@out.WriteVInt32(values[0]);
}
else
{
long max = 0;
for (int i = 0; i < length; ++i)
{
max |= (uint)values[i];
}
int bitsRequired = PackedInt32s.BitsRequired(max);
@out.WriteVInt32(bitsRequired);
PackedInt32s.Writer w = PackedInt32s.GetWriterNoHeader(@out, PackedInt32s.Format.PACKED, length, bitsRequired, 1);
for (int i = 0; i < length; ++i)
{
w.Add(values[i]);
}
w.Finish();
}
}
}
private void WriteHeader(int docBase, int numBufferedDocs, int[] numStoredFields, int[] lengths)
{
// save docBase and numBufferedDocs
fieldsStream.WriteVInt32(docBase);
fieldsStream.WriteVInt32(numBufferedDocs);
// save numStoredFields
SaveInt32s(numStoredFields, numBufferedDocs, fieldsStream);
// save lengths
SaveInt32s(lengths, numBufferedDocs, fieldsStream);
}
private bool TriggerFlush()
{
return bufferedDocs.Length >= chunkSize || numBufferedDocs >= MAX_DOCUMENTS_PER_CHUNK; // chunks of at least chunkSize bytes
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Flush()
{
indexWriter.WriteIndex(numBufferedDocs, fieldsStream.GetFilePointer());
// transform end offsets into lengths
int[] lengths = endOffsets;
for (int i = numBufferedDocs - 1; i > 0; --i)
{
lengths[i] = endOffsets[i] - endOffsets[i - 1];
if (Debugging.AssertsEnabled) Debugging.Assert(lengths[i] >= 0);
}
WriteHeader(docBase, numBufferedDocs, numStoredFields, lengths);
// compress stored fields to fieldsStream
if (bufferedDocs.Length >= 2 * chunkSize)
{
// big chunk, slice it
for (int compressed = 0; compressed < bufferedDocs.Length; compressed += chunkSize)
{
compressor.Compress(bufferedDocs.Bytes, compressed, Math.Min(chunkSize, bufferedDocs.Length - compressed), fieldsStream);
}
}
else
{
compressor.Compress(bufferedDocs.Bytes, 0, bufferedDocs.Length, fieldsStream);
}
// reset
docBase += numBufferedDocs;
numBufferedDocs = 0;
bufferedDocs.Length = 0;
}
public override void WriteField(FieldInfo info, IIndexableField field)
{
int bits = 0;
BytesRef bytes;
string @string;
// LUCENENET specific - To avoid boxing/unboxing, we don't
// call GetNumericValue(). Instead, we check the field.NumericType and then
// call the appropriate conversion method.
if (field.NumericType != NumericFieldType.NONE)
{
switch (field.NumericType)
{
case NumericFieldType.BYTE:
case NumericFieldType.INT16:
case NumericFieldType.INT32:
bits = NUMERIC_INT32;
break;
case NumericFieldType.INT64:
bits = NUMERIC_INT64;
break;
case NumericFieldType.SINGLE:
bits = NUMERIC_SINGLE;
break;
case NumericFieldType.DOUBLE:
bits = NUMERIC_DOUBLE;
break;
default:
throw new ArgumentException("cannot store numeric type " + field.NumericType);
}
@string = null;
bytes = null;
}
else
{
bytes = field.GetBinaryValue();
if (bytes != null)
{
bits = BYTE_ARR;
@string = null;
}
else
{
bits = STRING;
@string = field.GetStringValue();
if (@string == null)
{
throw new ArgumentException("field " + field.Name + " is stored but does not have BinaryValue, StringValue nor NumericValue");
}
}
}
long infoAndBits = (((long)info.Number) << TYPE_BITS) | (uint)bits;
bufferedDocs.WriteVInt64(infoAndBits);
if (bytes != null)
{
bufferedDocs.WriteVInt32(bytes.Length);
bufferedDocs.WriteBytes(bytes.Bytes, bytes.Offset, bytes.Length);
}
else if (@string != null)
{
bufferedDocs.WriteString(field.GetStringValue());
}
else
{
switch (field.NumericType)
{
case NumericFieldType.BYTE:
case NumericFieldType.INT16:
case NumericFieldType.INT32:
bufferedDocs.WriteInt32(field.GetInt32Value().Value);
break;
case NumericFieldType.INT64:
bufferedDocs.WriteInt64(field.GetInt64Value().Value);
break;
case NumericFieldType.SINGLE:
bufferedDocs.WriteInt32(BitConversion.SingleToInt32Bits(field.GetSingleValue().Value));
break;
case NumericFieldType.DOUBLE:
bufferedDocs.WriteInt64(BitConversion.DoubleToInt64Bits(field.GetDoubleValue().Value));
break;
default:
throw new Exception("Cannot get here");
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Abort()
{
IOUtils.DisposeWhileHandlingException(this);
IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_EXTENSION), IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_INDEX_EXTENSION));
}
public override void Finish(FieldInfos fis, int numDocs)
{
if (numBufferedDocs > 0)
{
Flush();
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(bufferedDocs.Length == 0);
}
if (docBase != numDocs)
{
throw new Exception("Wrote " + docBase + " docs, finish called with numDocs=" + numDocs);
}
indexWriter.Finish(numDocs, fieldsStream.GetFilePointer());
CodecUtil.WriteFooter(fieldsStream);
if (Debugging.AssertsEnabled) Debugging.Assert(bufferedDocs.Length == 0);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override int Merge(MergeState mergeState)
{
int docCount = 0;
int idx = 0;
foreach (AtomicReader reader in mergeState.Readers)
{
SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++];
CompressingStoredFieldsReader matchingFieldsReader = null;
if (matchingSegmentReader != null)
{
StoredFieldsReader fieldsReader = matchingSegmentReader.FieldsReader;
// we can only bulk-copy if the matching reader is also a CompressingStoredFieldsReader
if (fieldsReader != null && fieldsReader is CompressingStoredFieldsReader)
{
matchingFieldsReader = (CompressingStoredFieldsReader)fieldsReader;
}
}
int maxDoc = reader.MaxDoc;
IBits liveDocs = reader.LiveDocs;
if (matchingFieldsReader == null || matchingFieldsReader.Version != VERSION_CURRENT || matchingFieldsReader.CompressionMode != compressionMode || matchingFieldsReader.ChunkSize != chunkSize) // the way data is decompressed depends on the chunk size - means reader version is not the same as the writer version
{
// naive merge...
for (int i = NextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; i = NextLiveDoc(i + 1, liveDocs, maxDoc))
{
Document doc = reader.Document(i);
AddDocument(doc, mergeState.FieldInfos);
++docCount;
mergeState.CheckAbort.Work(300);
}
}
else
{
int docID = NextLiveDoc(0, liveDocs, maxDoc);
if (docID < maxDoc)
{
// not all docs were deleted
CompressingStoredFieldsReader.ChunkIterator it = matchingFieldsReader.GetChunkIterator(docID);
int[] startOffsets = new int[0];
do
{
// go to the next chunk that contains docID
it.Next(docID);
// transform lengths into offsets
if (startOffsets.Length < it.chunkDocs)
{
startOffsets = new int[ArrayUtil.Oversize(it.chunkDocs, 4)];
}
for (int i = 1; i < it.chunkDocs; ++i)
{
startOffsets[i] = startOffsets[i - 1] + it.lengths[i - 1];
}
if (numBufferedDocs == 0 && startOffsets[it.chunkDocs - 1] < chunkSize && startOffsets[it.chunkDocs - 1] + it.lengths[it.chunkDocs - 1] >= chunkSize && NextDeletedDoc(it.docBase, liveDocs, it.docBase + it.chunkDocs) == it.docBase + it.chunkDocs) // no deletion in the chunk - chunk is large enough - chunk is small enough - starting a new chunk
{
if (Debugging.AssertsEnabled) Debugging.Assert(docID == it.docBase);
// no need to decompress, just copy data
indexWriter.WriteIndex(it.chunkDocs, fieldsStream.GetFilePointer());
WriteHeader(this.docBase, it.chunkDocs, it.numStoredFields, it.lengths);
it.CopyCompressedData(fieldsStream);
this.docBase += it.chunkDocs;
docID = NextLiveDoc(it.docBase + it.chunkDocs, liveDocs, maxDoc);
docCount += it.chunkDocs;
mergeState.CheckAbort.Work(300 * it.chunkDocs);
}
else
{
// decompress
it.Decompress();
if (startOffsets[it.chunkDocs - 1] + it.lengths[it.chunkDocs - 1] != it.bytes.Length)
{
throw new CorruptIndexException("Corrupted: expected chunk size=" + startOffsets[it.chunkDocs - 1] + it.lengths[it.chunkDocs - 1] + ", got " + it.bytes.Length);
}
// copy non-deleted docs
for (; docID < it.docBase + it.chunkDocs; docID = NextLiveDoc(docID + 1, liveDocs, maxDoc))
{
int diff = docID - it.docBase;
StartDocument(it.numStoredFields[diff]);
bufferedDocs.WriteBytes(it.bytes.Bytes, it.bytes.Offset + startOffsets[diff], it.lengths[diff]);
FinishDocument();
++docCount;
mergeState.CheckAbort.Work(300);
}
}
} while (docID < maxDoc);
it.CheckIntegrity();
}
}
}
Finish(mergeState.FieldInfos, docCount);
return docCount;
}
private static int NextLiveDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return doc;
}
while (doc < maxDoc && !liveDocs.Get(doc))
{
++doc;
}
return doc;
}
private static int NextDeletedDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return maxDoc;
}
while (doc < maxDoc && liveDocs.Get(doc))
{
++doc;
}
return doc;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Avalonia.Data;
using Avalonia.Markup.Data.Plugins;
namespace Avalonia.Markup.Data
{
/// <summary>
/// Observes and sets the value of an expression on an object.
/// </summary>
public class ExpressionObserver : ObservableBase<object>, IDescription
{
/// <summary>
/// An ordered collection of property accessor plugins that can be used to customize
/// the reading and subscription of property values on a type.
/// </summary>
public static readonly IList<IPropertyAccessorPlugin> PropertyAccessors =
new List<IPropertyAccessorPlugin>
{
new AvaloniaPropertyAccessorPlugin(),
new InpcPropertyAccessorPlugin(),
};
/// <summary>
/// An ordered collection of validation checker plugins that can be used to customize
/// the validation of view model and model data.
/// </summary>
public static readonly IList<IDataValidationPlugin> DataValidators =
new List<IDataValidationPlugin>
{
new DataAnnotationsValidationPlugin(),
new IndeiValidationPlugin(),
new ExceptionValidationPlugin(),
};
/// <summary>
/// An ordered collection of stream plugins that can be used to customize the behavior
/// of the '^' stream binding operator.
/// </summary>
public static readonly IList<IStreamPlugin> StreamHandlers =
new List<IStreamPlugin>
{
new TaskStreamPlugin(),
new ObservableStreamPlugin(),
};
private static readonly object UninitializedValue = new object();
private readonly ExpressionNode _node;
private readonly Subject<Unit> _finished;
private readonly object _root;
private IObservable<object> _result;
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionObserver"/> class.
/// </summary>
/// <param name="root">The root object.</param>
/// <param name="expression">The expression.</param>
/// <param name="enableDataValidation">Whether data validation should be enabled.</param>
/// <param name="description">
/// A description of the expression. If null, <paramref name="expression"/> will be used.
/// </param>
public ExpressionObserver(
object root,
string expression,
bool enableDataValidation = false,
string description = null)
{
Contract.Requires<ArgumentNullException>(expression != null);
if (root == AvaloniaProperty.UnsetValue)
{
root = null;
}
Expression = expression;
Description = description ?? expression;
_node = Parse(expression, enableDataValidation);
_root = new WeakReference(root);
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionObserver"/> class.
/// </summary>
/// <param name="rootObservable">An observable which provides the root object.</param>
/// <param name="expression">The expression.</param>
/// <param name="enableDataValidation">Whether data validation should be enabled.</param>
/// <param name="description">
/// A description of the expression. If null, <paramref name="expression"/> will be used.
/// </param>
public ExpressionObserver(
IObservable<object> rootObservable,
string expression,
bool enableDataValidation = false,
string description = null)
{
Contract.Requires<ArgumentNullException>(rootObservable != null);
Contract.Requires<ArgumentNullException>(expression != null);
Expression = expression;
Description = description ?? expression;
_node = Parse(expression, enableDataValidation);
_finished = new Subject<Unit>();
_root = rootObservable;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionObserver"/> class.
/// </summary>
/// <param name="rootGetter">A function which gets the root object.</param>
/// <param name="expression">The expression.</param>
/// <param name="update">An observable which triggers a re-read of the getter.</param>
/// <param name="enableDataValidation">Whether data validation should be enabled.</param>
/// <param name="description">
/// A description of the expression. If null, <paramref name="expression"/> will be used.
/// </param>
public ExpressionObserver(
Func<object> rootGetter,
string expression,
IObservable<Unit> update,
bool enableDataValidation = false,
string description = null)
{
Contract.Requires<ArgumentNullException>(rootGetter != null);
Contract.Requires<ArgumentNullException>(expression != null);
Contract.Requires<ArgumentNullException>(update != null);
Expression = expression;
Description = description ?? expression;
_node = Parse(expression, enableDataValidation);
_finished = new Subject<Unit>();
_node.Target = new WeakReference(rootGetter());
_root = update.Select(x => rootGetter());
}
/// <summary>
/// Attempts to set the value of a property expression.
/// </summary>
/// <param name="value">The value to set.</param>
/// <param name="priority">The binding priority to use.</param>
/// <returns>
/// True if the value could be set; false if the expression does not evaluate to a
/// property. Note that the <see cref="ExpressionObserver"/> must be subscribed to
/// before setting the target value can work, as setting the value requires the
/// expression to be evaluated.
/// </returns>
public bool SetValue(object value, BindingPriority priority = BindingPriority.LocalValue)
{
return (Leaf as PropertyAccessorNode)?.SetTargetValue(value, priority) ?? false;
}
/// <summary>
/// Gets a description of the expression being observed.
/// </summary>
public string Description { get; }
/// <summary>
/// Gets the expression being observed.
/// </summary>
public string Expression { get; }
/// <summary>
/// Gets the type of the expression result or null if the expression could not be
/// evaluated.
/// </summary>
public Type ResultType => (Leaf as PropertyAccessorNode)?.PropertyType;
/// <summary>
/// Gets the leaf node.
/// </summary>
private ExpressionNode Leaf
{
get
{
var node = _node;
while (node.Next != null) node = node.Next;
return node;
}
}
/// <inheritdoc/>
protected override IDisposable SubscribeCore(IObserver<object> observer)
{
if (_result == null)
{
var source = (IObservable<object>)_node;
if (_finished != null)
{
source = source.TakeUntil(_finished);
}
_result = Observable.Using(StartRoot, _ => source)
.Select(ToWeakReference)
.Publish(UninitializedValue)
.RefCount()
.Where(x => x != UninitializedValue)
.Select(Translate);
}
return _result.Subscribe(observer);
}
private static ExpressionNode Parse(string expression, bool enableDataValidation)
{
if (!string.IsNullOrWhiteSpace(expression))
{
return ExpressionNodeBuilder.Build(expression, enableDataValidation);
}
else
{
return new EmptyExpressionNode();
}
}
private static object ToWeakReference(object o)
{
return o is BindingNotification ? o : new WeakReference(o);
}
private object Translate(object o)
{
var weak = o as WeakReference;
if (weak != null)
{
return weak.Target;
}
else
{
var broken = BindingNotification.ExtractError(o) as MarkupBindingChainException;
if (broken != null)
{
// We've received notification of a broken expression due to a null value
// somewhere in the chain. If this null value occurs at the first node then we
// ignore it, as its likely that e.g. the DataContext has not yet been set up.
if (broken.HasNodes)
{
broken.Commit(Description);
}
else
{
o = AvaloniaProperty.UnsetValue;
}
}
return o;
}
}
private IDisposable StartRoot()
{
var observable = _root as IObservable<object>;
if (observable != null)
{
return observable.Subscribe(
x => _node.Target = new WeakReference(x != AvaloniaProperty.UnsetValue ? x : null),
_ => _finished.OnNext(Unit.Default),
() => _finished.OnNext(Unit.Default));
}
else
{
_node.Target = (WeakReference)_root;
return Disposable.Empty;
}
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public partial class ParallelQueryCombinationTests
{
private const int EventualCancellationSize = 128;
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Aggregate_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Aggregate((i, j) => j));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j, i => i));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j, (i, j) => i, i => i));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(() => 0, (i, j) => j, (i, j) => i, i => i));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Aggregate_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Aggregate((i, j) => j));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j, i => i));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j, (i, j) => i, i => i));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(() => 0, (i, j) => j, (i, j) => i, i => i));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Aggregate((i, j) => j));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j, i => i));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(0, (i, j) => j, (i, j) => i, i => i));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Aggregate(() => 0, (i, j) => j, (i, j) => i, i => i));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Aggregate_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Aggregate((x, y) => x));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Aggregate(0, (x, y) => x + y));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Aggregate(0, (x, y) => x + y, r => r));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void All_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).All(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void All_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).All(x => true));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).All(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void All_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).All(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Any_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Any(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Any_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Any(x => false));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Any(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Any_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Any());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Any(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Average_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (int?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (long)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (long?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (float)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (float?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (double)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (double?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (decimal)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Average_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (int?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (long)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (long?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (float)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (float?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (double)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (double?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (decimal)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (decimal?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (int?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (long)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (long?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (float)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (float?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (double)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (double?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (decimal)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Average(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Average_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Average());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Contains_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Contains(-1));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Contains_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Contains(-1));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Contains(-1));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Contains_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Contains(DefaultStart));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Count_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Count());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).LongCount());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Count(x => true));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).LongCount(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Count_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Count());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).LongCount());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Count(x => true));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).LongCount(x => true));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Count());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).LongCount());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Count(x => true));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).LongCount(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Count_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Count());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).LongCount());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Count(x => true));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).LongCount(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ElementAt_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ElementAt(int.MaxValue));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ElementAt_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ElementAt(int.MaxValue));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ElementAt(int.MaxValue));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ElementAt_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ElementAt(0));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ElementAtOrDefault_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ElementAt(int.MaxValue));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ElementAtOrDefault_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ElementAtOrDefault(int.MaxValue));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ElementAtOrDefault(int.MaxValue));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ElementAtOrDefault_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ElementAtOrDefault(0));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ElementAtOrDefault(DefaultSize + 1));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void First_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).First(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void First_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).First(x => false));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).First(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void First_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).First());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).First(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void FirstOrDefault_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).FirstOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void FirstOrDefault_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).FirstOrDefault(x => false));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).FirstOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void FirstOrDefault_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).FirstOrDefault());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).FirstOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void ForAll_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ForAll(x => { }));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void ForAll_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ForAll(x => { }));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ForAll(x => { }));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void ForAll_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ForAll(x => { }));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ForEach_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => { foreach (int i in operation.Item(source, canceler)) ; });
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ForEach_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => { foreach (int i in operation.Item(source, canceler)) ; });
AssertThrows.SameTokenNotCanceled((source, canceler) => { foreach (int i in operation.Item(source, canceler)) ; });
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ForEach_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => { foreach (int i in operation.Item(source, () => { })) ; });
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void Last_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Last());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Last(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void Last_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Last());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Last(x => true));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Last());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Last(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void Last_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Last());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Last(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void LastOrDefault_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).LastOrDefault());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).LastOrDefault(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void LastOrDefault_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).LastOrDefault());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).LastOrDefault(x => true));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).LastOrDefault());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).LastOrDefault(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void LastOrDefault_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).LastOrDefault());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).LastOrDefault(x => true));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Max_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (int)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (int?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (long)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (long?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (float)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (float?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (double)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (double?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (decimal)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Max_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (int)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (int?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (long)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (long?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (float)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (float?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (double)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (double?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (decimal)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (decimal?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (int)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (int?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (long)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (long?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (float)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (float?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (double)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (double?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (decimal)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Max(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Max_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Max());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Min_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (int)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (int?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (long)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (long?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (float)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (float?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (double)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (double?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (decimal)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Min_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (int)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (int?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (long)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (long?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (float)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (float?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (double)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (double?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (decimal)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (decimal?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (int)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (int?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (long)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (long?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (float)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (float?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (double)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (double?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (decimal)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Min(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Min_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Min());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void SequenceEqual_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).SequenceEqual(ParallelEnumerable.Range(0, EventualCancellationSize).AsOrdered()));
AssertThrows.EventuallyCanceled((source, canceler) => ParallelEnumerable.Range(0, EventualCancellationSize).AsOrdered().SequenceEqual(operation.Item(source, canceler)));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void SequenceEqual_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
SequenceEqual_AssertAggregateAlternateCanceled((token, canceler) => WithCancellation(token, canceler, operation).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered()));
SequenceEqual_AssertAggregateAlternateCanceled((token, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(WithCancellation(token, canceler, operation)));
SequenceEqual_AssertAggregateNotCanceled((token, canceler) => WithCancellation(token, canceler, operation).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered()));
SequenceEqual_AssertAggregateNotCanceled((token, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(WithCancellation(token, canceler, operation)));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void SequenceEqual_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).SequenceEqual(ParallelEnumerable.Range(0, 2)));
AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(operation.Item(source, () => { })));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Single_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Single(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Single_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Single(x => false));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Single(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Single_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Single());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Single(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void SingleOrDefault_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).SingleOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void SingleOrDefault_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).SingleOrDefault(x => false));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).SingleOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void SingleOrDefault_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).SingleOrDefault());
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).SingleOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Sum_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum());
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (int?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (long)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (long?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (float)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (float?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (double)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (double?)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (decimal)x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Sum_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum());
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (int?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (long)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (long?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (float)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (float?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (double)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (double?)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (decimal)x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (decimal?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (int?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (long)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (long?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (float)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (float?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (double)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (double?)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (decimal)x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).Sum(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void Sum_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).Sum());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToArray_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ToArray());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToArray_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ToArray());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ToArray());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToArray_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ToArray());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void ToDictionary_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ToDictionary(x => x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ToDictionary(x => x, y => y));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void ToDictionary_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ToDictionary(x => x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ToDictionary(x => x, y => y));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ToDictionary(x => x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ToDictionary(x => x, y => y));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
public static void ToDictionary_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ToDictionary(x => x));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ToDictionary(x => x, y => y));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToList_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ToList());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToList_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ToList());
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ToList());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToList_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ToList());
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToLookup_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ToLookup(x => x));
AssertThrows.EventuallyCanceled((source, canceler) => operation.Item(source, canceler).ToLookup(x => x, y => y));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToLookup_AggregateException_Wraps_OperationCanceledException(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ToLookup(x => x));
AssertThrows.OtherTokenCanceled((source, canceler) => operation.Item(source, canceler).ToLookup(x => x, y => y));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ToLookup(x => x));
AssertThrows.SameTokenNotCanceled((source, canceler) => operation.Item(source, canceler).ToLookup(x => x, y => y));
}
[Theory]
[MemberData(nameof(UnaryCancelingOperators))]
[MemberData(nameof(BinaryCancelingOperators))]
[MemberData(nameof(OrderCancelingOperators))]
public static void ToLookup_OperationCanceledException_PreCanceled(Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ToLookup(x => x));
AssertThrows.AlreadyCanceled(source => operation.Item(source, () => { }).ToLookup(x => x, y => y));
}
private static ParallelQuery<int> WithCancellation(CancellationToken token, Action canceler, Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>> operation)
{
return operation.Item(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).WithCancellation(token), canceler);
}
private static void SequenceEqual_AssertAggregateAlternateCanceled(Action<CancellationToken, Action> query)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Action canceler = () => { throw new OperationCanceledException(cs.Token); };
AggregateException outer = Assert.Throws<AggregateException>(() => query(new CancellationTokenSource().Token, canceler));
AggregateException ae = Assert.Single<AggregateException>(outer.InnerExceptions.Cast<AggregateException>());
Assert.All(ae.InnerExceptions, e => Assert.IsType<OperationCanceledException>(e));
}
private static void SequenceEqual_AssertAggregateNotCanceled(Action<CancellationToken, Action> query)
{
CancellationToken token = new CancellationTokenSource().Token;
Action canceler = () => { throw new OperationCanceledException(token); };
AggregateException outer = Assert.Throws<AggregateException>(() => query(token, canceler));
AggregateException ae = Assert.Single<AggregateException>(outer.InnerExceptions.Cast<AggregateException>());
Assert.All(ae.InnerExceptions, e => Assert.IsType<OperationCanceledException>(e));
}
}
}
| |
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI.Windows.Plugins.Localization;
namespace UnityEngine.UI.Windows.Components {
public enum PointerEventState : byte {
Click,
Enter,
Leave,
};
public enum RichTextFlags : byte {
None = 0x0,
Color = 0x1,
Bold = 0x2,
Italic = 0x4,
Size = 0x8,
Material = 0x10,
Quad = 0x20,
};
public enum TextValueFormat : byte {
None, // 1234567890
WithSpace, // 1 234 567 890
WithComma, // 1,234 567 890
TimeHMSFromSeconds, // 00:00:00
TimeMSFromSeconds, // 00:00
TimeHMSmsFromMilliseconds, // 00:00:00`00
TimeMSmsFromMilliseconds, // 00:00`00
DateDMHMS, // 12 Aug 00:00:00
DateDMHMSFromMilliseconds,
TimeMSFromMilliseconds, // 00:00
TimeHMSFromMilliseconds, // 00:00:00
DateUniversalFromMilliseconds, // Universal
};
public enum FullTextFormat : byte {
None = 0x0,
UpperFirstLetter = 0x1,
LowerAll = 0x2,
UpperAll = 0x4,
UppercaseWords = 0x8,
TrimLeft = 0x10,
TrimRight = 0x20,
Trim = TrimLeft | TrimRight,
Percent = 0x40,
};
public interface IComponentElement : IWindowObject {
WindowObjectState GetComponentState();
void SetComponentState(WindowObjectState state, bool dontInactivate = false);
bool IsVisible();
bool IsVisibleSelf();
RectTransform GetRectTransform();
}
public interface IComponent : IComponentElement {
}
public interface IHoverableComponent : IComponent {
IHoverableComponent SetSFX(PointerEventState state, Audio.Component data);
IHoverableComponent SetHoverState(bool state);
IHoverableComponent SetHoverOnAnyPointerState(bool state);
IHoverableComponent SetCallbackHover(System.Action<bool> callback);
IHoverableComponent RemoveCallbackHover(System.Action<bool> onHover);
bool IsHovered();
IHoverableComponent SetHoverEnter();
IHoverableComponent SetHoverExit();
}
public interface IInteractableStateComponent : IWindowNavigation {
bool IsInteractable();
}
public interface IInteractableComponent : IInteractableStateComponent {
bool IsHoverCursorDefaultOnInactive();
IInteractableComponent SetEnabledState(bool state);
IInteractableComponent SetEnabled();
IInteractableComponent SetDisabled();
IInteractableComponent SetHoverOnAnyButtonState(bool state);
void Select();
Selectable GetSelectable();
bool IsInteractableAndHasEvents();
}
public interface IInteractableControllerComponent : IComponent {
IInteractableControllerComponent Click();
}
public interface IButtonComponent : ITextComponent, IImageComponent, IWindowNavigation, IInteractableControllerComponent, IInteractableComponent {
IButtonComponent RemoveAllCallbacks();
IButtonComponent RemoveCallback(System.Action callback);
IButtonComponent RemoveCallback(System.Action<ButtonComponent> callback);
IButtonComponent SetCallback(System.Action callback);
IButtonComponent SetCallback(System.Action<ButtonComponent> callback);
IButtonComponent AddCallback(System.Action callback);
IButtonComponent AddCallback(System.Action<ButtonComponent> callback);
void OnClick();
IButtonComponent SetButtonColor(Color color);
IButtonComponent SetSelectByDefault(bool state);
IButtonComponent SetNavigationMode(Navigation.Mode mode);
}
public interface IListComponent : IWindowNavigation {
IListComponent ListMoveUp(int count = 1);
IListComponent ListMoveDown(int count = 1);
IListComponent ListMoveLeft(int count = 1);
IListComponent ListMoveRight(int count = 1);
}
public interface ITextComponent : IComponent {
ITextComponent SetValue(int value);
ITextComponent SetValue(long value);
ITextComponent SetValue(int value, TextValueFormat format);
ITextComponent SetValue(long value, TextValueFormat format);
ITextComponent SetValue(int value, TextValueFormat format, bool animate);
ITextComponent SetValue(long value, TextValueFormat format, bool animate);
ITextComponent SetValueAnimate(bool state);
ITextComponent SetValueAnimateDuration(float duration);
ITextComponent SetTextLocalizationKey(LocalizationKey key);
ITextComponent SetText(string text);
ITextComponent SetText(LocalizationKey key, params object[] parameters);
string GetText();
ITextComponent SetTextColor(Color color);
ITextComponent SetValueFormat(TextValueFormat format);
ITextComponent SetFullTextFormat(FullTextFormat format);
ITextComponent SetFontSize(int value);
int GetFontSize();
ITextComponent SetLineSpacing(float value);
ITextComponent SetRichText(bool state);
ITextComponent SetTextAlignment(TextAnchor anchor);
ITextComponent SetTextVerticalOverflow(VerticalWrapMode mode);
ITextComponent SetTextHorizontalOverflow(HorizontalWrapMode mode);
ITextComponent SetBestFitState(bool state);
ITextComponent SetBestFitMinSize(int value);
ITextComponent SetBestFitMaxSize(int value);
Graphic GetGraphicSource();
}
public interface IAlphaComponent {
IAlphaComponent SetAlpha(float value);
}
public interface IImageComponent : IComponent, IAlphaComponent, ILoadableResource, IResourceReference {
IImageComponent ResetImage();
IImageComponent SetImage(ResourceAuto resource, System.Action onDataLoaded = null, System.Action onComplete = null, System.Action onFailed = null);
IImageComponent SetImage(Sprite sprite);
IImageComponent SetImage(Sprite sprite, bool immediately);
IImageComponent SetImage(Sprite sprite, System.Action onComplete);
IImageComponent SetImage(Sprite sprite, System.Action onComplete, bool immediately);
IImageComponent SetImage(Sprite sprite, bool preserveAspect, bool withPivotsAndSize, System.Action onComplete);
IImageComponent SetImage(Sprite sprite, bool preserveAspect, bool withPivotsAndSize, System.Action onComplete, bool immediately);
IImageComponent SetImage(Texture texture);
IImageComponent SetImage(Texture texture, bool immediately);
IImageComponent SetImage(Texture texture, System.Action onComplete);
IImageComponent SetImage(Texture texture, System.Action onComplete, bool immediately);
IImageComponent SetImage(Texture texture, bool preserveAspect, System.Action onComplete);
IImageComponent SetImage(Texture texture, bool preserveAspect, System.Action onComplete, bool immediately);
IImageComponent SetImage(LocalizationKey key, params object[] parameters);
IImageComponent SetImageLocalizationKey(LocalizationKey key);
IImageComponent SetMaterial(Material material, bool setMainTexture = false, System.Action callback = null);
Color GetColor();
void SetColor(Color color);
IImageComponent SetPreserveAspectState(bool state);
Texture GetTexture();
bool IsHorizontalFlip();
bool IsVerticalFlip();
bool IsPreserveAspect();
bool IsMovie();
bool GetPlayOnShow();
IImageComponent SetMovieTexture(ResourceAuto resource, System.Action onDataLoaded, System.Action onComplete = null, System.Action onFailed = null);
IImageComponent SetPlayOnShow(bool state);
IImageComponent SetLoop(bool state);
bool IsLoop();
bool IsPlaying();
IImageComponent Play();
IImageComponent Play(bool loop);
IImageComponent Play(bool loop, System.Action onComplete);
IImageComponent Stop();
IImageComponent Pause();
IImageComponent Rewind(bool pause = true);
Graphic GetGraphicSource();
Image GetImageSource();
RawImage GetRawImageSource();
}
public interface IProgressComponent : IComponent, IWindowNavigation, IInteractableComponent {
void SetDuration(float value);
void SetMinNormalizedValue(float value);
void SetContiniousState(bool continious);
void SetContiniousWidth(float continiousWidth);
void SetContiniousAngleStep(float continiousAngleStep);
void SetCallback(System.Action<float> onChanged);
IProgressComponent SetValue(float value, bool immediately = false, System.Action callback = null);
}
}
| |
/*
* 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 cloudfront-2015-04-17.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudFront.Model
{
/// <summary>
/// A summary of the information for an Amazon CloudFront streaming distribution.
/// </summary>
public partial class StreamingDistributionSummary
{
private Aliases _aliases;
private string _comment;
private string _domainName;
private bool? _enabled;
private string _id;
private DateTime? _lastModifiedTime;
private PriceClass _priceClass;
private S3Origin _s3Origin;
private string _status;
private TrustedSigners _trustedSigners;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public StreamingDistributionSummary() { }
/// <summary>
/// Gets and sets the property Aliases. A complex type that contains information about
/// CNAMEs (alternate domain names), if any, for this streaming distribution.
/// </summary>
public Aliases Aliases
{
get { return this._aliases; }
set { this._aliases = value; }
}
// Check to see if Aliases property is set
internal bool IsSetAliases()
{
return this._aliases != null;
}
/// <summary>
/// Gets and sets the property Comment. The comment originally specified when this distribution
/// was created.
/// </summary>
public string Comment
{
get { return this._comment; }
set { this._comment = value; }
}
// Check to see if Comment property is set
internal bool IsSetComment()
{
return this._comment != null;
}
/// <summary>
/// Gets and sets the property DomainName. The domain name corresponding to the distribution.
/// For example: d604721fxaaqy9.cloudfront.net.
/// </summary>
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
/// <summary>
/// Gets and sets the property Enabled. Whether the distribution is enabled to accept
/// end user requests for content.
/// </summary>
public bool Enabled
{
get { return this._enabled.GetValueOrDefault(); }
set { this._enabled = value; }
}
// Check to see if Enabled property is set
internal bool IsSetEnabled()
{
return this._enabled.HasValue;
}
/// <summary>
/// Gets and sets the property Id. The identifier for the distribution. For example: EDFDVBD632BHDS5.
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property LastModifiedTime. The date and time the distribution was
/// last modified.
/// </summary>
public DateTime LastModifiedTime
{
get { return this._lastModifiedTime.GetValueOrDefault(); }
set { this._lastModifiedTime = value; }
}
// Check to see if LastModifiedTime property is set
internal bool IsSetLastModifiedTime()
{
return this._lastModifiedTime.HasValue;
}
/// <summary>
/// Gets and sets the property PriceClass.
/// </summary>
public PriceClass PriceClass
{
get { return this._priceClass; }
set { this._priceClass = value; }
}
// Check to see if PriceClass property is set
internal bool IsSetPriceClass()
{
return this._priceClass != null;
}
/// <summary>
/// Gets and sets the property S3Origin. A complex type that contains information about
/// the Amazon S3 bucket from which you want CloudFront to get your media files for distribution.
/// </summary>
public S3Origin S3Origin
{
get { return this._s3Origin; }
set { this._s3Origin = value; }
}
// Check to see if S3Origin property is set
internal bool IsSetS3Origin()
{
return this._s3Origin != null;
}
/// <summary>
/// Gets and sets the property Status. Indicates the current status of the distribution.
/// When the status is Deployed, the distribution's information is fully propagated throughout
/// the Amazon CloudFront system.
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property TrustedSigners. A complex type that specifies the AWS accounts,
/// if any, that you want to allow to create signed URLs for private content. If you want
/// to require signed URLs in requests for objects in the target origin that match the
/// PathPattern for this cache behavior, specify true for Enabled, and specify the applicable
/// values for Quantity and Items. For more information, go to Using a Signed URL to Serve
/// Private Content in the Amazon CloudFront Developer Guide. If you don't want to require
/// signed URLs in requests for objects that match PathPattern, specify false for Enabled
/// and 0 for Quantity. Omit Items. To add, change, or remove one or more trusted signers,
/// change Enabled to true (if it's currently false), change Quantity as applicable, and
/// specify all of the trusted signers that you want to include in the updated distribution.
/// </summary>
public TrustedSigners TrustedSigners
{
get { return this._trustedSigners; }
set { this._trustedSigners = value; }
}
// Check to see if TrustedSigners property is set
internal bool IsSetTrustedSigners()
{
return this._trustedSigners != null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// AsynchronousOneToOneChannel.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.Linq.Parallel
{
/// <summary>
/// This is a bounded channel meant for single-producer/single-consumer scenarios.
/// </summary>
/// <typeparam name="T">Specifies the type of data in the channel.</typeparam>
internal sealed class AsynchronousChannel<T> : IDisposable
{
// The producer will be blocked once the channel reaches a capacity, and unblocked
// as soon as a consumer makes room. A consumer can block waiting until a producer
// enqueues a new element. We use a chunking scheme to adjust the granularity and
// frequency of synchronization, e.g. by enqueueing/dequeueing N elements at a time.
// Because there is only ever a single producer and consumer, we are able to acheive
// efficient and low-overhead synchronization.
//
// In general, the buffer has four logical states:
// FULL <--> OPEN <--> EMPTY <--> DONE
//
// Here is a summary of the state transitions and what they mean:
// * OPEN:
// A buffer starts in the OPEN state. When the buffer is in the READY state,
// a consumer and producer can dequeue and enqueue new elements.
// * OPEN->FULL:
// A producer transitions the buffer from OPEN->FULL when it enqueues a chunk
// that causes the buffer to reach capacity; a producer can no longer enqueue
// new chunks when this happens, causing it to block.
// * FULL->OPEN:
// When the consumer takes a chunk from a FULL buffer, it transitions back from
// FULL->OPEN and the producer is woken up.
// * OPEN->EMPTY:
// When the consumer takes the last chunk from a buffer, the buffer is
// transitioned from OPEN->EMPTY; a consumer can no longer take new chunks,
// causing it to block.
// * EMPTY->OPEN:
// Lastly, when the producer enqueues an item into an EMPTY buffer, it
// transitions to the OPEN state. This causes any waiting consumers to wake up.
// * EMPTY->DONE:
// If the buffer is empty, and the producer is done enqueueing new
// items, the buffer is DONE. There will be no more consumption or production.
//
// Assumptions:
// There is only ever one producer and one consumer operating on this channel
// concurrently. The internal synchronization cannot handle anything else.
//
// ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING **
// VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
//
// There... got your attention now... just in case you didn't read the comments
// very carefully above, this channel will deadlock, become corrupt, and generally
// make you an unhappy camper if you try to use more than 1 producer or more than
// 1 consumer thread to access this thing concurrently. It's been carefully designed
// to avoid locking, but only because of this restriction...
private T[][] _buffer; // The buffer of chunks.
private readonly int _index; // Index of this channel
private volatile int _producerBufferIndex; // Producer's current index, i.e. where to put the next chunk.
private volatile int _consumerBufferIndex; // Consumer's current index, i.e. where to get the next chunk.
private volatile bool _done; // Set to true once the producer is done.
private T[] _producerChunk; // The temporary chunk being generated by the producer.
private int _producerChunkIndex; // A producer's index into its temporary chunk.
private T[] _consumerChunk; // The temporary chunk being enumerated by the consumer.
private int _consumerChunkIndex; // A consumer's index into its temporary chunk.
private int _chunkSize; // The number of elements that comprise a chunk.
// These events are used to signal a waiting producer when the consumer dequeues, and to signal a
// waiting consumer when the producer enqueues.
private ManualResetEventSlim _producerEvent;
private IntValueEvent _consumerEvent;
// These two-valued ints track whether a producer or consumer _might_ be waiting. They are marked
// volatile because they are used in synchronization critical regions of code (see usage below).
private volatile int _producerIsWaiting;
private volatile int _consumerIsWaiting;
private CancellationToken _cancellationToken;
//-----------------------------------------------------------------------------------
// Initializes a new channel with the specific capacity and chunk size.
//
// Arguments:
// orderingHelper - the ordering helper to use for order preservation
// capacity - the maximum number of elements before a producer blocks
// chunkSize - the granularity of chunking on enqueue/dequeue. 0 means default size.
//
// Notes:
// The capacity represents the maximum number of chunks a channel can hold. That
// means producers will actually block after enqueueing capacity*chunkSize
// individual elements.
//
internal AsynchronousChannel(int index, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) :
this(index, Scheduling.DEFAULT_BOUNDED_BUFFER_CAPACITY, chunkSize, cancellationToken, consumerEvent)
{
}
internal AsynchronousChannel(int index, int capacity, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent)
{
if (chunkSize == 0) chunkSize = Scheduling.GetDefaultChunkSize<T>();
Contract.Assert(chunkSize > 0, "chunk size must be greater than 0");
Contract.Assert(capacity > 1, "this impl doesn't support capacity of 1 or 0");
// Initialize a buffer with enough space to hold 'capacity' elements.
// We need one extra unused element as a sentinel to detect a full buffer,
// thus we add one to the capacity requested.
_index = index;
_buffer = new T[capacity + 1][];
_producerBufferIndex = 0;
_consumerBufferIndex = 0;
_producerEvent = new ManualResetEventSlim();
_consumerEvent = consumerEvent;
_chunkSize = chunkSize;
_producerChunk = new T[chunkSize];
_producerChunkIndex = 0;
_cancellationToken = cancellationToken;
}
//-----------------------------------------------------------------------------------
// Checks whether the buffer is full. If the consumer is calling this, they can be
// assured that a true value won't change before the consumer has a chance to dequeue
// elements. That's because only one consumer can run at once. A producer might see
// a true value, however, and then a consumer might transition to non-full, so it's
// not stable for them. Lastly, it's of course possible to see a false value when
// there really is a full queue, it's all dependent on small race conditions.
//
internal bool IsFull
{
get
{
// Read the fields once. One of these is always stable, since the only threads
// that call this are the 1 producer/1 consumer threads.
int producerIndex = _producerBufferIndex;
int consumerIndex = _consumerBufferIndex;
// Two cases:
// 1) Is the producer index one less than the consumer?
// 2) The producer is at the end of the buffer and the consumer at the beginning.
return (producerIndex == consumerIndex - 1) ||
(consumerIndex == 0 && producerIndex == _buffer.Length - 1);
// Note to readers: you might have expected us to consider the case where
// _producerBufferIndex == _buffer.Length && _consumerBufferIndex == 1.
// That is, a producer has gone off the end of the array, but is about to
// wrap around to the 0th element again. We don't need this for a subtle
// reason. It is SAFE for a consumer to think we are non-full when we
// actually are full; it is NOT for a producer; but thankfully, there is
// only one producer, and hence the producer will never see this seemingly
// invalid state. Hence, we're fine producing a false negative. It's all
// based on a race condition we have to deal with anyway.
}
}
//-----------------------------------------------------------------------------------
// Checks whether the buffer is empty. If the producer is calling this, they can be
// assured that a true value won't change before the producer has a chance to enqueue
// an item. That's because only one producer can run at once. A consumer might see
// a true value, however, and then a producer might transition to non-empty.
//
internal bool IsChunkBufferEmpty
{
get
{
// The queue is empty when the producer and consumer are at the same index.
return _producerBufferIndex == _consumerBufferIndex;
}
}
//-----------------------------------------------------------------------------------
// Checks whether the producer is done enqueueing new elements.
//
internal bool IsDone
{
get { return _done; }
}
//-----------------------------------------------------------------------------------
// Used by a producer to flush out any internal buffers that have been accumulating
// data, but which hasn't yet been published to the consumer.
internal void FlushBuffers()
{
TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::FlushBuffers() called",
Environment.CurrentManagedThreadId);
// Ensure that a partially filled chunk is made available to the consumer.
FlushCachedChunk();
}
//-----------------------------------------------------------------------------------
// Used by a producer to signal that it is done producing new elements. This will
// also wake up any consumers that have gone to sleep.
//
internal void SetDone()
{
TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::SetDone() called",
Environment.CurrentManagedThreadId);
// This is set with a volatile write to ensure that, after the consumer
// sees done, they can re-read the enqueued chunks and see the last one we
// enqueued just above.
_done = true;
// We set the event to ensure consumers that may have waited or are
// considering waiting will notice that the producer is done. This is done
// after setting the done flag to facilitate a Dekker-style check/recheck.
//
// Because we can race with threads trying to Dispose of the event, we must
// acquire a lock around our setting, and double-check that the event isn't null.
//
// Update 8/2/2011: Dispose() should never be called with SetDone() concurrently,
// but in order to reduce churn late in the product cycle, we decided not to
// remove the lock.
lock (this)
{
if (_consumerEvent != null)
{
_consumerEvent.Set(_index);
}
}
}
//-----------------------------------------------------------------------------------
// Enqueues a new element to the buffer, possibly blocking in the process.
//
// Arguments:
// item - the new element to enqueue
// timeoutMilliseconds - a timeout (or -1 for no timeout) used in case the buffer
// is full; we return false if it expires
//
// Notes:
// This API will block until the buffer is non-full. This internally buffers
// elements up into chunks, so elements are not immediately available to consumers.
//
internal void Enqueue(T item)
{
// Store the element into our current chunk.
int producerChunkIndex = _producerChunkIndex;
_producerChunk[producerChunkIndex] = item;
// And lastly, if we have filled a chunk, make it visible to consumers.
if (producerChunkIndex == _chunkSize - 1)
{
EnqueueChunk(_producerChunk);
_producerChunk = new T[_chunkSize];
}
_producerChunkIndex = (producerChunkIndex + 1) % _chunkSize;
}
//-----------------------------------------------------------------------------------
// Internal helper to queue a real chunk, not just an element.
//
// Arguments:
// chunk - the chunk to make visible to consumers
// timeoutMilliseconds - an optional timeout; we return false if it expires
//
// Notes:
// This API will block if the buffer is full. A chunk must contain only valid
// elements; if the chunk wasn't filled, it should be trimmed to size before
// enqueueing it for consumers to observe.
//
private void EnqueueChunk(T[] chunk)
{
Contract.Assert(chunk != null);
Contract.Assert(!_done, "can't continue producing after the production is over");
if (IsFull)
WaitUntilNonFull();
Contract.Assert(!IsFull, "expected a non-full buffer");
// We can safely store into the current producer index because we know no consumers
// will be reading from it concurrently.
int bufferIndex = _producerBufferIndex;
_buffer[bufferIndex] = chunk;
// Increment the producer index, taking into count wrapping back to 0. This is a shared
// write; the CLR 2.0 memory model ensures the write won't move before the write to the
// corresponding element, so a consumer won't see the new index but the corresponding
// element in the array as empty.
#pragma warning disable 0420
Interlocked.Exchange(ref _producerBufferIndex, (bufferIndex + 1) % _buffer.Length);
#pragma warning restore 0420
// (If there is a consumer waiting, we have to ensure to signal the event. Unfortunately,
// this requires that we issue a memory barrier: We need to guarantee that the write to
// our producer index doesn't pass the read of the consumer waiting flags; the CLR memory
// model unfortunately permits this reordering. That is handled by using a CAS above.)
if (_consumerIsWaiting == 1 && !IsChunkBufferEmpty)
{
TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waking consumer");
_consumerIsWaiting = 0;
_consumerEvent.Set(_index);
}
}
//-----------------------------------------------------------------------------------
// Just waits until the queue is non-full.
//
private void WaitUntilNonFull()
{
// We must loop; sometimes the producer event will have been set
// prematurely due to the way waiting flags are managed. By looping,
// we will only return from this method when space is truly available.
do
{
// If the queue is full, we have to wait for a consumer to make room.
// Reset the event to unsignaled state before waiting.
_producerEvent.Reset();
// We have to handle the case where a producer and consumer are racing to
// wait simultaneously. For instance, a producer might see a full queue (by
// reading IsFull just above), but meanwhile a consumer might drain the queue
// very quickly, suddenly seeing an empty queue. This would lead to deadlock
// if we aren't careful. Therefore we check the empty/full state AGAIN after
// setting our flag to see if a real wait is warranted.
#pragma warning disable 0420
Interlocked.Exchange(ref _producerIsWaiting, 1);
#pragma warning restore 0420
// (We have to prevent the reads that go into determining whether the buffer
// is full from moving before the write to the producer-wait flag. Hence the CAS.)
// Because we might be racing with a consumer that is transitioning the
// buffer from full to non-full, we must check that the queue is full once
// more. Otherwise, we might decide to wait and never be woken up (since
// we just reset the event).
if (IsFull)
{
// Assuming a consumer didn't make room for us, we can wait on the event.
TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waiting, buffer full");
_producerEvent.Wait(_cancellationToken);
}
else
{
// Reset the flags, we don't actually have to wait after all.
_producerIsWaiting = 0;
}
}
while (IsFull);
}
//-----------------------------------------------------------------------------------
// Flushes any built up elements that haven't been made available to a consumer yet.
// Only safe to be called by a producer.
//
// Notes:
// This API can block if the channel is currently full.
//
private void FlushCachedChunk()
{
// If the producer didn't fill their temporary working chunk, flushing forces an enqueue
// so that a consumer will see the partially filled chunk of elements.
if (_producerChunk != null && _producerChunkIndex != 0)
{
// Trim the partially-full chunk to an array just big enough to hold it.
Contract.Assert(1 <= _producerChunkIndex && _producerChunkIndex <= _chunkSize);
T[] leftOverChunk = new T[_producerChunkIndex];
Array.Copy(_producerChunk, leftOverChunk, _producerChunkIndex);
// And enqueue the right-sized temporary chunk, possibly blocking if it's full.
EnqueueChunk(leftOverChunk);
_producerChunk = null;
}
}
//-----------------------------------------------------------------------------------
// Dequeues the next element in the queue.
//
// Arguments:
// item - a byref to the location into which we'll store the dequeued element
//
// Return Value:
// True if an item was found, false otherwise.
//
internal bool TryDequeue(ref T item)
{
// Ensure we have a chunk to work with.
if (_consumerChunk == null)
{
if (!TryDequeueChunk(ref _consumerChunk))
{
Contract.Assert(_consumerChunk == null);
return false;
}
_consumerChunkIndex = 0;
}
// Retrieve the current item in the chunk.
Contract.Assert(_consumerChunk != null, "consumer chunk is null");
Contract.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds");
item = _consumerChunk[_consumerChunkIndex];
// And lastly, if we have consumed the chunk, null it out so we'll get the
// next one when dequeue is called again.
++_consumerChunkIndex;
if (_consumerChunkIndex == _consumerChunk.Length)
{
_consumerChunk = null;
}
return true;
}
//-----------------------------------------------------------------------------------
// Internal helper method to dequeue a whole chunk.
//
// Arguments:
// chunk - a byref to the location into which we'll store the chunk
//
// Return Value:
// True if a chunk was found, false otherwise.
//
private bool TryDequeueChunk(ref T[] chunk)
{
// This is the non-blocking version of dequeue. We first check to see
// if the queue is empty. If the caller chooses to wait later, they can
// call the overload with an event.
if (IsChunkBufferEmpty)
{
return false;
}
chunk = InternalDequeueChunk();
return true;
}
//-----------------------------------------------------------------------------------
// Blocking dequeue for the next element. This version of the API is used when the
// caller will possibly wait for a new chunk to be enqueued.
//
// Arguments:
// item - a byref for the returned element
// waitEvent - a byref for the event used to signal blocked consumers
//
// Return Value:
// True if an element was found, false otherwise.
//
// Notes:
// If the return value is false, it doesn't always mean waitEvent will be non-
// null. If the producer is done enqueueing, the return will be false and the
// event will remain null. A caller must check for this condition.
//
// If the return value is false and an event is returned, there have been
// side-effects on the channel. Namely, the flag telling producers a consumer
// might be waiting will have been set. DequeueEndAfterWait _must_ be called
// eventually regardless of whether the caller actually waits or not.
//
internal bool TryDequeue(ref T item, ref bool isDone)
{
isDone = false;
// Ensure we have a buffer to work with.
if (_consumerChunk == null)
{
if (!TryDequeueChunk(ref _consumerChunk, ref isDone))
{
Contract.Assert(_consumerChunk == null);
return false;
}
_consumerChunkIndex = 0;
}
// Retrieve the current item in the chunk.
Contract.Assert(_consumerChunk != null, "consumer chunk is null");
Contract.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds");
item = _consumerChunk[_consumerChunkIndex];
// And lastly, if we have consumed the chunk, null it out.
++_consumerChunkIndex;
if (_consumerChunkIndex == _consumerChunk.Length)
{
_consumerChunk = null;
}
return true;
}
//-----------------------------------------------------------------------------------
// Internal helper method to dequeue a whole chunk. This version of the API is used
// when the caller will wait for a new chunk to be enqueued.
//
// Arguments:
// chunk - a byref for the dequeued chunk
// waitEvent - a byref for the event used to signal blocked consumers
//
// Return Value:
// True if a chunk was found, false otherwise.
//
// Notes:
// If the return value is false, it doesn't always mean waitEvent will be non-
// null. If the producer is done enqueueing, the return will be false and the
// event will remain null. A caller must check for this condition.
//
// If the return value is false and an event is returned, there have been
// side-effects on the channel. Namely, the flag telling producers a consumer
// might be waiting will have been set. DequeueEndAfterWait _must_ be called
// eventually regardless of whether the caller actually waits or not.
//
private bool TryDequeueChunk(ref T[] chunk, ref bool isDone)
{
isDone = false;
// We will register our interest in waiting, and then return an event
// that the caller can use to wait.
while (IsChunkBufferEmpty)
{
// If the producer is done and we've drained the queue, we can bail right away.
if (IsDone)
{
// We have to see if the buffer is empty AFTER we've seen that it's done.
// Otherwise, we would possibly miss the elements enqueued before the
// producer signaled that it's done. This is done with a volatile load so
// that the read of empty doesn't move before the read of done.
if (IsChunkBufferEmpty)
{
// Return isDone=true so callers know not to wait
isDone = true;
return false;
}
}
// We have to handle the case where a producer and consumer are racing to
// wait simultaneously. For instance, a consumer might see an empty queue (by
// reading IsChunkBufferEmpty just above), but meanwhile a producer might fill the queue
// very quickly, suddenly seeing a full queue. This would lead to deadlock
// if we aren't careful. Therefore we check the empty/full state AGAIN after
// setting our flag to see if a real wait is warranted.
#pragma warning disable 0420
Interlocked.Exchange(ref _consumerIsWaiting, 1);
#pragma warning restore 0420
// (We have to prevent the reads that go into determining whether the buffer
// is full from moving before the write to the producer-wait flag. Hence the CAS.)
// Because we might be racing with a producer that is transitioning the
// buffer from empty to non-full, we must check that the queue is empty once
// more. Similarly, if the queue has been marked as done, we must not wait
// because we just reset the event, possibly losing as signal. In both cases,
// we would otherwise decide to wait and never be woken up (i.e. deadlock).
if (IsChunkBufferEmpty && !IsDone)
{
// Note that the caller must eventually call DequeueEndAfterWait to set the
// flags back to a state where no consumer is waiting, whether they choose
// to wait or not.
TraceHelpers.TraceInfo("AsynchronousChannel::DequeueChunk - consumer possibly waiting");
return false;
}
else
{
// Reset the wait flags, we don't need to wait after all. We loop back around
// and recheck that the queue isn't empty, done, etc.
_consumerIsWaiting = 0;
}
}
Contract.Assert(!IsChunkBufferEmpty, "single-consumer should never witness an empty queue here");
chunk = InternalDequeueChunk();
return true;
}
//-----------------------------------------------------------------------------------
// Internal helper method that dequeues a chunk after we've verified that there is
// a chunk available to dequeue.
//
// Return Value:
// The dequeued chunk.
//
// Assumptions:
// The caller has verified that a chunk is available, i.e. the queue is non-empty.
//
private T[] InternalDequeueChunk()
{
Contract.Assert(!IsChunkBufferEmpty);
// We can safely read from the consumer index because we know no producers
// will write concurrently.
int consumerBufferIndex = _consumerBufferIndex;
T[] chunk = _buffer[consumerBufferIndex];
// Zero out contents to avoid holding on to memory for longer than necessary. This
// ensures the entire chunk is eligible for GC sooner. (More important for big chunks.)
_buffer[consumerBufferIndex] = null;
// Increment the consumer index, taking into count wrapping back to 0. This is a shared
// write; the CLR 2.0 memory model ensures the write won't move before the write to the
// corresponding element, so a consumer won't see the new index but the corresponding
// element in the array as empty.
#pragma warning disable 0420
Interlocked.Exchange(ref _consumerBufferIndex, (consumerBufferIndex + 1) % _buffer.Length);
#pragma warning restore 0420
// (Unfortunately, this whole sequence requires a memory barrier: We need to guarantee
// that the write to _consumerBufferIndex doesn't pass the read of the wait-flags; the CLR memory
// model sadly permits this reordering. Hence the CAS above.)
if (_producerIsWaiting == 1 && !IsFull)
{
TraceHelpers.TraceInfo("BoundedSingleLockFreeChannel::DequeueChunk - consumer waking producer");
_producerIsWaiting = 0;
_producerEvent.Set();
}
return chunk;
}
//-----------------------------------------------------------------------------------
// Clears the flag set when a blocking Dequeue is called, letting producers know
// the consumer is no longer waiting.
//
internal void DoneWithDequeueWait()
{
// On our way out, be sure to reset the flags.
_consumerIsWaiting = 0;
}
//-----------------------------------------------------------------------------------
// Closes Win32 events possibly allocated during execution.
//
public void Dispose()
{
// We need to take a lock to deal with consumer threads racing to call Dispose
// and producer threads racing inside of SetDone.
//
// Update 8/2/2011: Dispose() should never be called with SetDone() concurrently,
// but in order to reduce churn late in the product cycle, we decided not to
// remove the lock.
lock (this)
{
Contract.Assert(_done, "Expected channel to be done before disposing");
Contract.Assert(_producerEvent != null);
Contract.Assert(_consumerEvent != null);
_producerEvent.Dispose();
_producerEvent = null;
_consumerEvent = null;
}
}
}
}
| |
using System;
using System.Linq;
using UnityEditor.AnimatedValues;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.LWRP;
using UnityEngine.Rendering.PostProcessing;
namespace UnityEditor.Rendering.LWRP
{
[CustomEditorForRenderPipeline(typeof(Camera), typeof(LightweightRenderPipelineAsset))]
[CanEditMultipleObjects]
class LightweightRenderPipelineCameraEditor : CameraEditor
{
internal enum BackgroundType
{
Skybox = 0,
SolidColor,
DontCare,
}
internal class Styles
{
public static GUIContent backgroundType = EditorGUIUtility.TrTextContent("Background Type", "Controls how to initialize the Camera's background.\n\nSkybox initializes camera with Skybox, defaulting to a background color if no skybox is found.\n\nSolid Color initializes background with the background color.\n\nDon't care have undefined values for camera background. Use this only if you are rendering all pixels in the Camera's view.");
public static GUIContent renderingShadows = EditorGUIUtility.TrTextContent("Render Shadows", "Enable this to make this camera render shadows.");
public static GUIContent requireDepthTexture = EditorGUIUtility.TrTextContent("Depth Texture", "On makes this camera create a _CameraDepthTexture, which is a copy of the rendered depth values.\nOff makes the camera not create a depth texture.\nUse Pipeline Settings applies settings from the Render Pipeline Asset.");
public static GUIContent requireOpaqueTexture = EditorGUIUtility.TrTextContent("Opaque Texture", "On makes this camera create a _CameraOpaqueTexture, which is a copy of the rendered view.\nOff makes the camera does not create an opaque texture.\nUse Pipeline Settings applies settings from the Render Pipeline Asset.");
public static GUIContent allowMSAA = EditorGUIUtility.TrTextContent("MSAA", "Use Multi Sample Anti-Aliasing to reduce aliasing.");
public static GUIContent allowHDR = EditorGUIUtility.TrTextContent("HDR", "High Dynamic Range gives you a wider range of light intensities, so your lighting looks more realistic. With it, you can still see details and experience less saturation even with bright light.", (Texture) null);
public static GUIContent rendererType = EditorGUIUtility.TrTextContent("Renderer Type", "Controls which renderer this camera uses.");
public static GUIContent rendererData = EditorGUIUtility.TrTextContent("Renderer Data", "Required by a custom Renderer. If none is assigned this camera uses the one assigned in the Pipeline Settings.");
public readonly GUIContent[] renderingPathOptions = { EditorGUIUtility.TrTextContent("Forward") };
public readonly string hdrDisabledWarning = "HDR rendering is disabled in the Lightweight Render Pipeline asset.";
public readonly string mssaDisabledWarning = "Anti-aliasing is disabled in the Lightweight Render Pipeline asset.";
public static GUIContent[] displayedRendererTypeOverride =
{
new GUIContent("Custom"),
new GUIContent("Use Pipeline Settings"),
};
public static int[] rendererTypeOptions = Enum.GetValues(typeof(RendererOverrideOption)).Cast<int>().ToArray();
public static GUIContent[] cameraBackgroundType =
{
new GUIContent("Skybox"),
new GUIContent("Solid Color"),
new GUIContent("Don't Care"),
};
public static int[] cameraBackgroundValues = { 0, 1, 2};
// This is for adding more data like Pipeline Asset option
public static GUIContent[] displayedAdditionalDataOptions =
{
new GUIContent("Off"),
new GUIContent("On"),
new GUIContent("Use Pipeline Settings"),
};
public static GUIContent[] displayedDepthTextureOverride =
{
new GUIContent("On (Forced due to Post Processing)"),
};
public static int[] additionalDataOptions = Enum.GetValues(typeof(CameraOverrideOption)).Cast<int>().ToArray();
// Using the pipeline Settings
public static GUIContent[] displayedCameraOptions =
{
new GUIContent("Off"),
new GUIContent("Use Pipeline Settings"),
};
public static int[] cameraOptions = { 0, 1 };
};
public Camera camera { get { return target as Camera; } }
// Animation Properties
public bool isSameClearFlags { get { return !settings.clearFlags.hasMultipleDifferentValues; } }
public bool isSameOrthographic { get { return !settings.orthographic.hasMultipleDifferentValues; } }
static readonly int[] s_RenderingPathValues = {0};
static Styles s_Styles;
LightweightRenderPipelineAsset m_LightweightRenderPipeline;
LWRPAdditionalCameraData m_AdditionalCameraData;
SerializedObject m_AdditionalCameraDataSO;
readonly AnimBool m_ShowBGColorAnim = new AnimBool();
readonly AnimBool m_ShowOrthoAnim = new AnimBool();
readonly AnimBool m_ShowTargetEyeAnim = new AnimBool();
SerializedProperty m_AdditionalCameraDataRenderShadowsProp;
SerializedProperty m_AdditionalCameraDataRenderDepthProp;
SerializedProperty m_AdditionalCameraDataRenderOpaqueProp;
SerializedProperty m_AdditionalCameraDataRendererProp;
SerializedProperty m_AdditionalCameraDataRendererDataProp;
void SetAnimationTarget(AnimBool anim, bool initialize, bool targetValue)
{
if (initialize)
{
anim.value = targetValue;
anim.valueChanged.AddListener(Repaint);
}
else
{
anim.target = targetValue;
}
}
void UpdateAnimationValues(bool initialize)
{
SetAnimationTarget(m_ShowBGColorAnim, initialize, isSameClearFlags && (camera.clearFlags == CameraClearFlags.SolidColor || camera.clearFlags == CameraClearFlags.Skybox));
SetAnimationTarget(m_ShowOrthoAnim, initialize, isSameOrthographic && camera.orthographic);
SetAnimationTarget(m_ShowTargetEyeAnim, initialize, settings.targetEye.intValue != (int)StereoTargetEyeMask.Both || PlayerSettings.virtualRealitySupported);
}
public new void OnEnable()
{
m_LightweightRenderPipeline = GraphicsSettings.renderPipelineAsset as LightweightRenderPipelineAsset;
m_AdditionalCameraData = camera.gameObject.GetComponent<LWRPAdditionalCameraData>();
settings.OnEnable();
init(m_AdditionalCameraData);
UpdateAnimationValues(true);
}
void init(LWRPAdditionalCameraData additionalCameraData)
{
if(additionalCameraData == null)
return;
m_AdditionalCameraDataSO = new SerializedObject(additionalCameraData);
m_AdditionalCameraDataRenderShadowsProp = m_AdditionalCameraDataSO.FindProperty("m_RenderShadows");
m_AdditionalCameraDataRenderDepthProp = m_AdditionalCameraDataSO.FindProperty("m_RequiresDepthTextureOption");
m_AdditionalCameraDataRenderOpaqueProp = m_AdditionalCameraDataSO.FindProperty("m_RequiresOpaqueTextureOption");
m_AdditionalCameraDataRendererProp = m_AdditionalCameraDataSO.FindProperty("m_RendererOverrideOption");
m_AdditionalCameraDataRendererDataProp = m_AdditionalCameraDataSO.FindProperty("m_RendererData");
}
public void OnDisable()
{
m_ShowBGColorAnim.valueChanged.RemoveListener(Repaint);
m_ShowOrthoAnim.valueChanged.RemoveListener(Repaint);
m_ShowTargetEyeAnim.valueChanged.RemoveListener(Repaint);
m_LightweightRenderPipeline = null;
}
public override void OnInspectorGUI()
{
if (s_Styles == null)
s_Styles = new Styles();
settings.Update();
UpdateAnimationValues(false);
DrawClearFlags();
using (var group = new EditorGUILayout.FadeGroupScope(m_ShowBGColorAnim.faded))
if (group.visible) settings.DrawBackgroundColor();
settings.DrawCullingMask();
EditorGUILayout.Space();
settings.DrawProjection();
settings.DrawClippingPlanes();
settings.DrawNormalizedViewPort();
EditorGUILayout.Space();
settings.DrawDepth();
DrawTargetTexture();
settings.DrawOcclusionCulling();
DrawHDR();
DrawMSAA();
settings.DrawDynamicResolution();
DrawAdditionalData();
settings.DrawVR();
settings.DrawMultiDisplay();
using (var group = new EditorGUILayout.FadeGroupScope(m_ShowTargetEyeAnim.faded))
if (group.visible) settings.DrawTargetEye();
EditorGUILayout.Space();
EditorGUILayout.Space();
settings.ApplyModifiedProperties();
}
BackgroundType GetBackgroundType(CameraClearFlags clearFlags)
{
switch (clearFlags)
{
case CameraClearFlags.Skybox:
return BackgroundType.Skybox;
case CameraClearFlags.Nothing:
return BackgroundType.DontCare;
// DepthOnly is not supported by design in LWRP. We upgrade it to SolidColor
default:
return BackgroundType.SolidColor;
}
}
void DrawClearFlags()
{
// Converts between ClearFlags and Background Type.
BackgroundType backgroundType = GetBackgroundType((CameraClearFlags) settings.clearFlags.intValue);
EditorGUI.BeginChangeCheck();
BackgroundType selectedType = (BackgroundType)EditorGUILayout.IntPopup(Styles.backgroundType, (int)backgroundType,
Styles.cameraBackgroundType, Styles.cameraBackgroundValues);
if (EditorGUI.EndChangeCheck())
{
CameraClearFlags selectedClearFlags;
switch (selectedType)
{
case BackgroundType.Skybox:
selectedClearFlags = CameraClearFlags.Skybox;
break;
case BackgroundType.DontCare:
selectedClearFlags = CameraClearFlags.Nothing;
break;
default:
selectedClearFlags = CameraClearFlags.SolidColor;
break;
}
settings.clearFlags.intValue = (int) selectedClearFlags;
}
}
void DrawHDR()
{
Rect controlRect = EditorGUILayout.GetControlRect(true);
EditorGUI.BeginProperty(controlRect, Styles.allowHDR, settings.HDR);
int selectedValue = !settings.HDR.boolValue ? 0 : 1;
settings.HDR.boolValue = EditorGUI.IntPopup(controlRect, Styles.allowHDR, selectedValue, Styles.displayedCameraOptions, Styles.cameraOptions) == 1;
EditorGUI.EndProperty();
}
void DrawMSAA()
{
Rect controlRect = EditorGUILayout.GetControlRect(true);
EditorGUI.BeginProperty(controlRect, Styles.allowMSAA, settings.allowMSAA);
int selectedValue = !settings.allowMSAA.boolValue ? 0 : 1;
settings.allowMSAA.boolValue = EditorGUI.IntPopup(controlRect, Styles.allowMSAA, selectedValue, Styles.displayedCameraOptions, Styles.cameraOptions) == 1;
EditorGUI.EndProperty();
}
void DrawTargetTexture()
{
EditorGUILayout.PropertyField(settings.targetTexture);
if (!settings.targetTexture.hasMultipleDifferentValues)
{
var texture = settings.targetTexture.objectReferenceValue as RenderTexture;
int pipelineSamplesCount = m_LightweightRenderPipeline.msaaSampleCount;
if (texture && texture.antiAliasing > pipelineSamplesCount)
{
string pipelineMSAACaps = (pipelineSamplesCount > 1)
? String.Format("is set to support {0}x", pipelineSamplesCount)
: "has MSAA disabled";
EditorGUILayout.HelpBox(String.Format("Camera target texture requires {0}x MSAA. Lightweight pipeline {1}.", texture.antiAliasing, pipelineMSAACaps),
MessageType.Warning, true);
}
}
}
void DrawAdditionalData()
{
bool hasChanged = false;
bool selectedValueShadows;
CameraOverrideOption selectedDepthOption;
CameraOverrideOption selectedOpaqueOption;
RendererOverrideOption selectedRendererOption;
if (m_AdditionalCameraDataSO == null)
{
selectedValueShadows = true;
selectedDepthOption = CameraOverrideOption.UsePipelineSettings;
selectedOpaqueOption = CameraOverrideOption.UsePipelineSettings;
selectedRendererOption = RendererOverrideOption.UsePipelineSettings;
}
else
{
m_AdditionalCameraDataSO.Update();
selectedValueShadows = m_AdditionalCameraData.renderShadows;
selectedDepthOption = (CameraOverrideOption)m_AdditionalCameraDataRenderDepthProp.intValue;
selectedOpaqueOption =(CameraOverrideOption)m_AdditionalCameraDataRenderOpaqueProp.intValue;
selectedRendererOption = (RendererOverrideOption) m_AdditionalCameraDataRendererProp.intValue;
}
// Renderer Type
Rect controlRectRendererType = EditorGUILayout.GetControlRect(true);
if (m_AdditionalCameraDataSO != null)
EditorGUI.BeginProperty(controlRectRendererType, Styles.rendererType, m_AdditionalCameraDataRendererProp);
EditorGUI.BeginChangeCheck();
selectedRendererOption = (RendererOverrideOption)EditorGUI.IntPopup(controlRectRendererType, Styles.rendererType, (int)selectedRendererOption, Styles.displayedRendererTypeOverride, Styles.rendererTypeOptions);
if (EditorGUI.EndChangeCheck())
hasChanged = true;
if (m_AdditionalCameraDataSO != null)
EditorGUI.EndProperty();
if (selectedRendererOption == RendererOverrideOption.Custom && m_AdditionalCameraDataSO != null)
{
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AdditionalCameraDataRendererDataProp, Styles.rendererData);
if (EditorGUI.EndChangeCheck())
hasChanged = true;
EditorGUI.indentLevel--;
}
// Depth Texture
Rect controlRectDepth = EditorGUILayout.GetControlRect(true);
// Need to check if post processing is added and active.
// If it is we will set the int pop to be 1 which is ON and gray it out
bool defaultDrawOfDepthTextureUI = true;
PostProcessLayer ppl = camera.GetComponent<PostProcessLayer>();
var propValue = (int)selectedDepthOption;
if (ppl != null && ppl.isActiveAndEnabled)
{
if ((propValue == 2 && !m_LightweightRenderPipeline.supportsCameraDepthTexture) || propValue == 0)
{
EditorGUI.BeginDisabledGroup(true);
EditorGUI.IntPopup(controlRectDepth, Styles.requireDepthTexture, 0, Styles.displayedDepthTextureOverride, Styles.additionalDataOptions);
EditorGUI.EndDisabledGroup();
defaultDrawOfDepthTextureUI = false;
}
}
if(defaultDrawOfDepthTextureUI)
{
if(m_AdditionalCameraDataSO != null)
EditorGUI.BeginProperty(controlRectDepth, Styles.requireDepthTexture, m_AdditionalCameraDataRenderDepthProp);
EditorGUI.BeginChangeCheck();
selectedDepthOption = (CameraOverrideOption)EditorGUI.IntPopup(controlRectDepth, Styles.requireDepthTexture, (int)selectedDepthOption, Styles.displayedAdditionalDataOptions, Styles.additionalDataOptions);
if (EditorGUI.EndChangeCheck())
{
hasChanged = true;
}
if(m_AdditionalCameraDataSO != null)
EditorGUI.EndProperty();
}
// Opaque Texture
Rect controlRectColor = EditorGUILayout.GetControlRect(true);
// Starting to check the property if we have the scriptable object
if(m_AdditionalCameraDataSO != null)
EditorGUI.BeginProperty(controlRectColor, Styles.requireOpaqueTexture, m_AdditionalCameraDataRenderOpaqueProp);
EditorGUI.BeginChangeCheck();
selectedOpaqueOption = (CameraOverrideOption)EditorGUI.IntPopup(controlRectColor, Styles.requireOpaqueTexture, (int)selectedOpaqueOption, Styles.displayedAdditionalDataOptions, Styles.additionalDataOptions);
if (EditorGUI.EndChangeCheck())
{
hasChanged = true;
}
// Ending to check the property if we have the scriptable object
if(m_AdditionalCameraDataSO != null)
EditorGUI.EndProperty();
// Shadows
Rect controlRectShadows = EditorGUILayout.GetControlRect(true);
if(m_AdditionalCameraDataSO != null)
EditorGUI.BeginProperty(controlRectShadows, Styles.renderingShadows, m_AdditionalCameraDataRenderShadowsProp);
EditorGUI.BeginChangeCheck();
selectedValueShadows = EditorGUI.Toggle(controlRectShadows, Styles.renderingShadows, selectedValueShadows);
if (EditorGUI.EndChangeCheck())
{
hasChanged = true;
}
if(m_AdditionalCameraDataSO != null)
EditorGUI.EndProperty();
if (hasChanged)
{
if (m_AdditionalCameraDataSO == null)
{
m_AdditionalCameraData = camera.gameObject.AddComponent<LWRPAdditionalCameraData>();
init(m_AdditionalCameraData);
}
m_AdditionalCameraDataRenderShadowsProp.boolValue = selectedValueShadows;
m_AdditionalCameraDataRenderDepthProp.intValue = (int)selectedDepthOption;
m_AdditionalCameraDataRenderOpaqueProp.intValue = (int)selectedOpaqueOption;
m_AdditionalCameraDataRendererProp.intValue = (int)selectedRendererOption;
m_AdditionalCameraDataSO.ApplyModifiedProperties();
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public sealed class CompareConditionalControlOperator : ConditionalControlOperator
{
//
// State
//
private CompareAndSetOperator.ActionCondition m_condition;
private bool m_fSigned;
private BasicBlock m_targetBranchTaken;
//
// Constructor Methods
//
private CompareConditionalControlOperator( Debugging.DebugInfo debugInfo ,
OperatorCapabilities capabilities ,
CompareAndSetOperator.ActionCondition condition ,
bool fSigned ) : base( debugInfo, capabilities, OperatorLevel.ConcreteTypes_NoExceptions )
{
m_condition = condition;
m_fSigned = fSigned;
}
//--//
public static CompareConditionalControlOperator New( Debugging.DebugInfo debugInfo ,
CompareAndSetOperator.ActionCondition condition ,
bool fSigned ,
Expression rhsLeft ,
Expression rhsRight ,
BasicBlock targetFalse ,
BasicBlock targetTrue )
{
OperatorCapabilities capabilities = OperatorCapabilities.DoesNotMutateExistingStorage |
OperatorCapabilities.DoesNotAllocateStorage |
OperatorCapabilities.DoesNotReadExistingMutableStorage |
OperatorCapabilities.DoesNotThrow |
OperatorCapabilities.DoesNotReadThroughPointerOperands |
OperatorCapabilities.DoesNotWriteThroughPointerOperands |
OperatorCapabilities.DoesNotCapturePointerOperands ;
switch(condition)
{
case CompareAndSetOperator.ActionCondition.EQ:
case CompareAndSetOperator.ActionCondition.NE:
capabilities |= OperatorCapabilities.IsCommutative;
break;
default:
capabilities |= OperatorCapabilities.IsNonCommutative;
break;
}
CompareConditionalControlOperator res = new CompareConditionalControlOperator( debugInfo, capabilities, condition, fSigned );
res.SetRhs( rhsLeft, rhsRight );
res.m_targetBranchNotTaken = targetFalse;
res.m_targetBranchTaken = targetTrue;
return res;
}
//--//
//
// Helper Methods
//
public override Operator Clone( CloningContext context )
{
return RegisterAndCloneState( context, new CompareConditionalControlOperator( m_debugInfo, m_capabilities, m_condition, m_fSigned ) );
}
protected override void CloneState( CloningContext context ,
Operator clone )
{
CompareConditionalControlOperator clone2 = (CompareConditionalControlOperator)clone;
clone2.m_targetBranchTaken = context.Clone( m_targetBranchTaken );
base.CloneState( context, clone );
}
//--//
public override void ApplyTransformation( TransformationContextForIR context )
{
context.Push( this );
base.ApplyTransformation( context );
context.Transform( ref m_condition );
context.Transform( ref m_fSigned );
context.Transform( ref m_targetBranchTaken );
context.Pop();
}
//--//
protected override void UpdateSuccessorInformation()
{
base.UpdateSuccessorInformation();
m_basicBlock.LinkToNormalBasicBlock( m_targetBranchTaken );
}
//--//
public override bool SubstituteTarget( BasicBlock oldBB ,
BasicBlock newBB )
{
bool fChanged = base.SubstituteTarget( oldBB, newBB );
if(m_targetBranchTaken == oldBB)
{
m_targetBranchTaken = newBB;
BumpVersion();
fChanged = true;
}
return fChanged;
}
//--//
public override bool Simplify( Operator[][] defChains ,
Operator[][] useChains ,
VariableExpression.Property[] properties )
{
var exL = FindConstantOrigin( this.FirstArgument , defChains, useChains, properties );
var exR = FindConstantOrigin( this.SecondArgument, defChains, useChains, properties );
if(exL != null && exR != null)
{
bool res;
if(exL.IsValueInteger)
{
if(!exR.IsValueInteger)
{
throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this );
}
if(this.Signed)
{
long valL;
long valR;
if(exL.GetAsSignedInteger( out valL ) == false ||
exR.GetAsSignedInteger( out valR ) == false )
{
return false;
}
switch(m_condition)
{
case CompareAndSetOperator.ActionCondition.EQ: res = (valL == valR); break;
case CompareAndSetOperator.ActionCondition.GE: res = (valL >= valR); break;
case CompareAndSetOperator.ActionCondition.GT: res = (valL > valR); break;
case CompareAndSetOperator.ActionCondition.LE: res = (valL <= valR); break;
case CompareAndSetOperator.ActionCondition.LT: res = (valL < valR); break;
case CompareAndSetOperator.ActionCondition.NE: res = (valL != valR); break;
default:
return false;
}
}
else
{
ulong valL;
ulong valR;
if(exL.GetAsUnsignedInteger( out valL ) == false ||
exR.GetAsUnsignedInteger( out valR ) == false )
{
return false;
}
switch(m_condition)
{
case CompareAndSetOperator.ActionCondition.EQ: res = (valL == valR); break;
case CompareAndSetOperator.ActionCondition.GE: res = (valL >= valR); break;
case CompareAndSetOperator.ActionCondition.GT: res = (valL > valR); break;
case CompareAndSetOperator.ActionCondition.LE: res = (valL <= valR); break;
case CompareAndSetOperator.ActionCondition.LT: res = (valL < valR); break;
case CompareAndSetOperator.ActionCondition.NE: res = (valL != valR); break;
default:
return false;
}
}
}
else if(exL.IsValueFloatingPoint)
{
if(!exR.IsValueFloatingPoint)
{
throw TypeConsistencyErrorException.Create( "Cannot mix integer and floating-point values in the same operation: {0}", this );
}
object valL = exL.Value;
object valR = exR.Value;
if(valL is float)
{
if(!(valR is float))
{
throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this );
}
float valL2 = (float)valL;
float valR2 = (float)valR;
switch(m_condition)
{
case CompareAndSetOperator.ActionCondition.EQ: res = (valL2 == valR2); break;
case CompareAndSetOperator.ActionCondition.GE: res = (valL2 >= valR2); break;
case CompareAndSetOperator.ActionCondition.GT: res = (valL2 > valR2); break;
case CompareAndSetOperator.ActionCondition.LE: res = (valL2 <= valR2); break;
case CompareAndSetOperator.ActionCondition.LT: res = (valL2 < valR2); break;
case CompareAndSetOperator.ActionCondition.NE: res = (valL2 != valR2); break;
default:
return false;
}
}
else if(valL is double)
{
if(!(valR is double))
{
throw TypeConsistencyErrorException.Create( "Cannot mix single and double values in the same operation: {0}", this );
}
double valL2 = (double)valL;
double valR2 = (double)valR;
switch(m_condition)
{
case CompareAndSetOperator.ActionCondition.EQ: res = (valL2 == valR2); break;
case CompareAndSetOperator.ActionCondition.GE: res = (valL2 >= valR2); break;
case CompareAndSetOperator.ActionCondition.GT: res = (valL2 > valR2); break;
case CompareAndSetOperator.ActionCondition.LE: res = (valL2 <= valR2); break;
case CompareAndSetOperator.ActionCondition.LT: res = (valL2 < valR2); break;
case CompareAndSetOperator.ActionCondition.NE: res = (valL2 != valR2); break;
default:
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
this.SubstituteWithOperator( UnconditionalControlOperator.New( this.DebugInfo, res ? this.TargetBranchTaken : this.TargetBranchNotTaken ), SubstitutionFlags.Default );
return true;
}
return false;
}
//--//
//
// Access Methods
//
public CompareAndSetOperator.ActionCondition Condition
{
get
{
return m_condition;
}
}
public CompareAndSetOperator.ActionCondition InvertedCondition
{
get
{
switch(m_condition)
{
case CompareAndSetOperator.ActionCondition.EQ: return CompareAndSetOperator.ActionCondition.NE;
case CompareAndSetOperator.ActionCondition.GE: return CompareAndSetOperator.ActionCondition.LT;
case CompareAndSetOperator.ActionCondition.GT: return CompareAndSetOperator.ActionCondition.LE;
case CompareAndSetOperator.ActionCondition.LE: return CompareAndSetOperator.ActionCondition.GT;
case CompareAndSetOperator.ActionCondition.LT: return CompareAndSetOperator.ActionCondition.GE;
case CompareAndSetOperator.ActionCondition.NE: return CompareAndSetOperator.ActionCondition.EQ;
}
throw TypeConsistencyErrorException.Create( "Unexpected condition value: {0}", m_condition );
}
}
public bool Signed
{
get
{
return m_fSigned;
}
}
public BasicBlock TargetBranchTaken
{
get
{
return m_targetBranchTaken;
}
}
//--//
//
// Debug Methods
//
public override void InnerToString( System.Text.StringBuilder sb )
{
sb.Append( "CompareConditionalControlOperator(" );
base.InnerToString( sb );
sb.AppendFormat( " Cond: {0}", m_condition );
sb.AppendFormat( " Signed: {0}", m_fSigned );
sb.AppendFormat( " Taken: {0}", m_targetBranchTaken.SpanningTreeIndex );
sb.Append( ")" );
}
public override string FormatOutput( IIntermediateRepresentationDumper dumper )
{
return dumper.FormatOutput( "if {0} {1}{2} {3} then goto {4} else goto {5}", this.FirstArgument, m_condition, m_fSigned ? ".signed" : ".unsigned", this.SecondArgument, m_targetBranchTaken, m_targetBranchNotTaken );
}
}
}
| |
// 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.
#pragma warning disable CS0067 // events are declared but not used
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.Loader;
using System.IO;
using System.Security.Principal;
namespace System
{
public partial class AppDomain : MarshalByRefObject
{
private static readonly AppDomain s_domain = new AppDomain();
private readonly object _forLock = new object();
private IPrincipal _defaultPrincipal;
private AppDomain() { }
public static AppDomain CurrentDomain => s_domain;
public string BaseDirectory => AppContext.BaseDirectory;
public string RelativeSearchPath => null;
public event UnhandledExceptionEventHandler UnhandledException
{
add { AppContext.UnhandledException += value; }
remove { AppContext.UnhandledException -= value; }
}
public string DynamicDirectory => null;
[ObsoleteAttribute("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetDynamicBase(string path) { }
public string FriendlyName
{
get
{
Assembly assembly = Assembly.GetEntryAssembly();
return assembly != null ? assembly.GetName().Name : "DefaultDomain";
}
}
public int Id => 1;
public bool IsFullyTrusted => true;
public bool IsHomogenous => true;
public event EventHandler DomainUnload;
public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException
{
add
{
#if uapaot
AppContext.SetAppDomain(this);
#endif
AppContext.FirstChanceException += value;
}
remove { AppContext.FirstChanceException -= value; }
}
public event EventHandler ProcessExit
{
add { AppContext.ProcessExit += value; }
remove { AppContext.ProcessExit -= value; }
}
public string ApplyPolicy(string assemblyName)
{
if (assemblyName == null)
{
throw new ArgumentNullException(nameof(assemblyName));
}
if (assemblyName.Length == 0 || assemblyName[0] == '\0')
{
throw new ArgumentException(SR.ZeroLengthString);
}
return assemblyName;
}
public static AppDomain CreateDomain(string friendlyName)
{
if (friendlyName == null) throw new ArgumentNullException(nameof(friendlyName));
throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomains);
}
public int ExecuteAssembly(string assemblyFile) => ExecuteAssembly(assemblyFile, null);
public int ExecuteAssembly(string assemblyFile, string[] args)
{
if (assemblyFile == null)
{
throw new ArgumentNullException(nameof(assemblyFile));
}
string fullPath = Path.GetFullPath(assemblyFile);
Assembly assembly = Assembly.LoadFile(fullPath);
return ExecuteAssembly(assembly, args);
}
public int ExecuteAssembly(string assemblyFile, string[] args, byte[] hashValue, Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // This api is only meaningful for very specific partial trust/CAS scenarios
}
private int ExecuteAssembly(Assembly assembly, string[] args)
{
MethodInfo entry = assembly.EntryPoint;
if (entry == null)
{
throw new MissingMethodException(SR.EntryPointNotFound + assembly.FullName);
}
object result = null;
try
{
result = entry.GetParameters().Length > 0 ?
entry.Invoke(null, new object[] { args }) :
entry.Invoke(null, null);
}
catch (TargetInvocationException targetInvocationException)
{
if (targetInvocationException.InnerException == null)
{
throw;
}
// We are catching the TIE here and throws the inner exception only,
// this is needed to have a consistent exception story with desktop clr
ExceptionDispatchInfo.Throw(targetInvocationException.InnerException);
}
return result != null ? (int)result : 0;
}
public int ExecuteAssemblyByName(AssemblyName assemblyName, params string[] args) =>
ExecuteAssembly(Assembly.Load(assemblyName), args);
public int ExecuteAssemblyByName(string assemblyName) =>
ExecuteAssemblyByName(assemblyName, null);
public int ExecuteAssemblyByName(string assemblyName, params string[] args) =>
ExecuteAssembly(Assembly.Load(assemblyName), args);
public object GetData(string name) => AppContext.GetData(name);
public void SetData(string name, object data) => AppContext.SetData(name, data);
public bool? IsCompatibilitySwitchSet(string value)
{
bool result;
return AppContext.TryGetSwitch(value, out result) ? result : default(bool?);
}
public bool IsDefaultAppDomain() => true;
public bool IsFinalizingForUnload() => false;
public override string ToString() =>
SR.AppDomain_Name + FriendlyName + Environment.NewLine + SR.AppDomain_NoContextPolicies;
public static void Unload(AppDomain domain)
{
if (domain == null)
{
throw new ArgumentNullException(nameof(domain));
}
throw new CannotUnloadAppDomainException(SR.NotSupported);
}
public Assembly Load(byte[] rawAssembly) => Assembly.Load(rawAssembly);
public Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) => Assembly.Load(rawAssembly, rawSymbolStore);
public Assembly Load(AssemblyName assemblyRef) => Assembly.Load(assemblyRef);
public Assembly Load(string assemblyString) => Assembly.Load(assemblyString);
public Assembly[] ReflectionOnlyGetAssemblies() => Array.Empty<Assembly>();
public static bool MonitoringIsEnabled
{
get { return false; }
set
{
if (!value)
{
throw new ArgumentException(SR.Arg_MustBeTrue);
}
throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomain_ResMon);
}
}
public long MonitoringSurvivedMemorySize { get { throw CreateResMonNotAvailException(); } }
public static long MonitoringSurvivedProcessMemorySize { get { throw CreateResMonNotAvailException(); } }
public long MonitoringTotalAllocatedMemorySize { get { throw CreateResMonNotAvailException(); } }
public TimeSpan MonitoringTotalProcessorTime { get { throw CreateResMonNotAvailException(); } }
private static Exception CreateResMonNotAvailException() => new InvalidOperationException(SR.PlatformNotSupported_AppDomain_ResMon);
[ObsoleteAttribute("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)]
public static int GetCurrentThreadId() => Environment.CurrentManagedThreadId;
public bool ShadowCopyFiles => false;
[ObsoleteAttribute("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void AppendPrivatePath(string path) { }
[ObsoleteAttribute("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void ClearPrivatePath() { }
[ObsoleteAttribute("AppDomain.ClearShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void ClearShadowCopyPath() { }
[ObsoleteAttribute("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetCachePath(string path) { }
[ObsoleteAttribute("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetShadowCopyFiles() { }
[ObsoleteAttribute("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetShadowCopyPath(string path) { }
public Assembly[] GetAssemblies() => AssemblyLoadContext.GetLoadedAssemblies();
public event AssemblyLoadEventHandler AssemblyLoad
{
add { AssemblyLoadContext.AssemblyLoad += value; }
remove { AssemblyLoadContext.AssemblyLoad -= value; }
}
public event ResolveEventHandler AssemblyResolve
{
add { AssemblyLoadContext.AssemblyResolve += value; }
remove { AssemblyLoadContext.AssemblyResolve -= value; }
}
public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
public event ResolveEventHandler TypeResolve
{
add { AssemblyLoadContext.TypeResolve += value; }
remove { AssemblyLoadContext.TypeResolve -= value; }
}
public event ResolveEventHandler ResourceResolve
{
add { AssemblyLoadContext.ResourceResolve += value; }
remove { AssemblyLoadContext.ResourceResolve -= value; }
}
public void SetPrincipalPolicy(PrincipalPolicy policy) { }
public void SetThreadPrincipal(IPrincipal principal)
{
if (principal == null)
{
throw new ArgumentNullException(nameof(principal));
}
lock (_forLock)
{
// Check that principal has not been set previously.
if (_defaultPrincipal != null)
{
throw new SystemException(SR.AppDomain_Policy_PrincipalTwice);
}
_defaultPrincipal = principal;
}
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace Microsoft.PowerShell.Commands
{
#region PSSnapInCommandBase
/// <summary>
/// Base class for all the pssnapin related cmdlets.
/// </summary>
public abstract class PSSnapInCommandBase : PSCmdlet, IDisposable
{
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed
/// </summary>
///
private bool _disposed;
/// <summary>
/// Dispose method unloads the app domain and the
/// resource reader if it was created.
/// </summary>
///
public void Dispose()
{
if (_disposed == false)
{
if (_resourceReader != null)
{
_resourceReader.Dispose();
_resourceReader = null;
}
GC.SuppressFinalize(this);
}
_disposed = true;
}
#endregion IDisposable Members
#region Cmdlet Methods
/// <summary>
/// Disposes the resource reader.
/// </summary>
///
protected override void EndProcessing()
{
if (_resourceReader != null)
{
_resourceReader.Dispose();
_resourceReader = null;
}
}
#endregion CmdletMethods
#region Internal Methods
/// <summary>
/// Runspace configuration for the current engine
/// </summary>
/// <remarks>
/// PSSnapIn cmdlets need <see cref="RunspaceConfigForSingleShell"/> object to work with.
/// </remarks>
internal RunspaceConfigForSingleShell Runspace
{
get
{
RunspaceConfigForSingleShell runSpace = Context.RunspaceConfiguration as RunspaceConfigForSingleShell;
if (runSpace == null)
{
return null;
}
return runSpace;
}
}
/// <summary>
/// Writes a non-terminating error onto the pipeline.
/// </summary>
/// <param name="targetObject">Object which caused this exception.</param>
/// <param name="errorId">ErrorId for this error.</param>
/// <param name="innerException">Complete exception object.</param>
/// <param name="category">ErrorCategory for this exception.</param>
internal void WriteNonTerminatingError(
Object targetObject,
string errorId,
Exception innerException,
ErrorCategory category)
{
WriteError(new ErrorRecord(innerException, errorId, category, targetObject));
}
/// <summary>
/// Searches the input list for the pattern supplied.
/// </summary>
/// <param name="searchList">Input list</param>
/// <param name="pattern">pattern with wildcards</param>
/// <returns>
/// A collection of string objects (representing PSSnapIn name)
/// that match the pattern.
/// </returns>
/// <remarks>
/// Please note that this method will use WildcardPattern class.
/// So it wont support all the 'regex' patterns
/// </remarks>
internal Collection<string>
SearchListForPattern(Collection<PSSnapInInfo> searchList,
string pattern)
{
Collection<string> listToReturn = new Collection<string>();
if (null == searchList)
{
// return an empty list
return listToReturn;
}
WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
// We are doing WildCard search
foreach (PSSnapInInfo psSnapIn in searchList)
{
if (matcher.IsMatch(psSnapIn.Name))
{
listToReturn.Add(psSnapIn.Name);
}
}
// the returned list might contain 0 objects
return listToReturn;
}
/// <summary>
/// See if the snapin is already loaded..returns load snapin info if true, null otherwise.
/// </summary>
/// <returns></returns>
internal static PSSnapInInfo IsSnapInLoaded(Collection<PSSnapInInfo> loadedSnapins, PSSnapInInfo psSnapInInfo)
{
if (null == loadedSnapins)
{
return null;
}
foreach (PSSnapInInfo loadedPSSnapInInfo in loadedSnapins)
{
// See if the assembly-qualified names match and return the existing PSSnapInInfo
// if they do.
string loadedSnapInAssemblyName = loadedPSSnapInInfo.AssemblyName;
if (string.Equals(loadedPSSnapInInfo.Name, psSnapInInfo.Name, StringComparison.OrdinalIgnoreCase) &&
!string.IsNullOrEmpty(loadedSnapInAssemblyName)
&& string.Equals(loadedSnapInAssemblyName, psSnapInInfo.AssemblyName, System.StringComparison.OrdinalIgnoreCase))
{
return loadedPSSnapInInfo;
}
}
return null;
}
/// <summary>
/// Routine to get the list of loaded snapins...
/// </summary>
/// <returns></returns>
protected internal Collection<PSSnapInInfo> GetSnapIns(string pattern)
{
// If RunspaceConfiguration is not null, then return the list that it has
if (Runspace != null)
{
if (pattern != null)
return Runspace.ConsoleInfo.GetPSSnapIn(pattern, _shouldGetAll);
else
return Runspace.ConsoleInfo.PSSnapIns;
}
WildcardPattern matcher = null;
if (!String.IsNullOrEmpty(pattern))
{
bool doWildCardSearch = WildcardPattern.ContainsWildcardCharacters(pattern);
if (!doWildCardSearch)
{
// Verify PSSnapInID..
// This will throw if it not a valid name
PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern);
}
matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
}
Collection<PSSnapInInfo> snapins = new Collection<PSSnapInInfo>();
if (_shouldGetAll)
{
foreach (PSSnapInInfo snapinKey in PSSnapInReader.ReadAll())
{
if (matcher == null || matcher.IsMatch(snapinKey.Name))
snapins.Add(snapinKey);
}
}
else
{
// Otherwise, just scan through the list of cmdlets and rebuild the table.
List<CmdletInfo> cmdlets = InvokeCommand.GetCmdlets();
Dictionary<PSSnapInInfo, bool> snapinTable = new Dictionary<PSSnapInInfo, bool>();
foreach (CmdletInfo cmdlet in cmdlets)
{
PSSnapInInfo snapin = cmdlet.PSSnapIn;
if (snapin != null && !snapinTable.ContainsKey(snapin))
snapinTable.Add(snapin, true);
}
foreach (PSSnapInInfo snapinKey in snapinTable.Keys)
{
if (matcher == null || matcher.IsMatch(snapinKey.Name))
snapins.Add(snapinKey);
}
}
return snapins;
}
/// <summary>
/// Use to indicate if all registered snapins should be listed by GetSnapins...
/// </summary>
protected internal bool ShouldGetAll
{
get { return _shouldGetAll; }
set { _shouldGetAll = value; }
}
private bool _shouldGetAll;
/// <summary>
/// A single instance of the resource indirect reader. This is used to load the
/// managed resource assemblies in a different app-domain so that they can be unloaded.
/// For perf reasons we only want to create one instance for the duration of the command
/// and be sure it gets disposed when the command completes.
/// </summary>
///
internal RegistryStringResourceIndirect ResourceReader
{
get {
return _resourceReader ?? (_resourceReader = RegistryStringResourceIndirect.GetResourceIndirectReader());
}
}
private RegistryStringResourceIndirect _resourceReader;
#endregion
}
#endregion
#region Add-PSSnapIn
/// <summary>
/// Class that implements add-pssnapin cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Add, "PSSnapin", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113281")]
[OutputType(typeof(PSSnapInInfo))]
public sealed class AddPSSnapinCommand : PSSnapInCommandBase
{
#region Parameters
/// <summary>
/// Property that gets/sets PSSnapIn Ids for the cmdlet.
/// </summary>
/// <value>An array of strings representing PSSnapIn ids.</value>
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string[] Name
{
get
{
return _pssnapins;
}
set
{
_pssnapins = value;
}
}
private string[] _pssnapins;
/// <summary>
/// Gets or sets the Passthru flag for the operation.
/// If true, the PSSnapInInfo object is passed down the
/// output pipeline.
/// </summary>
[Parameter()]
public SwitchParameter PassThru
{
get
{
return _passThru;
}
set
{
_passThru = value;
}
}
private bool _passThru;
#endregion
#region Overrides
/// <summary>
/// Adds pssnapins to console file and loads the pssnapin dlls into
/// the current monad runtime.
/// </summary>
/// <remarks>
/// The new pssnapin information is not stored in the console file until
/// the file is saved.
/// </remarks>
protected override void ProcessRecord()
{
// Cache for the information stored in the registry
// update the cache the first time a wildcard is found..
Collection<PSSnapInInfo> listToSearch = null;
foreach (string pattern in _pssnapins)
{
Exception exception = null;
Collection<string> listToAdd = new Collection<string>();
try
{
// check whether there are any wildcard characters
bool doWildCardSearch = WildcardPattern.ContainsWildcardCharacters(pattern);
if (doWildCardSearch)
{
// wildcard found in the pattern
// Get all the possible candidates for current monad version
if (listToSearch == null)
{
// cache snapin registry information...
// For 3.0 PowerShell, we still use "1" as the registry version key for
// Snapin and Custom shell lookup/discovery.
// For 3.0 PowerShell, we use "3" as the registry version key only for Engine
// related data like ApplicationBase etc.
listToSearch = PSSnapInReader.ReadAll(PSVersionInfo.RegistryVersion1Key);
}
listToAdd = SearchListForPattern(listToSearch, pattern);
// listToAdd wont be null..
Diagnostics.Assert(listToAdd != null, "Pattern matching returned null");
if (listToAdd.Count == 0)
{
if (_passThru)
{
// passThru is specified and we have nothing to add...
WriteNonTerminatingError(pattern, "NoPSSnapInsFound",
PSTraceSource.NewArgumentException(pattern,
MshSnapInCmdletResources.NoPSSnapInsFound, pattern),
ErrorCategory.InvalidArgument);
}
continue;
}
}
else
{
listToAdd.Add(pattern);
}
// now add all the snapins for this pattern...
AddPSSnapIns(listToAdd);
}
catch (PSArgumentException ae)
{
exception = ae;
}
catch (System.Security.SecurityException se)
{
exception = se;
}
if (exception != null)
{
WriteNonTerminatingError(pattern,
"AddPSSnapInRead",
exception,
ErrorCategory.InvalidArgument);
}
}
}
#endregion
#region Private Methods
/// <summary>
/// Adds one or more snapins
/// </summary>
/// <param name="snapInList">List of snapin IDs</param>
/// <remarks>
/// This is a helper method and should not throw any
/// exceptions. All exceptions are caught and displayed
/// to the user using write* methods
/// </remarks>
private void AddPSSnapIns(Collection<string> snapInList)
{
if (snapInList == null)
{
// nothing to add
return;
}
//BUGBUG TODO - brucepay - this is a workaround for not being able to dynamically update
// the set of cmdlets in a runspace if there is no RunspaceConfiguration object.
// This is a temporary fix to unblock remoting tests and need to be corrected/completed
// before we can ship...
// If there is no RunspaceConfig object, then
// use an InitialSessionState object to gather and
// bind the cmdlets from the snapins...
if (Context.RunspaceConfiguration == null)
{
Collection<PSSnapInInfo> loadedSnapins = base.GetSnapIns(null);
InitialSessionState iss = InitialSessionState.Create();
bool isAtleastOneSnapinLoaded = false;
foreach (string snapIn in snapInList)
{
if (InitialSessionState.IsEngineModule(snapIn))
{
WriteNonTerminatingError(snapIn, "LoadSystemSnapinAsModule",
PSTraceSource.NewArgumentException(snapIn,
MshSnapInCmdletResources.LoadSystemSnapinAsModule, snapIn),
ErrorCategory.InvalidArgument);
}
else
{
PSSnapInException warning;
try
{
// Read snapin data
PSSnapInInfo newPSSnapIn = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), snapIn);
PSSnapInInfo psSnapInInfo = IsSnapInLoaded(loadedSnapins, newPSSnapIn);
// that means snapin is not already loaded ..so load the snapin
// now.
if (null == psSnapInInfo)
{
psSnapInInfo = iss.ImportPSSnapIn(snapIn, out warning);
isAtleastOneSnapinLoaded = true;
Context.InitialSessionState.ImportedSnapins.Add(psSnapInInfo.Name, psSnapInInfo);
}
// Write psSnapInInfo object only if passthru is specified.
if (_passThru)
{
// Load the pssnapin info properties that are localizable and redirected in the registry
psSnapInInfo.LoadIndirectResources(ResourceReader);
WriteObject(psSnapInInfo);
}
}
catch (PSSnapInException pse)
{
WriteNonTerminatingError(snapIn, "AddPSSnapInRead", pse, ErrorCategory.InvalidData);
}
}
}
if (isAtleastOneSnapinLoaded)
{
// Now update the session state with the new stuff...
iss.Bind(Context, /*updateOnly*/ true);
}
return;
}
foreach (string psSnapIn in snapInList)
{
Exception exception = null;
try
{
PSSnapInException warning = null;
PSSnapInInfo psSnapInInfo = this.Runspace.AddPSSnapIn(psSnapIn, out warning);
if (warning != null)
{
WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", warning, ErrorCategory.InvalidData);
}
// Write psSnapInInfo object only if passthru is specified.
if (_passThru)
{
// Load the pssnapin info properties that are localizable and redirected in the registry
psSnapInInfo.LoadIndirectResources(ResourceReader);
WriteObject(psSnapInInfo);
}
}
catch (PSArgumentException ae)
{
exception = ae;
}
catch (PSSnapInException sle)
{
exception = sle;
}
catch (System.Security.SecurityException se)
{
exception = se;
}
if (exception != null)
{
WriteNonTerminatingError(psSnapIn,
"AddPSSnapInRead",
exception,
ErrorCategory.InvalidArgument);
}
}
}
#endregion
}
#endregion
#region Remove-PSSnapIn
/// <summary>
/// Class that implements remove-pssnapin cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "PSSnapin", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113378")]
[OutputType(typeof(PSSnapInInfo))]
public sealed class RemovePSSnapinCommand : PSSnapInCommandBase
{
#region Parameters
/// <summary>
/// Property that gets/sets PSSnapIn Ids for the cmdlet.
/// </summary>
/// <value>An array of strings representing PSSnapIn ids.</value>
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string[] Name
{
get
{
return _pssnapins;
}
set
{
_pssnapins = value;
}
}
private string[] _pssnapins;
/// <summary>
/// Gets or sets the Passthru flag for the operation.
/// If true, the PSSnapInInfo object is also passed
/// down the output pipeline.
/// </summary>
[Parameter()]
public SwitchParameter PassThru
{
get
{
return _passThru;
}
set
{
_passThru = value;
}
}
private bool _passThru;
#endregion
#region Overrides
/// <summary>
/// Removes pssnapins from the current console file.
/// </summary>
/// <remarks>
/// The pssnapin is not unloaded from the current engine. So all the cmdlets that are
/// represented by this pssnapin will continue to work.
/// </remarks>
protected override void ProcessRecord()
{
foreach (string psSnapIn in _pssnapins)
{
Collection<PSSnapInInfo> snapIns = GetSnapIns(psSnapIn);
// snapIns won't be null..
Diagnostics.Assert(snapIns != null, "GetSnapIns() returned null");
if (snapIns.Count == 0)
{
WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound",
PSTraceSource.NewArgumentException(psSnapIn,
MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn),
ErrorCategory.InvalidArgument);
continue;
}
foreach (PSSnapInInfo snapIn in snapIns)
{
// confirm the operation first
// this is always false if WhatIf is set
if (ShouldProcess(snapIn.Name))
{
Exception exception = null;
if (this.Runspace == null && this.Context.InitialSessionState != null)
{
try
{
// Check if this snapin can be removed
// Monad has specific restrictions on the mshsnapinid like
// mshsnapinid should be A-Za-z0-9.-_ etc.
PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(snapIn.Name);
if (MshConsoleInfo.IsDefaultPSSnapIn(snapIn.Name, this.Context.InitialSessionState.defaultSnapins))
{
throw PSTraceSource.NewArgumentException(snapIn.Name, ConsoleInfoErrorStrings.CannotRemoveDefault, snapIn.Name);
}
// Handle the initial session state case...
InitialSessionState iss = InitialSessionState.Create();
PSSnapInException warning;
// Get the snapin information...
iss.ImportPSSnapIn(snapIn, out warning);
iss.Unbind(Context);
Context.InitialSessionState.ImportedSnapins.Remove(snapIn.Name);
}
catch (PSArgumentException ae)
{
exception = ae;
}
if (exception != null)
{
WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
}
}
else
{
try
{
PSSnapInException warning = null;
PSSnapInInfo psSnapInInfo = this.Runspace.RemovePSSnapIn(snapIn.Name, out warning);
if (warning != null)
{
WriteNonTerminatingError(snapIn.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData);
}
if (_passThru)
{
// Load the pssnapin info properties that are localizable and redirected in the registry
psSnapInInfo.LoadIndirectResources(ResourceReader);
WriteObject(psSnapInInfo);
}
}
catch (PSArgumentException ae)
{
exception = ae;
}
if (exception != null)
{
WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
}
}
} // ShouldContinue
}
}
}
#endregion
}
#endregion
#region Get-PSSnapIn
/// <summary>
/// Class that implements get-pssnapin cmdlet.
/// </summary>
[Cmdlet(VerbsCommon.Get, "PSSnapin", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113330")]
[OutputType(typeof(PSSnapInInfo))]
public sealed class GetPSSnapinCommand : PSSnapInCommandBase
{
#region Parameters
/// <summary>
/// Name(s) of PSSnapIn(s).
/// </summary>
[Parameter(Position = 0, Mandatory = false)]
public string[] Name
{
get
{
return _pssnapins;
}
set
{
_pssnapins = value;
}
}
private string[] _pssnapins;
/// <summary>
/// Property that determines whether to get all pssnapins that are currently
/// registered ( in registry ).
/// </summary>
/// <value>
/// A boolean that determines whether to get all pssnapins that are currently
/// registered ( in registry ).
/// </value>
[Parameter(Mandatory = false)]
public SwitchParameter Registered
{
get
{
return ShouldGetAll;
}
set
{
ShouldGetAll = value;
}
}
#endregion
#region Overrides
/// <summary>
/// Constructs PSSnapInfo objects as requested by the user and writes them to the
/// output buffer.
/// </summary>
protected override void BeginProcessing()
{
if (_pssnapins != null)
{
foreach (string psSnapIn in _pssnapins)
{
Exception exception = null;
try
{
Collection<PSSnapInInfo> psSnapInInfoList = GetSnapIns(psSnapIn);
// psSnapInInfoList wont be null..
Diagnostics.Assert(psSnapInInfoList != null, "ConsoleInfo.GetPSSnapIn returned null");
if (psSnapInInfoList.Count == 0)
{
WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound",
PSTraceSource.NewArgumentException(psSnapIn,
MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn),
ErrorCategory.InvalidArgument);
continue;
}
foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList)
{
// Load the pssnapin info properties that are localizable and redirected in the registry
pssnapinInfo.LoadIndirectResources(ResourceReader);
WriteObject(pssnapinInfo);
}
}
catch (System.Security.SecurityException se)
{
exception = se;
}
catch (PSArgumentException ae)
{
exception = ae;
}
if (exception != null)
{
WriteNonTerminatingError(psSnapIn, "GetPSSnapInRead", exception, ErrorCategory.InvalidArgument);
}
}
}
else if (ShouldGetAll)
{
Exception exception = null;
try
{
Collection<PSSnapInInfo> psSnapInInfoList = PSSnapInReader.ReadAll();
foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList)
{
// Load the pssnapin info properties that are localizable and redirected in the registry
pssnapinInfo.LoadIndirectResources(ResourceReader);
WriteObject(pssnapinInfo);
}
}
catch (System.Security.SecurityException se)
{
exception = se;
}
catch (PSArgumentException ae)
{
exception = ae;
}
if (exception != null)
{
WriteNonTerminatingError(this, "GetPSSnapInRead", exception, ErrorCategory.InvalidArgument);
}
}
else
{
// this should never throw..
Collection<PSSnapInInfo> psSnapInInfoList = GetSnapIns(null);
foreach (PSSnapInInfo pssnapinInfo in psSnapInInfoList)
{
// Load the pssnapin info properties that are localizable and redirected in the registry
pssnapinInfo.LoadIndirectResources(ResourceReader);
WriteObject(pssnapinInfo);
}
}
}
#endregion
}
#endregion
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using UIKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreFoundation;
namespace CloudKitAtlas
{
public partial class ResultsViewController : ResultOrErrorViewController, IUITableViewDelegate, IUITableViewDataSource, IUIScrollViewDelegate
{
[Outlet]
public TableView TableView { get; set; }
[Outlet]
public NSLayoutConstraint ToolbarHeightConstraint { get; set; }
[Outlet]
public UIToolbar Toolbar { get; set; }
public CodeSample CodeSample { get; set; }
public Results Results { get; set; } = new Results ();
string selectedAttributeValue;
readonly UIActivityIndicatorView activityIndicator = new UIActivityIndicatorView (new CGRect (0, 0, 20, 20));
public override bool CanBecomeFirstResponder {
get {
return true;
}
}
public ResultsViewController (IntPtr handle)
: base (handle)
{
}
[Export ("initWithCoder:")]
public ResultsViewController (NSCoder coder)
: base (coder)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
if (Results.Items.Count == 1) {
var result = Results.Items [0];
NavigationItem.Title = result.SummaryField ?? "Result";
} else {
NavigationItem.Title = "Result";
}
activityIndicator.HidesWhenStopped = true;
ToggleToolbar ();
}
public override void ViewDidAppear (bool animated)
{
var codeSample = CodeSample as MarkNotificationsReadSample;
codeSample?.Cache?.MarkAsRead ();
}
void ToggleToolbar ()
{
if (ToolbarHeightConstraint == null)
return;
if (Results.MoreComing) {
Toolbar.Hidden = false;
ToolbarHeightConstraint.Constant = 44;
} else {
Toolbar.Hidden = true;
ToolbarHeightConstraint.Constant = 0;
}
}
#region Table view data source
[Export ("numberOfSectionsInTableView:")]
public nint NumberOfSections (UITableView tableView)
{
bool showAsList = (Results.Items.Count == 0 || Results.ShowAsList);
return showAsList ? 1 : Results.Items [0].AttributeList.Count;
}
public nint RowsInSection (UITableView tableView, nint section)
{
return (Results.Items.Count == 0 || Results.ShowAsList)
? Results.Items.Count
: Results.Items [0].AttributeList [(int)section].Attributes.Count;
}
public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
if (Results.ShowAsList) {
var resultCell = (ResultTableViewCell)tableView.DequeueReusableCell ("ResultCell", indexPath);
var result = Results.Items [indexPath.Row];
resultCell.ResultLabel.Text = result.SummaryField ?? string.Empty;
resultCell.ChangeLabelWidthConstraint.Constant = 15;
if (Results.Added.Contains (indexPath.Row))
resultCell.ChangeLabel.Text = "A";
else if (Results.Deleted.Contains (indexPath.Row))
resultCell.ChangeLabel.Text = "D";
else if (Results.Modified.Contains (indexPath.Row))
resultCell.ChangeLabel.Text = "M";
else
resultCell.ChangeLabelWidthConstraint.Constant = 0;
return resultCell;
}
var attribute = Results.Items [0].AttributeList [indexPath.Section].Attributes [indexPath.Row];
var value = attribute.Value;
if (value == null) {
var attribCell = (AttributeKeyTableViewCell)tableView.DequeueReusableCell ("AttributeKeyCell", indexPath);
attribCell.AttributeKey.Text = attribute.Key;
return attribCell;
}
if (attribute.Image != null) {
var imgCell = (ImageTableViewCell)tableView.DequeueReusableCell ("ImageCell", indexPath);
imgCell.AttributeKey.Text = attribute.Key;
imgCell.AttributeValue.Text = string.IsNullOrWhiteSpace (value) ? "-" : value;
imgCell.AssetImage.Image = attribute.Image;
return imgCell;
}
var cellIdentifier = attribute.IsNested ? "NestedAttributeCell" : "AttributeCell";
var cell = (AttributeTableViewCell)tableView.DequeueReusableCell (cellIdentifier, indexPath);
cell.AttributeKey.Text = attribute.Key;
cell.AttributeValue.Text = string.IsNullOrWhiteSpace (value) ? "-" : value;
return cell;
}
[Export ("tableView:titleForHeaderInSection:")]
public string TitleForHeader (UITableView tableView, nint section)
{
var codeSample = CodeSample;
if (codeSample == null)
return string.Empty;
if (Results.ShowAsList)
return codeSample.ListHeading;
var result = Results.Items [0];
return result.AttributeList [(int)section].Title;
}
[Export ("tableView:heightForRowAtIndexPath:")]
public nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
if (Results.Items.Count > 0 && !Results.ShowAsList) {
var attribute = Results.Items [0].AttributeList [indexPath.Section].Attributes [indexPath.Row];
if (attribute.Image != null)
return 200;
}
return tableView.RowHeight;
}
#endregion
#region Responder
public override bool BecomeFirstResponder ()
{
return base.BecomeFirstResponder ();
}
public override bool CanPerform (Selector action, NSObject withSender)
{
return action.Name == "copyAttributeToClipboard";
}
#endregion
#region Actions
[Action ("handleLongPress:")]
void HandleLongPress (UILongPressGestureRecognizer sender)
{
if (sender.State != UIGestureRecognizerState.Ended)
return;
var point = sender.LocationInView (TableView);
var indexPath = TableView.IndexPathForRowAtPoint (point);
var attributeCell = TableView.CellAt (indexPath) as AttributeTableViewCell;
var attributeValue = attributeCell?.AttributeValue;
if (attributeValue == null)
return;
BecomeFirstResponder ();
selectedAttributeValue = attributeValue.Text ?? string.Empty;
var menuController = UIMenuController.SharedMenuController;
menuController.SetTargetRect (attributeValue.Frame, attributeCell);
menuController.MenuItems = new UIMenuItem [] {
new UIMenuItem ("Copy attribute value", new Selector ("copyAttributeToClipboard:"))
};
menuController.SetMenuVisible (true, true);
}
[Action ("copyAttributeToClipboard")]
void CopyAttributeToClipboard ()
{
var value = selectedAttributeValue;
if (value != null) {
var pasteBoard = UIPasteboard.General;
pasteBoard.String = value;
}
}
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier != "DrillDown")
return;
var resultsViewController = segue.DestinationViewController as ResultsViewController;
if (resultsViewController == null)
return;
var indexPath = TableView.IndexPathForSelectedRow;
if (indexPath == null)
return;
var result = Results.Items [indexPath.Row];
resultsViewController.Results = new Results (new IResult [] { result });
resultsViewController.CodeSample = CodeSample;
resultsViewController.IsDrilldown = true;
TableView.DeselectRow (indexPath, false);
}
[Action ("loadMoreResults:")]
public async void loadMoreResults (UIBarButtonItem sender)
{
sender.Enabled = false;
NavigationItem.RightBarButtonItem = new UIBarButtonItem (activityIndicator);
activityIndicator.StartAnimating ();
var codeSample = CodeSample;
if (codeSample != null) {
try {
var results = await codeSample.Run ();
Results = results;
DispatchQueue.MainQueue.DispatchAsync (() => {
var indexPaths = new List<NSIndexPath> ();
foreach (var index in results.Added.OrderBy (i => i))
indexPaths.Add (NSIndexPath.FromRowSection (index, 0));
if (indexPaths.Count > 0)
TableView.InsertRows (indexPaths.ToArray (), UITableViewRowAnimation.Automatic);
indexPaths.Clear ();
foreach (var index in results.Deleted.Union (results.Modified).OrderBy (i => i))
indexPaths.Add (NSIndexPath.FromRowSection (index, 0));
if (indexPaths.Count > 0)
TableView.ReloadRows (indexPaths.ToArray (), UITableViewRowAnimation.Automatic);
NavigationItem.RightBarButtonItem = DoneButton;
activityIndicator.StopAnimating ();
if (Results.MoreComing) {
sender.Enabled = true;
} else {
UIView.Animate (0.4, () => {
ToggleToolbar ();
View.LayoutIfNeeded ();
});
}
});
} catch (Exception ex) {
Console.WriteLine (ex);
throw ex;
}
}
}
#endregion
}
}
| |
using UnityEngine;
namespace UnityTest
{
public class CallTesting : MonoBehaviour
{
public enum Functions
{
CallAfterSeconds,
CallAfterFrames,
Start,
Update,
FixedUpdate,
LateUpdate,
OnDestroy,
OnEnable,
OnDisable,
OnControllerColliderHit,
OnParticleCollision,
OnJointBreak,
OnBecameInvisible,
OnBecameVisible,
OnTriggerEnter,
OnTriggerExit,
OnTriggerStay,
OnCollisionEnter,
OnCollisionExit,
OnCollisionStay,
#if !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
OnTriggerEnter2D,
OnTriggerExit2D,
OnTriggerStay2D,
OnCollisionEnter2D,
OnCollisionExit2D,
OnCollisionStay2D,
#endif
}
public enum Method
{
Pass,
Fail
}
public int afterFrames = 0;
public float afterSeconds = 0.0f;
public Functions callOnMethod = Functions.Start;
public Method methodToCall;
private int startFrame = 0;
private float startTime;
private void TryToCallTesting (Functions invokingMethod)
{
if (invokingMethod == callOnMethod)
{
if (methodToCall == Method.Pass)
IntegrationTest.Pass (gameObject);
else
IntegrationTest.Fail (gameObject);
afterFrames = 0;
afterSeconds = 0.0f;
startTime = float.PositiveInfinity;
startFrame = int.MinValue;
}
}
public void Start ()
{
startTime = Time.time;
startFrame = afterFrames;
TryToCallTesting (Functions.Start);
}
public void Update ()
{
TryToCallTesting (Functions.Update);
CallAfterSeconds ();
CallAfterFrames ();
}
private void CallAfterFrames ()
{
if (afterFrames > 0 && (startFrame + afterFrames) <= Time.frameCount)
TryToCallTesting (Functions.CallAfterFrames);
}
private void CallAfterSeconds ()
{
if ((startTime + afterSeconds) <= Time.time)
TryToCallTesting (Functions.CallAfterSeconds);
}
public void OnDisable ()
{
TryToCallTesting (Functions.OnDisable);
}
public void OnEnable ()
{
TryToCallTesting (Functions.OnEnable);
}
public void OnDestroy ()
{
TryToCallTesting (Functions.OnDestroy);
}
public void FixedUpdate ()
{
TryToCallTesting (Functions.FixedUpdate);
}
public void LateUpdate ()
{
TryToCallTesting (Functions.LateUpdate);
}
public void OnControllerColliderHit ()
{
TryToCallTesting (Functions.OnControllerColliderHit);
}
public void OnParticleCollision ()
{
TryToCallTesting (Functions.OnParticleCollision);
}
public void OnJointBreak ()
{
TryToCallTesting (Functions.OnJointBreak);
}
public void OnBecameInvisible ()
{
TryToCallTesting (Functions.OnBecameInvisible);
}
public void OnBecameVisible ()
{
TryToCallTesting (Functions.OnBecameVisible);
}
public void OnTriggerEnter ()
{
TryToCallTesting (Functions.OnTriggerEnter);
}
public void OnTriggerExit ()
{
TryToCallTesting (Functions.OnTriggerExit);
}
public void OnTriggerStay ()
{
TryToCallTesting (Functions.OnTriggerStay);
}
public void OnCollisionEnter ()
{
TryToCallTesting (Functions.OnCollisionEnter);
}
public void OnCollisionExit ()
{
TryToCallTesting (Functions.OnCollisionExit);
}
public void OnCollisionStay ()
{
TryToCallTesting (Functions.OnCollisionStay);
}
#if !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2
public void OnTriggerEnter2D ()
{
TryToCallTesting (Functions.OnTriggerEnter2D);
}
public void OnTriggerExit2D ()
{
TryToCallTesting (Functions.OnTriggerExit2D);
}
public void OnTriggerStay2D ()
{
TryToCallTesting (Functions.OnTriggerStay2D);
}
public void OnCollisionEnter2D ()
{
TryToCallTesting (Functions.OnCollisionEnter2D);
}
public void OnCollisionExit2D ()
{
TryToCallTesting (Functions.OnCollisionExit2D);
}
public void OnCollisionStay2D ()
{
TryToCallTesting (Functions.OnCollisionStay2D);
}
#endif
}
}
| |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace NLog.Windows.Forms
{
/// <summary>
/// Form helper methods.
/// </summary>
internal class FormHelper
{
/// <summary>
/// Creates RichTextBox and docks in parentForm.
/// </summary>
/// <param name="name">Name of RichTextBox.</param>
/// <param name="parentForm">Form to dock RichTextBox.</param>
/// <returns>Created RichTextBox.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects are disposed elsewhere")]
internal static RichTextBox CreateRichTextBox(string name, Form parentForm)
{
var rtb = new RichTextBox
{
Dock = DockStyle.Fill,
Location = new Point(0, 0),
Name = name,
Size = new Size(parentForm.Width, parentForm.Height)
};
parentForm.Controls.Add(rtb);
return rtb;
}
/// <summary>
/// Finds control embedded on searchControl.
/// </summary>
/// <param name="name">Name of the control.</param>
/// <param name="searchControl">Control in which we're searching for control.</param>
/// <returns>A value of null if no control has been found.</returns>
internal static Control FindControl(string name, Control searchControl)
{
if (searchControl.Name == name)
{
return searchControl;
}
foreach (Control childControl in searchControl.Controls)
{
Control foundControl = FindControl(name, childControl);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}
/// <summary>
/// Finds item within searchCollection it's contents drop down items.
/// </summary>
/// <param name="name">Name of the ToolStripItem</param>
/// <param name="searchCollection">Collection of ToolStripItem we are looking for the item in.</param>
/// <returns>A value of null of no item has been found.</returns>
internal static ToolStripItem FindToolStripItem(string name, ToolStripItemCollection searchCollection)
{
foreach (ToolStripItem childItem in searchCollection)
{
if(childItem.Name == name)
{
return childItem;
}
if(childItem is ToolStripDropDownItem)
{
ToolStripDropDownItem childDropDown = childItem as ToolStripDropDownItem;
ToolStripItem foundItem = FindToolStripItem(name, childDropDown.DropDownItems);
if (foundItem != null)
{
return foundItem;
}
}
}
return null;
}
/// <summary>
/// Finds control of specified type embended on searchControl.
/// </summary>
/// <typeparam name="TControl">The type of the control.</typeparam>
/// <param name="name">Name of the control.</param>
/// <param name="searchControl">Control in which we're searching for control.</param>
/// <returns>
/// A value of null if no control has been found.
/// </returns>
internal static TControl FindControl<TControl>(string name, Control searchControl)
where TControl : Control
{
if (searchControl.Name == name)
{
TControl foundControl = searchControl as TControl;
if (foundControl != null)
{
return foundControl;
}
}
foreach (Control childControl in searchControl.Controls)
{
TControl foundControl = FindControl<TControl>(name, childControl);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}
/// <summary>
/// Creates a form.
/// </summary>
/// <param name="name">Name of form.</param>
/// <param name="width">Width of form.</param>
/// <param name="height">Height of form.</param>
/// <param name="show">Auto show form.</param>
/// <param name="showMinimized">If set to <c>true</c> the form will be minimized.</param>
/// <param name="toolWindow">If set to <c>true</c> the form will be created as tool window.</param>
/// <returns>Created form.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Windows.Forms.Control.set_Text(System.String)", Justification = "Does not need to be localized.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects are disposed elsewhere")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")]
internal static Form CreateForm(string name, int width, int height, bool show, bool showMinimized, bool toolWindow)
{
var f = new Form
{
Name = name,
Text = "NLog",
Icon = GetNLogIcon(),
};
#if !Smartphone
if (toolWindow)
{
f.FormBorderStyle = FormBorderStyle.SizableToolWindow;
}
#endif
if (width > 0)
{
f.Width = width;
}
if (height > 0)
{
f.Height = height;
}
if (show)
{
if (showMinimized)
{
f.WindowState = FormWindowState.Minimized;
f.Show();
}
else
{
f.Show();
}
}
return f;
}
private static Icon GetNLogIcon()
{
using (var stream = typeof(FormHelper).Assembly.GetManifestResourceStream("NLog.Windows.Forms.Resources.NLog.ico"))
{
return new Icon(stream);
}
}
#region Link support
/// <summary>
/// Replaces currently selected text in the RTB control with a link
/// </summary>
/// <param name="textBox">target control</param>
/// <param name="text">visible text of the new link</param>
/// <param name="hyperlink">hidden part of the new link</param>
/// <remarks>
/// Based on http://www.codeproject.com/info/cpol10.aspx
/// </remarks>
internal static void ChangeSelectionToLink(RichTextBox textBox, string text, string hyperlink)
{
#if NETCOREAPP
textBox.SelectedRtf = @"{\rtf1\ansi{\field{\*\fldinst{HYPERLINK """ + text + @"#" + hyperlink + @""" }}{\fldrslt{" + text + @"}}}}";
#else
int selectionStart = textBox.SelectionStart;
//using \v tag to hide hyperlink part of the text, and \v0 to end hiding. See http://stackoverflow.com/a/14339531/376066
//so in the control the link would consist only of "<text>", but in link clicked event we would get "<text>#<hyperlink>"
textBox.SelectedRtf = @"{\rtf1\ansi " + text + @"\v #" + hyperlink + @"\v0}";
textBox.Select(selectionStart, text.Length + 1 + hyperlink.Length); //now select both visible and invisible part
SetSelectionStyle(textBox, CFM_LINK, CFE_LINK); //and turn into a link
#endif
}
/// <summary>
/// Sets selection style for RichTextBox
/// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787883(v=vs.85).aspx
/// </summary>
/// <param name="textBox">target control</param>
/// <param name="mask">Specifies the parts of the CHARFORMAT2 structure that contain valid information.</param>
/// <param name="effect">A set of bit flags that specify character effects.</param>
/// <remarks>
/// Based on http://www.codeproject.com/info/cpol10.aspx
/// </remarks>
private static void SetSelectionStyle(RichTextBox textBox, UInt32 mask, UInt32 effect)
{
CHARFORMAT2_STRUCT cf = new CHARFORMAT2_STRUCT();
cf.cbSize = (UInt32)Marshal.SizeOf(cf);
cf.dwMask = mask;
cf.dwEffects = effect;
IntPtr wpar = new IntPtr(SCF_SELECTION);
IntPtr lpar = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf));
Marshal.StructureToPtr(cf, lpar, false);
IntPtr res = SendMessage(textBox.Handle, EM_SETCHARFORMAT, wpar, lpar);
Marshal.FreeCoTaskMem(lpar);
}
/// <summary>
/// CHARFORMAT2 structure, contains information about character formatting in a rich edit control.
/// </summary>
/// see https://msdn.microsoft.com/en-us/library/windows/desktop/bb787883(v=vs.85).aspx
[StructLayout(LayoutKind.Sequential)]
private struct CHARFORMAT2_STRUCT
{
public UInt32 cbSize;
public UInt32 dwMask;
public UInt32 dwEffects;
public Int32 yHeight;
public Int32 yOffset;
public Int32 crTextColor;
public byte bCharSet;
public byte bPitchAndFamily;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public char[] szFaceName;
public UInt16 wWeight;
public UInt16 sSpacing;
public int crBackColor; // Color.ToArgb() -> int
public int lcid;
public int dwReserved;
public Int16 sStyle;
public Int16 wKerning;
public byte bUnderlineType;
public byte bAnimation;
public byte bRevAuthor;
public byte bReserved1;
}
private const int WM_USER = 0x0400;
private const int EM_SETCHARFORMAT = WM_USER + 68; //EM_SETCHARFORMAT message - Sets character formatting in a rich edit control. https://msdn.microsoft.com/en-us/library/windows/desktop/bb774230(v=vs.85).aspx
private const int SCF_SELECTION = 0x0001; //Applies the formatting to the current selection. https://msdn.microsoft.com/en-us/library/windows/desktop/bb774230(v=vs.85).aspx
private const UInt32 CFE_LINK = 0x0020; //link effect https://msdn.microsoft.com/en-us/library/windows/desktop/bb787970(v=vs.85).aspx
private const UInt32 CFM_LINK = 0x00000020; //mask for CFE_LINK, see https://msdn.microsoft.com/en-us/library/windows/desktop/bb787883(v=vs.85).aspx
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RoleService.cs">
// Copyright (c) 2014-present Andrea Di Giorgi
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <author>Andrea Di Giorgi</author>
// <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Liferay.SDK.Service.V62.Role
{
public class RoleService : ServiceBase
{
public RoleService(ISession session)
: base(session)
{
}
public async Task<dynamic> AddRoleAsync(string name, IDictionary<string, string> titleMap, IDictionary<string, string> descriptionMap, int type)
{
var _parameters = new JsonObject();
_parameters.Add("name", name);
_parameters.Add("titleMap", titleMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("type", type);
var _command = new JsonObject()
{
{ "/role/add-role", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> AddRoleAsync(string className, long classPK, string name, IDictionary<string, string> titleMap, IDictionary<string, string> descriptionMap, int type, string subtype, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("className", className);
_parameters.Add("classPK", classPK);
_parameters.Add("name", name);
_parameters.Add("titleMap", titleMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("type", type);
_parameters.Add("subtype", subtype);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/role/add-role", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task AddUserRolesAsync(long userId, IEnumerable<long> roleIds)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
_parameters.Add("roleIds", roleIds);
var _command = new JsonObject()
{
{ "/role/add-user-roles", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task DeleteRoleAsync(long roleId)
{
var _parameters = new JsonObject();
_parameters.Add("roleId", roleId);
var _command = new JsonObject()
{
{ "/role/delete-role", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<IEnumerable<dynamic>> GetGroupRolesAsync(long groupId)
{
var _parameters = new JsonObject();
_parameters.Add("groupId", groupId);
var _command = new JsonObject()
{
{ "/role/get-group-roles", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<dynamic> GetRoleAsync(long roleId)
{
var _parameters = new JsonObject();
_parameters.Add("roleId", roleId);
var _command = new JsonObject()
{
{ "/role/get-role", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<dynamic> GetRoleAsync(long companyId, string name)
{
var _parameters = new JsonObject();
_parameters.Add("companyId", companyId);
_parameters.Add("name", name);
var _command = new JsonObject()
{
{ "/role/get-role", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
public async Task<IEnumerable<dynamic>> GetUserGroupGroupRolesAsync(long userId, long groupId)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
_parameters.Add("groupId", groupId);
var _command = new JsonObject()
{
{ "/role/get-user-group-group-roles", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetUserGroupRolesAsync(long userId, long groupId)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
_parameters.Add("groupId", groupId);
var _command = new JsonObject()
{
{ "/role/get-user-group-roles", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetUserRelatedRolesAsync(long userId, IEnumerable<object> groups)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
_parameters.Add("groups", groups);
var _command = new JsonObject()
{
{ "/role/get-user-related-roles", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<IEnumerable<dynamic>> GetUserRolesAsync(long userId)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
var _command = new JsonObject()
{
{ "/role/get-user-roles", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (IEnumerable<dynamic>)_obj;
}
public async Task<bool> HasUserRoleAsync(long userId, long companyId, string name, bool inherited)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
_parameters.Add("companyId", companyId);
_parameters.Add("name", name);
_parameters.Add("inherited", inherited);
var _command = new JsonObject()
{
{ "/role/has-user-role", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (bool)_obj;
}
public async Task<bool> HasUserRolesAsync(long userId, long companyId, IEnumerable<string> names, bool inherited)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
_parameters.Add("companyId", companyId);
_parameters.Add("names", names);
_parameters.Add("inherited", inherited);
var _command = new JsonObject()
{
{ "/role/has-user-roles", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (bool)_obj;
}
public async Task UnsetUserRolesAsync(long userId, IEnumerable<long> roleIds)
{
var _parameters = new JsonObject();
_parameters.Add("userId", userId);
_parameters.Add("roleIds", roleIds);
var _command = new JsonObject()
{
{ "/role/unset-user-roles", _parameters }
};
await this.Session.InvokeAsync(_command);
}
public async Task<dynamic> UpdateRoleAsync(long roleId, string name, IDictionary<string, string> titleMap, IDictionary<string, string> descriptionMap, string subtype, JsonObjectWrapper serviceContext)
{
var _parameters = new JsonObject();
_parameters.Add("roleId", roleId);
_parameters.Add("name", name);
_parameters.Add("titleMap", titleMap);
_parameters.Add("descriptionMap", descriptionMap);
_parameters.Add("subtype", subtype);
this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext);
var _command = new JsonObject()
{
{ "/role/update-role", _parameters }
};
var _obj = await this.Session.InvokeAsync(_command);
return (dynamic)_obj;
}
}
}
| |
/*
* Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library 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
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using uhttpsharp.Headers;
namespace uhttpsharp
{
public interface IHttpResponse
{
Task WriteBody(StreamWriter writer);
/// <summary>
/// Gets the status line of this http response,
/// The first line that will be sent to the client.
/// </summary>
HttpResponseCode ResponseCode { get; }
IHttpHeaders Headers { get; }
bool CloseConnection { get; }
}
public abstract class HttpResponseBase : IHttpResponse
{
private readonly HttpResponseCode _code;
private readonly IHttpHeaders _headers;
protected HttpResponseBase(HttpResponseCode code, IHttpHeaders headers)
{
_code = code;
_headers = headers;
}
public abstract Task WriteBody(StreamWriter writer);
public HttpResponseCode ResponseCode
{
get { return _code; }
}
public IHttpHeaders Headers
{
get { return _headers; }
}
public bool CloseConnection
{
get
{
string value;
return !(_headers.TryGetByName("Connection", out value) &&
value.Equals("Keep-Alive", StringComparison.InvariantCultureIgnoreCase));
}
}
}
public sealed class StreamHttpResponse : HttpResponseBase
{
private readonly Stream _body;
public StreamHttpResponse(Stream body, HttpResponseCode code, IHttpHeaders headers) : base(code, headers)
{
_body = body;
}
public static IHttpResponse Create(Stream body, HttpResponseCode code = HttpResponseCode.Ok, string contentType = "text/html; charset=utf-8", bool keepAlive = true)
{
return new StreamHttpResponse(body, code, new ListHttpHeaders(new[]
{
new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
new KeyValuePair<string, string>("content-type", contentType),
new KeyValuePair<string, string>("connection", keepAlive ? "keep-alive" : "close"),
new KeyValuePair<string, string>("content-length", body.Length.ToString(CultureInfo.InvariantCulture)),
}));
}
public async override Task WriteBody(StreamWriter writer)
{
await writer.FlushAsync().ConfigureAwait(false);
await _body.CopyToAsync(writer.BaseStream).ConfigureAwait(false);
await writer.BaseStream.FlushAsync().ConfigureAwait(false);
}
}
public sealed class EmptyHttpResponse : HttpResponseBase
{
public EmptyHttpResponse(HttpResponseCode code, IHttpHeaders headers) : base(code, headers)
{
}
public static IHttpResponse Create(HttpResponseCode code = HttpResponseCode.Ok, bool keepAlive = true)
{
return new EmptyHttpResponse(code, new ListHttpHeaders(new[]
{
new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
new KeyValuePair<string, string>("content-type", "text/html"),
new KeyValuePair<string, string>("connection", keepAlive ? "keep-alive" : "close"),
new KeyValuePair<string, string>("content-length", "0"),
}));
}
public override Task WriteBody(StreamWriter writer)
{
return Task.Factory.GetCompleted();
}
}
public sealed class StringHttpResponse : HttpResponseBase
{
private readonly string _body;
public StringHttpResponse(string body, HttpResponseCode code, IHttpHeaders headers) : base(code, headers)
{
_body = body;
}
public static IHttpResponse Create(string body, HttpResponseCode code = HttpResponseCode.Ok, string contentType = "text/html; charset=utf-8", bool keepAlive = true)
{
return new StringHttpResponse(body, code, new ListHttpHeaders(new[]
{
new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
new KeyValuePair<string, string>("content-type", contentType),
new KeyValuePair<string, string>("connection", keepAlive ? "keep-alive" : "close"),
new KeyValuePair<string, string>("content-length", Encoding.UTF8.GetByteCount(body).ToString(CultureInfo.InvariantCulture)),
}));
}
public async override Task WriteBody(StreamWriter writer)
{
await writer.WriteAsync(_body).ConfigureAwait(false);
}
}
public sealed class HttpResponse : IHttpResponse
{
private Stream ContentStream { get; set; }
private readonly Stream _headerStream = new MemoryStream();
private readonly bool _closeConnection;
private readonly IHttpHeaders _headers;
private readonly HttpResponseCode _responseCode;
public HttpResponse(HttpResponseCode code, string content, bool closeConnection)
: this(code, "text/html; charset=utf-8", StringToStream(content), closeConnection)
{
}
public HttpResponse(HttpResponseCode code, string content, IEnumerable<KeyValuePair<string,string>> headers, bool closeConnection)
: this(code, "text/html; charset=utf-8", StringToStream(content), closeConnection,headers)
{
}
public HttpResponse(string contentType, Stream contentStream, bool closeConnection)
: this(HttpResponseCode.Ok, contentType, contentStream, closeConnection)
{
}
public HttpResponse(HttpResponseCode code, string contentType, Stream contentStream, bool keepAliveConnection, IEnumerable<KeyValuePair<string, string>> headers)
{
ContentStream = contentStream;
_closeConnection = !keepAliveConnection;
_responseCode = code;
_headers = new ListHttpHeaders(new[]
{
new KeyValuePair<string, string>("Date", DateTime.UtcNow.ToString("R")),
new KeyValuePair<string, string>("Connection", _closeConnection ? "Close" : "Keep-Alive"),
new KeyValuePair<string, string>("Content-Type", contentType),
new KeyValuePair<string, string>("Content-Length", ContentStream.Length.ToString(CultureInfo.InvariantCulture)),
}.Concat(headers).ToList());
}
public HttpResponse(HttpResponseCode code, string contentType, Stream contentStream, bool keepAliveConnection) :
this(code, contentType, contentStream, keepAliveConnection, Enumerable.Empty<KeyValuePair<string, string>>())
{
}
public HttpResponse(HttpResponseCode code, byte[] contentStream, bool keepAliveConnection)
: this (code, "text/html; charset=utf-8", new MemoryStream(contentStream), keepAliveConnection)
{
}
public HttpResponse(HttpResponseCode code, string contentType, string content, bool closeConnection)
: this(code, contentType, StringToStream(content), closeConnection)
{
}
public static HttpResponse CreateWithMessage(HttpResponseCode code, string message, bool keepAliveConnection, string body = "")
{
return new HttpResponse(
code,
string.Format(
"<html><head><title>{0}</title></head><body><h1>{0}</h1><hr>{1}</body></html>",
message, body), keepAliveConnection);
}
private static MemoryStream StringToStream(string content)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(content);
writer.Flush();
return stream;
}
public async Task WriteBody(StreamWriter writer)
{
ContentStream.Position = 0;
await ContentStream.CopyToAsync(writer.BaseStream).ConfigureAwait(false);
}
public HttpResponseCode ResponseCode
{
get { return _responseCode; }
}
public IHttpHeaders Headers
{
get { return _headers; }
}
public bool CloseConnection
{
get { return _closeConnection; }
}
public async Task WriteHeaders(StreamWriter writer)
{
_headerStream.Position = 0;
await _headerStream.CopyToAsync(writer.BaseStream).ConfigureAwait(false);
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.Extensions.NamingContextConstants.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
namespace Novell.Directory.LDAP.VQ.Extensions
{
/*
* public class NamingContextConstants
*/
/// <summary> Contains a collection of constants used by the Novell Ldap extensions.</summary>
public class NamingContextConstants
{
/// <summary> A constant for the createNamingContextRequest OID.</summary>
public const String CREATE_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.3";
/// <summary> A constant for the createNamingContextResponse OID.</summary>
public const String CREATE_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.4";
/// <summary> A constant for the mergeNamingContextRequest OID.</summary>
public const String MERGE_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.5";
/// <summary> A constant for the mergeNamingContextResponse OID.</summary>
public const String MERGE_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.6";
/// <summary> A constant for the addReplicaRequest OID.</summary>
public const String ADD_REPLICA_REQ = "2.16.840.1.113719.1.27.100.7";
/// <summary> A constant for the addReplicaResponse OID.</summary>
public const String ADD_REPLICA_RES = "2.16.840.1.113719.1.27.100.8";
/// <summary> A constant for the refreshServerRequest OID.</summary>
public const String REFRESH_SERVER_REQ = "2.16.840.1.113719.1.27.100.9";
/// <summary> A constant for the refreshServerResponse OID.</summary>
public const String REFRESH_SERVER_RES = "2.16.840.1.113719.1.27.100.10";
/// <summary> A constant for the removeReplicaRequest OID.</summary>
public const String DELETE_REPLICA_REQ = "2.16.840.1.113719.1.27.100.11";
/// <summary> A constant for the removeReplicaResponse OID.</summary>
public const String DELETE_REPLICA_RES = "2.16.840.1.113719.1.27.100.12";
/// <summary> A constant for the namingContextEntryCountRequest OID.</summary>
public const String NAMING_CONTEXT_COUNT_REQ = "2.16.840.1.113719.1.27.100.13";
/// <summary> A constant for the namingContextEntryCountResponse OID.</summary>
public const String NAMING_CONTEXT_COUNT_RES = "2.16.840.1.113719.1.27.100.14";
/// <summary> A constant for the changeReplicaTypeRequest OID.</summary>
public const String CHANGE_REPLICA_TYPE_REQ = "2.16.840.1.113719.1.27.100.15";
/// <summary> A constant for the changeReplicaTypeResponse OID.</summary>
public const String CHANGE_REPLICA_TYPE_RES = "2.16.840.1.113719.1.27.100.16";
/// <summary> A constant for the getReplicaInfoRequest OID.</summary>
public const String GET_REPLICA_INFO_REQ = "2.16.840.1.113719.1.27.100.17";
/// <summary> A constant for the getReplicaInfoResponse OID.</summary>
public const String GET_REPLICA_INFO_RES = "2.16.840.1.113719.1.27.100.18";
/// <summary> A constant for the listReplicaRequest OID.</summary>
public const String LIST_REPLICAS_REQ = "2.16.840.1.113719.1.27.100.19";
/// <summary> A constant for the listReplicaResponse OID.</summary>
public const String LIST_REPLICAS_RES = "2.16.840.1.113719.1.27.100.20";
/// <summary> A constant for the receiveAllUpdatesRequest OID.</summary>
public const String RECEIVE_ALL_UPDATES_REQ = "2.16.840.1.113719.1.27.100.21";
/// <summary> A constant for the receiveAllUpdatesResponse OID.</summary>
public const String RECEIVE_ALL_UPDATES_RES = "2.16.840.1.113719.1.27.100.22";
/// <summary> A constant for the sendAllUpdatesRequest OID.</summary>
public const String SEND_ALL_UPDATES_REQ = "2.16.840.1.113719.1.27.100.23";
/// <summary> A constant for the sendAllUpdatesResponse OID.</summary>
public const String SEND_ALL_UPDATES_RES = "2.16.840.1.113719.1.27.100.24";
/// <summary> A constant for the requestNamingContextSyncRequest OID.</summary>
public const String NAMING_CONTEXT_SYNC_REQ = "2.16.840.1.113719.1.27.100.25";
/// <summary> A constant for the requestNamingContextSyncResponse OID.</summary>
public const String NAMING_CONTEXT_SYNC_RES = "2.16.840.1.113719.1.27.100.26";
/// <summary> A constant for the requestSchemaSyncRequest OID.</summary>
public const String SCHEMA_SYNC_REQ = "2.16.840.1.113719.1.27.100.27";
/// <summary> A constant for the requestSchemaSyncResponse OID.</summary>
public const String SCHEMA_SYNC_RES = "2.16.840.1.113719.1.27.100.28";
/// <summary> A constant for the abortNamingContextOperationRequest OID.</summary>
public const String ABORT_NAMING_CONTEXT_OP_REQ = "2.16.840.1.113719.1.27.100.29";
/// <summary> A constant for the abortNamingContextOperationResponse OID.</summary>
public const String ABORT_NAMING_CONTEXT_OP_RES = "2.16.840.1.113719.1.27.100.30";
/// <summary> A constant for the getContextIdentityNameRequest OID.</summary>
public const String GET_IDENTITY_NAME_REQ = "2.16.840.1.113719.1.27.100.31";
/// <summary> A constant for the getContextIdentityNameResponse OID.</summary>
public const String GET_IDENTITY_NAME_RES = "2.16.840.1.113719.1.27.100.32";
/// <summary> A constant for the getEffectivePrivilegesRequest OID.</summary>
public const String GET_EFFECTIVE_PRIVILEGES_REQ = "2.16.840.1.113719.1.27.100.33";
/// <summary> A constant for the getEffectivePrivilegesResponse OID.</summary>
public const String GET_EFFECTIVE_PRIVILEGES_RES = "2.16.840.1.113719.1.27.100.34";
/// <summary> A constant for the setReplicationFilterRequest OID.</summary>
public const String SET_REPLICATION_FILTER_REQ = "2.16.840.1.113719.1.27.100.35";
/// <summary> A constant for the setReplicationFilterResponse OID.</summary>
public const String SET_REPLICATION_FILTER_RES = "2.16.840.1.113719.1.27.100.36";
/// <summary> A constant for the getReplicationFilterRequest OID.</summary>
public const String GET_REPLICATION_FILTER_REQ = "2.16.840.1.113719.1.27.100.37";
/// <summary> A constant for the getReplicationFilterResponse OID.</summary>
public const String GET_REPLICATION_FILTER_RES = "2.16.840.1.113719.1.27.100.38";
/// <summary> A constant for the createOrphanNamingContextRequest OID.</summary>
public const String CREATE_ORPHAN_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.39";
/// <summary> A constant for the createOrphanNamingContextResponse OID.</summary>
public const String CREATE_ORPHAN_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.40";
/// <summary> A constant for the removeOrphanNamingContextRequest OID.</summary>
public const String REMOVE_ORPHAN_NAMING_CONTEXT_REQ = "2.16.840.1.113719.1.27.100.41";
/// <summary> A constant for the removeOrphanNamingContextResponse OID.</summary>
public const String REMOVE_ORPHAN_NAMING_CONTEXT_RES = "2.16.840.1.113719.1.27.100.42";
/// <summary> A constant for the triggerBackLinkerRequest OID.</summary>
public const String TRIGGER_BKLINKER_REQ = "2.16.840.1.113719.1.27.100.43";
/// <summary> A constant for the triggerBackLinkerResponse OID.</summary>
public const String TRIGGER_BKLINKER_RES = "2.16.840.1.113719.1.27.100.44";
/// <summary> A constant for the triggerJanitorRequest OID.</summary>
public const String TRIGGER_JANITOR_REQ = "2.16.840.1.113719.1.27.100.47";
/// <summary> A constant for the triggerJanitorResponse OID.</summary>
public const String TRIGGER_JANITOR_RES = "2.16.840.1.113719.1.27.100.48";
/// <summary> A constant for the triggerLimberRequest OID.</summary>
public const String TRIGGER_LIMBER_REQ = "2.16.840.1.113719.1.27.100.49";
/// <summary> A constant for the triggerLimberResponse OID.</summary>
public const String TRIGGER_LIMBER_RES = "2.16.840.1.113719.1.27.100.50";
/// <summary> A constant for the triggerSkulkerRequest OID.</summary>
public const String TRIGGER_SKULKER_REQ = "2.16.840.1.113719.1.27.100.51";
/// <summary> A constant for the triggerSkulkerResponse OID.</summary>
public const String TRIGGER_SKULKER_RES = "2.16.840.1.113719.1.27.100.52";
/// <summary> A constant for the triggerSchemaSyncRequest OID.</summary>
public const String TRIGGER_SCHEMA_SYNC_REQ = "2.16.840.1.113719.1.27.100.53";
/// <summary> A constant for the triggerSchemaSyncResponse OID.</summary>
public const String TRIGGER_SCHEMA_SYNC_RES = "2.16.840.1.113719.1.27.100.54";
/// <summary> A constant for the triggerPartitionPurgeRequest OID.</summary>
public const String TRIGGER_PART_PURGE_REQ = "2.16.840.1.113719.1.27.100.55";
/// <summary> A constant for the triggerPartitionPurgeResponse OID.</summary>
public const String TRIGGER_PART_PURGE_RES = "2.16.840.1.113719.1.27.100.56";
/// <summary> A constant that specifies that all servers in a replica ring must be
/// running for a naming context operation to proceed.
/// </summary>
public const int Ldap_ENSURE_SERVERS_UP = 1;
/// <summary> Identifies this replica as the master replica of the naming context.
///
/// On this type of replica, entries can be modified, and naming context
/// operations can be performed.
/// </summary>
public const int Ldap_RT_MASTER = 0;
/// <summary> Identifies this replica as a secondary replica of the naming context.
///
/// On this type of replica, read and write operations can be performed,
/// and entries can be modified.
/// </summary>
public const int Ldap_RT_SECONDARY = 1;
/// <summary> Identifies this replica as a read-only replica of the naming context.
///
/// Only Novell eDirectory synchronization processes can modifie
/// entries on this replica.
/// </summary>
public const int Ldap_RT_READONLY = 2;
/// <summary> Identifies this replica as a subordinate reference replica of the
/// naming context.
///
/// Novell eDirectory automatically adds these replicas to a server
/// when the server does not contain replicas of all child naming contexts.
/// Only eDirectory can modify information on these types of replicas.
/// </summary>
public const int Ldap_RT_SUBREF = 3;
/// <summary> Identifies this replica as a read/write replica of the naming context,
/// but the replica contains sparse data.
///
/// The replica has been configured to contain only specified object types
/// and attributes. On this type of replica, only the attributes and objects
/// contained in the sparse data can be modified.
/// </summary>
public const int Ldap_RT_SPARSE_WRITE = 4;
/// <summary> Identifies this replica as a read-only replica of the naming context,
/// but the replica contains sparse data.
///
/// The replica has been configured to contain only specified object types
/// and attributes. On this type of replica, only Novell eDirectory
/// synchronization processes can modify the sparse data.
/// </summary>
public const int Ldap_RT_SPARSE_READ = 5;
//Replica States
/// <summary> Indicates that the replica is fully functioning and capable of responding
/// to requests.
/// </summary>
public const int Ldap_RS_ON = 0;
/// <summary> Indicates that a new replica has been added but has not received a full
/// download of information from the replica ring.
/// </summary>
public const int Ldap_RS_NEW_REPLICA = 1;
/// <summary> Indicates that the replica is being deleted and that the request has
/// been received.
/// </summary>
public const int Ldap_RS_DYING_REPLICA = 2;
/// <summary> Indicates that the replica is locked. The move operation uses this state
/// to lock the parent naming context of the child naming context that is moving.
/// </summary>
public const int Ldap_RS_LOCKED = 3;
/// <summary> Indicates that a new replica has finished receiving its download from the
/// master replica and is now receiving synchronization updates from other
/// replicas.
/// </summary>
public const int Ldap_RS_TRANSITION_ON = 6;
/// <summary> Indicates that the dying replica needs to synchronize with another replica
/// before being converted either to an external reference, if a root replica,
/// or to a subordinate reference, if a non-root replica.
/// </summary>
public const int Ldap_RS_DEAD_REPLICA = 7;
/// <summary> Indicates that the subordinate references of the new replica are being
/// added.
/// </summary>
public const int Ldap_RS_BEGIN_ADD = 8;
/// <summary> Indicates that a naming context is receiving a new master replica.
///
/// The replica that will be the new master replica is set to this state.
/// </summary>
public const int Ldap_RS_MASTER_START = 11;
/// <summary> Indicates that a naming context has a new master replica.
///
/// When the new master is set to this state, Novell eDirectory knows
/// that the replica is now the master and changes its replica type to
/// master and the old master to read/write.
/// </summary>
public const int Ldap_RS_MASTER_DONE = 12;
/// <summary> Indicates that the naming context is going to split into two naming contexts.
///
/// In this state, other replicas of the naming context are informed of the
/// pending split.
/// </summary>
public const int Ldap_RS_SS_0 = 48; // Replica splitting 0
/// <summary> Indicates that that the split naming context operation has started.
///
/// When the split is finished, the state will change to RS_ON.
/// </summary>
public const int Ldap_RS_SS_1 = 49; // Replica splitting 1
/// <summary> Indicates that that two naming contexts are in the process of joining
/// into one naming context.
///
/// In this state, the replicas that are affected are informed of the join
/// operation. The master replica of the parent and child naming contexts are
/// first set to this state and then all the replicas of the parent and child.
/// New replicas are added where needed.
/// </summary>
public const int Ldap_RS_JS_0 = 64; // Replica joining 0
/// <summary> Indicates that that two naming contexts are in the process of joining
/// into one naming context.
///
/// This state indicates that the join operation is waiting for the new
/// replicas to synchronize and move to the RS_ON state.
/// </summary>
public const int Ldap_RS_JS_1 = 65; // Replica joining 1
/// <summary> Indicates that that two naming contexts are in the process of joining
/// into one naming context.
///
/// This state indicates that all the new replicas are in the RS_ON state
/// and that the rest of the work can be completed.
/// </summary>
public const int Ldap_RS_JS_2 = 66; // Replica joining 2
// Values for flags used in the replica info class structure
/// <summary> Indicates that the replica is involved with a partition operation,
/// for example, merging a tree or moving a subtree.
/// </summary>
public const int Ldap_DS_FLAG_BUSY = 0x0001;
/// <summary> Indicates that this naming context is on the DNS federation boundary.
/// This flag is only set on DNS trees.
/// </summary>
public const int Ldap_DS_FLAG_BOUNDARY = 0x0002;
public NamingContextConstants()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using HoneyBear.HalClient.Http;
using HoneyBear.HalClient.Models;
using Tavis.UriTemplates;
namespace HoneyBear.HalClient
{
/// <summary>
/// A lightweight fluent .NET client for navigating and consuming HAL APIs.
/// </summary>
public class HalClient : IHalClient
{
private readonly IJsonHttpClient _client;
private readonly IEnumerable<MediaTypeFormatter> _formatters;
private readonly IEnumerable<IResource> _current = Enumerable.Empty<IResource>();
private static readonly ICollection<MediaTypeFormatter> _defaultFormatters =
new[] {new HalJsonMediaTypeFormatter()};
/// <summary>
/// Creates an instance of the <see cref="HalClient"/> class.
/// </summary>
/// <param name="client">The <see cref="System.Net.Http.HttpClient"/> to use.</param>
/// <param name="formatters">
/// Specifies the list of <see cref="MediaTypeFormatter"/>s to use.
/// Default is <see cref="HalJsonMediaTypeFormatter"/>.
/// </param>
public HalClient(
HttpClient client,
ICollection<MediaTypeFormatter> formatters)
{
_client = new JsonHttpClient(client);
_formatters = formatters == null || !formatters.Any() ? _defaultFormatters : formatters;
}
/// <summary>
/// Creates an instance of the <see cref="HalClient"/> class.
/// </summary>
/// <param name="client">The <see cref="System.Net.Http.HttpClient"/> to use.</param>
public HalClient(
HttpClient client)
: this(client, _defaultFormatters)
{
}
/// <summary>
/// Creates an instance of the <see cref="HalClient"/> class.
/// Uses a default instance of <see cref="System.Net.Http.HttpClient"/>.
/// </summary>
public HalClient()
: this(new HttpClient())
{
}
/// <summary>
/// Creates an instance of the <see cref="HalClient"/> class.
/// </summary>
/// <param name="client">The implementation of <see cref="IJsonHttpClient"/> to use.</param>
/// <param name="formatters">
/// Specifies the list of <see cref="MediaTypeFormatter"/>s to use.
/// Default is <see cref="HalJsonMediaTypeFormatter"/>.
/// </param>
public HalClient(
IJsonHttpClient client,
ICollection<MediaTypeFormatter> formatters)
{
_client = client;
_formatters = formatters == null || !formatters.Any() ? _defaultFormatters : formatters;
}
/// <summary>
/// Creates an instance of the <see cref="HalClient"/> class.
/// </summary>
/// <param name="client">The implementation of <see cref="IJsonHttpClient"/> to use.</param>
public HalClient(
IJsonHttpClient client)
: this(client, _defaultFormatters)
{
}
private HalClient(
HalClient client,
IEnumerable<IResource> current)
: this(client._client, client._formatters.ToList())
{
_current = current;
}
/// <summary>
/// Gets the instance of <see cref="System.Net.Http.HttpClient"/> used by the <see cref="HalClient"/>.
/// </summary>
public HttpClient HttpClient => _client.HttpClient;
/// <summary>
/// Returns the most recently navigated resource of the specified type.
/// </summary>
/// <typeparam name="T">The type of the resource to return.</typeparam>
/// <returns>The most recent navigated resource of the specified type.</returns>
/// <exception cref="NoActiveResource" />
public IResource<T> Item<T>() where T : class, new() => Convert<T>(Latest);
/// <summary>
/// Returns the list of embedded resources in the most recently navigated resource.
/// </summary>
/// <typeparam name="T">The type of the resource to return.</typeparam>
/// <returns>The list of embedded resources in the most recently navigated resource.</returns>
/// <exception cref="NoActiveResource" />
public IEnumerable<IResource<T>> Items<T>() where T : class, new() => _current.Select(Convert<T>);
/// <summary>
/// Makes a HTTP GET request to the default URI and stores the returned resource.
/// </summary>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
public IHalClient Root() => Root(string.Empty);
internal Task<IHalClient> RootAsync() => RootAsync(string.Empty);
/// <summary>
/// Makes a HTTP GET request to the given URL and stores the returned resource.
/// </summary>
/// <param name="href">The URI to request.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
public IHalClient Root(string href) => Execute(href, uri => _client.GetAsync(uri));
/// <summary>
/// Makes a HTTP GET request to the given URL and stores the returned resource.
/// </summary>
/// <param name="href">The URI to request.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
public Task<IHalClient> RootAsync(string href) => ExecuteAsync(href, uri => _client.GetAsync(uri));
/// <summary>
/// Navigates the given link relation and stores the returned resource(s).
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Get(string rel) => Get(rel, null, null);
/// <summary>
/// Navigates the given link relation and stores the returned resource(s).
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Get(string rel, string curie) => Get(rel, null, curie);
/// <summary>
/// Navigates the given templated link relation and stores the returned resource(s).
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Get(string rel, object parameters) => Get(rel, parameters, null);
/// <summary>
/// Navigates the given templated link relation and stores the returned resource(s).
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Get(string rel, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
var embedded = _current.FirstOrDefault(r => r.Embedded.Any(e => e.Rel == relationship));
if (embedded != null)
{
var current = embedded.Embedded.Where(e => e.Rel == relationship);
return new HalClient(this, current);
}
return BuildAndExecute(relationship, parameters, uri => _client.GetAsync(uri));
}
/// <summary>
/// Navigates the given templated link relation and stores the returned resource(s).
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="AggregateException" />
public async Task<IHalClient> GetAsync(string rel, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
var embedded = _current.FirstOrDefault(r => r.Embedded.Any(e => e.Rel == relationship));
if (embedded != null)
{
var current = embedded.Embedded.Where(e => e.Rel == relationship);
return new HalClient(this, current);
}
return await BuildAndExecuteAsync(relationship, parameters, uri => _client.GetAsync(uri));
}
/// <summary>
/// Navigates the given link relation and stores the returned resource(s).
/// </summary>
/// <param name="resource">The current <see cref="IResource"/>.</param>
/// <param name="rel">The link relation to follow.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Get(IResource resource, string rel) => Get(resource, rel, null, null);
/// <summary>
/// Navigates the given link relation and stores the returned resource(s).
/// </summary>
/// <param name="resource">The current <see cref="IResource"/>.</param>
/// <param name="rel">The link relation to follow.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Get(IResource resource, string rel, string curie) => Get(resource, rel, null, curie);
/// <summary>
/// Navigates the given templated link relation and stores the returned resource(s).
/// </summary>
/// <param name="resource">The current <see cref="IResource"/>.</param>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Get(IResource resource, string rel, object parameters) => Get(resource, rel, parameters, null);
/// <summary>
/// Navigates the given templated link relation and stores the returned resource(s).
/// </summary>
/// <param name="resource">The current <see cref="IResource"/>.</param>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Get(IResource resource, string rel, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
if (resource.Embedded.Any(e => e.Rel == relationship))
{
var current = resource.Embedded.Where(e => e.Rel == relationship);
return new HalClient(this, current);
}
var link = resource.Links.FirstOrDefault(l => l.Rel == relationship);
if (link == null)
throw new FailedToResolveRelationship(relationship);
return Execute(Construct(link, parameters), uri => _client.GetAsync(uri));
}
/// <summary>
/// Navigates the given templated link relation and stores the returned resource(s).
/// </summary>
/// <param name="resource">The current <see cref="IResource"/>.</param>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="AggregateException" />
public async Task<IHalClient> GetAsync(IResource resource, string rel, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
if (resource.Embedded.Any(e => e.Rel == relationship))
{
var current = resource.Embedded.Where(e => e.Rel == relationship);
return new HalClient(this, current);
}
var link = resource.Links.FirstOrDefault(l => l.Rel == relationship);
if (link == null)
throw new FailedToResolveRelationship(relationship);
return await ExecuteAsync(Construct(link, parameters), uri => _client.GetAsync(uri));
}
/// <summary>
/// Makes a HTTP POST request to the given link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <param name="value">The payload to POST.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Post(string rel, object value) => Post(rel, value, null, null);
/// <summary>
/// Makes a HTTP POST request to the given link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <param name="value">The payload to POST.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Post(string rel, object value, string curie) => Post(rel, value, null, curie);
/// <summary>
/// Makes a HTTP POST request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to POST.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Post(string rel, object value, object parameters) => Post(rel, value, parameters, null);
/// <summary>
/// Makes a HTTP POST request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to POST.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Post(string rel, object value, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecute(relationship, parameters, uri => _client.PostAsync(uri, value));
}
/// <summary>
/// Makes a HTTP POST request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to POST.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="AggregateException" />
public Task<IHalClient> PostAsync(string rel, object value, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecuteAsync(relationship, parameters, uri => _client.PostAsync(uri, value));
}
/// <summary>
/// Makes a HTTP PUT request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PUT.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Put(string rel, object value) => Put(rel, value, null, null);
/// <summary>
/// Makes a HTTP PUT request to the given link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <param name="value">The payload to PUT.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Put(string rel, object value, string curie) => Put(rel, value, null, curie);
/// <summary>
/// Makes a HTTP PUT request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PUT.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Put(string rel, object value, object parameters) => Put(rel, value, parameters, null);
/// <summary>
/// Makes a HTTP PUT request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PUT.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Put(string rel, object value, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecute(relationship, parameters, uri => _client.PutAsync(uri, value));
}
/// <summary>
/// Makes a HTTP PUT request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PUT.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="AggregateException" />
public Task<IHalClient> PutAsync(string rel, object value, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecuteAsync(relationship, parameters, uri => _client.PutAsync(uri, value));
}
/// <summary>
/// Makes a HTTP PATCH request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PATCH.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Patch(string rel, object value) => Patch(rel, value, null, null);
/// <summary>
/// Makes a HTTP PATCH request to the given link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <param name="value">The payload to PATCH.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Patch(string rel, object value, string curie) => Patch(rel, value, null, curie);
/// <summary>
/// Makes a HTTP PATCH request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PATCH.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Patch(string rel, object value, object parameters) => Patch(rel, value, parameters, null);
/// <summary>
/// Makes a HTTP PATCH request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PATCH.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Patch(string rel, object value, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecute(relationship, parameters, uri => _client.PatchAsync(uri, value));
}
/// <summary>
/// Makes a HTTP PATCH request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="value">The payload to PATCH.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="AggregateException" />
public Task<IHalClient> PatchAsync(string rel, object value, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecuteAsync(relationship, parameters, uri => _client.PatchAsync(uri, value));
}
/// <summary>
/// Makes a HTTP DELETE request to the given link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Delete(string rel) => Delete(rel, null, null);
/// <summary>
/// Makes a HTTP DELETE request to the given link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The link relation to follow.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
public IHalClient Delete(string rel, string curie) => Delete(rel, null, curie);
/// <summary>
/// Makes a HTTP DELETE request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Delete(string rel, object parameters) => Delete(rel, parameters, null);
/// <summary>
/// Makes a HTTP DELETE request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="FailedToResolveRelationship" />
/// <exception cref="TemplateParametersAreRequired" />
public IHalClient Delete(string rel, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecute(relationship, parameters, uri => _client.DeleteAsync(uri));
}
/// <summary>
/// Makes a HTTP DELETE request to the given templated link relation on the most recently navigated resource.
/// </summary>
/// <param name="rel">The templated link relation to follow.</param>
/// <param name="parameters">An anonymous object containing the template parameters to apply.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>The updated <see cref="IHalClient"/>.</returns>
/// <exception cref="AggregateException" />
public Task<IHalClient> DeleteAsync(string rel, object parameters, string curie)
{
var relationship = Relationship(rel, curie);
return BuildAndExecuteAsync(relationship, parameters, uri => _client.DeleteAsync(uri));
}
/// <summary>
/// Determines whether the most recently navigated resource contains the given link relation.
/// </summary>
/// <param name="rel">The link relation to look for.</param>
/// <returns>Whether or not the link relation exists.</returns>
public bool Has(string rel) => Has(rel, null);
/// <summary>
/// Determines whether the most recently navigated resource contains the given link relation.
/// </summary>
/// <param name="rel">The link relation to look for.</param>
/// <param name="curie">The curie of the link relation.</param>
/// <returns>Whether or not the link relation exists.</returns>
public bool Has(string rel, string curie)
{
var relationship = Relationship(rel, curie);
return
_current.Any(r => r.Embedded.Any(e => e.Rel == relationship))
|| _current.Any(r => r.Links.Any(l => l.Rel == relationship));
}
private IHalClient BuildAndExecute(string relationship, object parameters, Func<string, Task<HttpResponseMessage>> command)
{
var resource = _current.FirstOrDefault(r => r.Links.Any(l => l.Rel == relationship));
if (resource == null)
throw new FailedToResolveRelationship(relationship);
var link = resource.Links.FirstOrDefault(l => l.Rel == relationship);
return Execute(Construct(link, parameters), command);
}
internal Task<IHalClient> BuildAndExecuteAsync(string relationship, object parameters, Func<string, Task<HttpResponseMessage>> command)
{
var resource = _current.FirstOrDefault(r => r.Links.Any(l => l.Rel == relationship));
if (resource == null)
throw new FailedToResolveRelationship(relationship);
var link = resource.Links.FirstOrDefault(l => l.Rel == relationship);
return ExecuteAsync(Construct(link, parameters), command);
}
private IHalClient Execute(string uri, Func<string, Task<HttpResponseMessage>> command)
{
var result = command(uri).Result;
return Process(result);
}
internal async Task<IHalClient> ExecuteAsync(string uri, Func<string, Task<HttpResponseMessage>> command)
{
var result = await command(uri);
return Process(result);
}
private IHalClient Process(HttpResponseMessage result)
{
AssertSuccessfulStatusCode(result);
var current =
new[]
{
result.Content == null
? new Resource()
: result.Content.ReadAsAsync<Resource>(_formatters).Result
};
return new HalClient(this, current);
}
private static string Construct(ILink link, object parameters)
{
if (!link.Templated)
return link.Href;
if (parameters == null)
throw new TemplateParametersAreRequired(link);
var template = new UriTemplate(link.Href, caseInsensitiveParameterNames: true);
template.AddParameters(parameters);
return template.Resolve();
}
private static IResource<T> Convert<T>(IResource resource)
where T : class, new() =>
new Resource<T>
{
Rel = resource.Rel,
Href = resource.Href,
Name = resource.Name,
Data = resource.Data<T>(),
Links = resource.Links,
Embedded = resource.Embedded
};
private static void AssertSuccessfulStatusCode(HttpResponseMessage result)
{
if (!result.IsSuccessStatusCode)
throw new HttpRequestFailed(result.StatusCode);
}
private IResource Latest
{
get
{
if (_current == null || !_current.Any())
throw new NoActiveResource();
return _current.Last();
}
}
private static string Relationship(string rel, string curie) => curie == null ? rel : $"{curie}:{rel}";
}
}
| |
#define DEV
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/*!
\brief This behaviour class manages the line drawing on a basic 2D shape
\sa PanelInfo
\sa Line
*/
public class VectrosityPanel : MonoBehaviour
{
public Camera GUICam; //!< The Isometric camera which will display the layer
public bool draw = true; //!< Toggles drawing of the lines
public RectTransform graphPlaceHolder;
public string identifier;
private const int width = 200;
private const float height = 200;
public ReactionEngine _reactionEngine;
public LinkedList<Medium> _mediums;
public int _mediumId;
public List<Line> _lines = new List<Line>();
public int lineCount;
public Dictionary<string, Molecule> _molecules;
public bool _paused = false;
private bool areLinesNull = false;
public void setPause(bool paused)
{
_paused = paused;
}
public int getMediumId()
{
return _mediumId;
}
private bool safeLazyInit()
{
if (null == _reactionEngine)
{
_reactionEngine = ReactionEngine.get();
}
if (_reactionEngine != null)
{
if (null == _mediums)
{
_mediums = _reactionEngine.getMediumList();
}
if (null == _mediums)
{
Debug.LogWarning(this.GetType() + " safeLazyInit failed to get mediums");
return false;
}
}
else
{
Debug.LogWarning(this.GetType() + " safeLazyInit failed to get ReactionEngine");
return false;
}
return true;
}
public void setMedium(int mediumId)
{
if (!safeLazyInit())
return;
_mediumId = mediumId;
Medium medium = ReactionEngine.getMediumFromId(_mediumId, _mediums);
if (medium == null)
{
Debug.LogError(this.GetType() + " Can't find the given medium (" + _mediumId + ")");
return;
}
_molecules = medium.getMolecules();
if (_molecules == null)
{
Debug.LogError(this.GetType() + " Can't find molecules in medium (" + _mediumId + ")");
return;
}
Line line;
foreach (Molecule m in _molecules.Values)
{
line = _lines.Find(l => m.getName() == l.moleculeName);
if (null == line)
{
string moleculeName = m.getName();
_lines.Add(new Line(width, height, _mediumId, m.getName(), graphPlaceHolder));
}
}
drawLines(true);
lineCount = _lines.Count;
}
// Use this for initialization
void Start()
{
safeLazyInit();
_lines = new List<Line>();
setMedium(_mediumId);
}
// Update is called once per frame
void Update()
{
//bool resize = refreshInfos();
//drawLines(resize);
#if DEV
if(Input.GetKeyDown(KeyCode.W)) {
draw = !draw;
}
#endif
if (draw)
{
//bool resize = refreshInfos();
//drawLines(resize);
drawLines(false);
}
#if DEV
if (Input.GetKeyDown(KeyCode.Z))
{
if (_mediumId == 1)
{
foreach (Line line in _lines)
{
line.doDebugAction();
}
}
}
if (Input.GetKeyDown(KeyCode.E))
{
if (_mediumId == 1)
{
if (areLinesNull)
{
// Debug.Log(this.GetType() + " toggling lines with areLinesNull=" + areLinesNull + ": creating lines");
foreach (Line line in _lines)
{
line.initializeVectorLine();
// Debug.Log(this.GetType() + " initialized line " + line.name);
}
areLinesNull = false;
}
else
{
// Debug.Log(this.GetType() + " toggling lines with areLinesNull=" + areLinesNull + ": destroying lines");
foreach (Line line in _lines)
{
line.destroyLine();
// Debug.Log(this.GetType() + " destroyed line " + line.name);
}
areLinesNull = true;
}
}
}
#endif
}
// can only be called directly by GUITransitioner
// use GUITransitioner.showGraphs instead
public void show(bool show)
{
foreach (Line line in _lines)
{
line.setActive(show);
}
}
void OnDisable()
{
// Debug.Log(this.GetType() + " OnDisable " + identifier);
GUITransitioner.showGraphs(false, GUITransitioner.GRAPH_HIDER.VECTROSITYPANEL);
}
void OnEnable()
{
// Debug.Log(this.GetType() + " OnEnable " + identifier);
GUITransitioner.showGraphs(true, GUITransitioner.GRAPH_HIDER.VECTROSITYPANEL);
}
/*!
* \brief Will draw the lines in the list
* \param resize If true will resize the lines first
*/
private void drawLines(bool resize)
{
if (_molecules == null)
return;
foreach (Line line in _lines)
{
Molecule m = ReactionEngine.getMoleculeFromName(line.moleculeName, _molecules);
//TODO dynamic resize
//if(resize)
//line.resize();
if (!_paused)
{
if (m != null)
{
line.addPoint(m.getConcentration());
}
else
{
line.addPoint(0f);
}
}
line.redraw();
}
}
}
| |
using System;
using System.Runtime.InteropServices;
#pragma warning disable 1591
namespace GongSolutions.Shell.Interop
{
[Flags]
public enum LVIF
{
LVIF_TEXT = 0x0001,
LVIF_IMAGE = 0x0002,
LVIF_PARAM = 0x0004,
LVIF_STATE = 0x0008,
LVIF_INDENT = 0x0010,
LVIF_GROUPID = 0x0100,
LVIF_COLUMNS = 0x0200,
LVIF_NORECOMPUTE = 0x0800,
LVIF_DI_SETITEM = 0x1000,
LVIF_COLFMT = 0x00010000,
}
[Flags]
public enum LVIS
{
LVIS_FOCUSED = 0x0001,
LVIS_SELECTED = 0x0002,
LVIS_CUT = 0x0004,
LVIS_DROPHILITED = 0x0008,
LVIS_ACTIVATING = 0x0020,
LVIS_OVERLAYMASK = 0x0F00,
LVIS_STATEIMAGEMASK = 0xF000,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct LVITEMA
{
public LVIF mask;
public int iItem;
public int iSubItem;
public LVIS state;
public LVIS stateMask;
[MarshalAs(UnmanagedType.LPTStr)]
public string pszText;
public int cchTextMax;
public int iImage;
public int lParam;
}
public enum LVSIL
{
LVSIL_NORMAL = 0,
LVSIL_SMALL = 1,
LVSIL_STATE = 2,
}
[StructLayout(LayoutKind.Sequential)]
public struct MENUINFO
{
public UInt32 cbSize;
public MIM fMask;
public UInt32 dwStyle;
public UInt32 cyMax;
public IntPtr hbrBack;
public UInt32 dwContextHelpID;
public UIntPtr dwMenuData;
}
[StructLayout(LayoutKind.Sequential)]
public struct MENUITEMINFO
{
public UInt32 cbSize;
public MIIM fMask;
public UInt32 fType;
public UInt32 fState;
public UInt32 wID;
public IntPtr hSubMenu;
public IntPtr hbmpChecked;
public IntPtr hbmpUnchecked;
public UIntPtr dwItemData;
public string dwTypeData;
public UInt32 cch;
public IntPtr hbmpItem;
}
public enum MF
{
MF_BYCOMMAND = 0x00000000,
MF_BYPOSITION = 0x00000400,
}
public enum MIIM : uint
{
MIIM_STATE = 0x00000001,
MIIM_ID = 0x00000002,
MIIM_SUBMENU = 0x00000004,
MIIM_CHECKMARKS = 0x00000008,
MIIM_TYPE = 0x00000010,
MIIM_DATA = 0x00000020,
MIIM_STRING = 0x00000040,
MIIM_BITMAP = 0x00000080,
MIIM_FTYPE = 0x00000100,
}
public enum MIM : uint
{
MIM_MAXHEIGHT = 0x00000001,
MIM_BACKGROUND = 0x00000002,
MIM_HELPID = 0x00000004,
MIM_MENUDATA = 0x00000008,
MIM_STYLE = 0x00000010,
MIM_APPLYTOSUBMENUS = 0x80000000,
}
public enum MK
{
MK_LBUTTON = 0x0001,
MK_RBUTTON = 0x0002,
MK_SHIFT = 0x0004,
MK_CONTROL = 0x0008,
MK_MBUTTON = 0x0010,
MK_ALT = 0x1000,
}
public enum MSG
{
WM_COMMAND = 0x0111,
WM_VSCROLL = 0x0115,
LVM_FIRST = 0x1000,
LVM_SETIMAGELIST = 0x1003,
LVM_GETITEMCOUNT = 0x1004,
LVM_GETITEMA = 0x1005,
LVM_EDITLABEL = 0x1017,
LVM_GETCOLUMNWIDTH = LVM_FIRST + 29,
LVM_SETCOLUMNWIDTH = LVM_FIRST + 30,
TVM_SETIMAGELIST = 4361,
TVM_SETITEMW = 4415
}
[Flags]
public enum TPM
{
TPM_LEFTBUTTON = 0x0000,
TPM_RIGHTBUTTON = 0x0002,
TPM_LEFTALIGN = 0x0000,
TPM_CENTERALIGN = 0x000,
TPM_RIGHTALIGN = 0x000,
TPM_TOPALIGN = 0x0000,
TPM_VCENTERALIGN = 0x0010,
TPM_BOTTOMALIGN = 0x0020,
TPM_HORIZONTAL = 0x0000,
TPM_VERTICAL = 0x0040,
TPM_NONOTIFY = 0x0080,
TPM_RETURNCMD = 0x0100,
TPM_RECURSE = 0x0001,
TPM_HORPOSANIMATION = 0x0400,
TPM_HORNEGANIMATION = 0x0800,
TPM_VERPOSANIMATION = 0x1000,
TPM_VERNEGANIMATION = 0x2000,
TPM_NOANIMATION = 0x4000,
TPM_LAYOUTRTL = 0x8000,
}
[Flags]
public enum TVIF
{
TVIF_TEXT = 0x0001,
TVIF_IMAGE = 0x0002,
TVIF_PARAM = 0x0004,
TVIF_STATE = 0x0008,
TVIF_HANDLE = 0x0010,
TVIF_SELECTEDIMAGE = 0x0020,
TVIF_CHILDREN = 0x0040,
TVIF_INTEGRAL = 0x0080,
}
[Flags]
public enum TVIS
{
TVIS_SELECTED = 0x0002,
TVIS_CUT = 0x0004,
TVIS_DROPHILITED = 0x0008,
TVIS_BOLD = 0x0010,
TVIS_EXPANDED = 0x0020,
TVIS_EXPANDEDONCE = 0x0040,
TVIS_EXPANDPARTIAL = 0x0080,
TVIS_OVERLAYMASK = 0x0F00,
TVIS_STATEIMAGEMASK = 0xF000,
TVIS_USERMASK = 0xF000,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct TVITEMW
{
public TVIF mask;
public IntPtr hItem;
public TVIS state;
public TVIS stateMask;
public string pszText;
public int cchTextMax;
public int iImage;
public int iSelectedImage;
public int cChildren;
public int lParam;
}
internal enum GetWindow_Cmd : uint
{
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
class User32
{
[DllImport("user32.dll")]
public static extern bool DeleteMenu(IntPtr hMenu, int uPosition,
MF uFlags);
[DllImport("user32.dll")]
public static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
[DllImport("user32.dll")]
public static extern IntPtr EnumChildWindows(IntPtr parentHandle,
Win32Callback callback, IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool GetMenuInfo(IntPtr hmenu,
ref MENUINFO lpcmi);
[DllImport("user32.dll")]
public static extern int GetMenuItemCount(IntPtr hMenu);
[DllImport("user32.dll")]
public static extern bool GetMenuItemInfo(IntPtr hMenu, int uItem,
bool fByPosition, ref MENUITEMINFO lpmii);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);
[DllImport("user32.dll")]
public static extern uint RegisterClipboardFormat(string lpszFormat);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, MSG Msg,
int wParam, int lParam);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, MSG Msg,
int wParam, ref LVITEMA lParam);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, MSG Msg,
int wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, MSG Msg,
int wParam, ref TVITEMW lParam);
[DllImport("user32.dll")]
public static extern bool SetMenuInfo(IntPtr hmenu,
ref MENUINFO lpcmi);
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd,
IntPtr hWndInsertAfter, int X, int Y, int cx, int cy,
uint uFlags);
[DllImport("user32.dll")]
public static extern int TrackPopupMenuEx(IntPtr hmenu,
TPM fuFlags, int x, int y, IntPtr hwnd, IntPtr lptpm);
public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam);
}
}
| |
// Copyright 2017, Google LLC All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Bigtable.Admin.V2;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Bigtable.Admin.V2.Snippets
{
/// <summary>Generated snippets</summary>
public class GeneratedBigtableTableAdminClientSnippets
{
/// <summary>Snippet for CreateTableAsync</summary>
public async Task CreateTableAsync()
{
// Snippet: CreateTableAsync(InstanceName,string,Table,CallSettings)
// Additional: CreateTableAsync(InstanceName,string,Table,CancellationToken)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
string tableId = "";
Table table = new Table();
// Make the request
Table response = await bigtableTableAdminClient.CreateTableAsync(parent, tableId, table);
// End snippet
}
/// <summary>Snippet for CreateTable</summary>
public void CreateTable()
{
// Snippet: CreateTable(InstanceName,string,Table,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
string tableId = "";
Table table = new Table();
// Make the request
Table response = bigtableTableAdminClient.CreateTable(parent, tableId, table);
// End snippet
}
/// <summary>Snippet for CreateTableAsync</summary>
public async Task CreateTableAsync_RequestObject()
{
// Snippet: CreateTableAsync(CreateTableRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
CreateTableRequest request = new CreateTableRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
TableId = "",
Table = new Table(),
};
// Make the request
Table response = await bigtableTableAdminClient.CreateTableAsync(request);
// End snippet
}
/// <summary>Snippet for CreateTable</summary>
public void CreateTable_RequestObject()
{
// Snippet: CreateTable(CreateTableRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
CreateTableRequest request = new CreateTableRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
TableId = "",
Table = new Table(),
};
// Make the request
Table response = bigtableTableAdminClient.CreateTable(request);
// End snippet
}
/// <summary>Snippet for ListTablesAsync</summary>
public async Task ListTablesAsync()
{
// Snippet: ListTablesAsync(InstanceName,string,int?,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
// Make the request
PagedAsyncEnumerable<ListTablesResponse, Table> response =
bigtableTableAdminClient.ListTablesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Table item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTablesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTables</summary>
public void ListTables()
{
// Snippet: ListTables(InstanceName,string,int?,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
// Make the request
PagedEnumerable<ListTablesResponse, Table> response =
bigtableTableAdminClient.ListTables(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Table item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTablesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTablesAsync</summary>
public async Task ListTablesAsync_RequestObject()
{
// Snippet: ListTablesAsync(ListTablesRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
ListTablesRequest request = new ListTablesRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
// Make the request
PagedAsyncEnumerable<ListTablesResponse, Table> response =
bigtableTableAdminClient.ListTablesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Table item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTablesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTables</summary>
public void ListTables_RequestObject()
{
// Snippet: ListTables(ListTablesRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
ListTablesRequest request = new ListTablesRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
// Make the request
PagedEnumerable<ListTablesResponse, Table> response =
bigtableTableAdminClient.ListTables(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Table item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTablesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableAsync()
{
// Snippet: GetTableAsync(TableName,CallSettings)
// Additional: GetTableAsync(TableName,CancellationToken)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
TableName name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
// Make the request
Table response = await bigtableTableAdminClient.GetTableAsync(name);
// End snippet
}
/// <summary>Snippet for GetTable</summary>
public void GetTable()
{
// Snippet: GetTable(TableName,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
TableName name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
// Make the request
Table response = bigtableTableAdminClient.GetTable(name);
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableAsync_RequestObject()
{
// Snippet: GetTableAsync(GetTableRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
GetTableRequest request = new GetTableRequest
{
TableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
};
// Make the request
Table response = await bigtableTableAdminClient.GetTableAsync(request);
// End snippet
}
/// <summary>Snippet for GetTable</summary>
public void GetTable_RequestObject()
{
// Snippet: GetTable(GetTableRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
GetTableRequest request = new GetTableRequest
{
TableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
};
// Make the request
Table response = bigtableTableAdminClient.GetTable(request);
// End snippet
}
/// <summary>Snippet for DeleteTableAsync</summary>
public async Task DeleteTableAsync()
{
// Snippet: DeleteTableAsync(TableName,CallSettings)
// Additional: DeleteTableAsync(TableName,CancellationToken)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
TableName name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
// Make the request
await bigtableTableAdminClient.DeleteTableAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteTable</summary>
public void DeleteTable()
{
// Snippet: DeleteTable(TableName,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
TableName name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
// Make the request
bigtableTableAdminClient.DeleteTable(name);
// End snippet
}
/// <summary>Snippet for DeleteTableAsync</summary>
public async Task DeleteTableAsync_RequestObject()
{
// Snippet: DeleteTableAsync(DeleteTableRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
DeleteTableRequest request = new DeleteTableRequest
{
TableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
};
// Make the request
await bigtableTableAdminClient.DeleteTableAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteTable</summary>
public void DeleteTable_RequestObject()
{
// Snippet: DeleteTable(DeleteTableRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
DeleteTableRequest request = new DeleteTableRequest
{
TableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
};
// Make the request
bigtableTableAdminClient.DeleteTable(request);
// End snippet
}
/// <summary>Snippet for ModifyColumnFamiliesAsync</summary>
public async Task ModifyColumnFamiliesAsync()
{
// Snippet: ModifyColumnFamiliesAsync(TableName,IEnumerable<ModifyColumnFamiliesRequest.Types.Modification>,CallSettings)
// Additional: ModifyColumnFamiliesAsync(TableName,IEnumerable<ModifyColumnFamiliesRequest.Types.Modification>,CancellationToken)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
TableName name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
IEnumerable<ModifyColumnFamiliesRequest.Types.Modification> modifications = new List<ModifyColumnFamiliesRequest.Types.Modification>();
// Make the request
Table response = await bigtableTableAdminClient.ModifyColumnFamiliesAsync(name, modifications);
// End snippet
}
/// <summary>Snippet for ModifyColumnFamilies</summary>
public void ModifyColumnFamilies()
{
// Snippet: ModifyColumnFamilies(TableName,IEnumerable<ModifyColumnFamiliesRequest.Types.Modification>,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
TableName name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]");
IEnumerable<ModifyColumnFamiliesRequest.Types.Modification> modifications = new List<ModifyColumnFamiliesRequest.Types.Modification>();
// Make the request
Table response = bigtableTableAdminClient.ModifyColumnFamilies(name, modifications);
// End snippet
}
/// <summary>Snippet for ModifyColumnFamiliesAsync</summary>
public async Task ModifyColumnFamiliesAsync_RequestObject()
{
// Snippet: ModifyColumnFamiliesAsync(ModifyColumnFamiliesRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
ModifyColumnFamiliesRequest request = new ModifyColumnFamiliesRequest
{
TableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
Modifications = { },
};
// Make the request
Table response = await bigtableTableAdminClient.ModifyColumnFamiliesAsync(request);
// End snippet
}
/// <summary>Snippet for ModifyColumnFamilies</summary>
public void ModifyColumnFamilies_RequestObject()
{
// Snippet: ModifyColumnFamilies(ModifyColumnFamiliesRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
ModifyColumnFamiliesRequest request = new ModifyColumnFamiliesRequest
{
TableName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]"),
Modifications = { },
};
// Make the request
Table response = bigtableTableAdminClient.ModifyColumnFamilies(request);
// End snippet
}
/// <summary>Snippet for DropRowRangeAsync</summary>
public async Task DropRowRangeAsync()
{
// Snippet: DropRowRangeAsync(string,ByteString,CallSettings)
// Additional: DropRowRangeAsync(string,ByteString,CancellationToken)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
string formattedName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]").ToString();
ByteString rowKeyPrefix = ByteString.CopyFromUtf8("");
// Make the request
await bigtableTableAdminClient.DropRowRangeAsync(formattedName, rowKeyPrefix);
// End snippet
}
/// <summary>Snippet for DropRowRange</summary>
public void DropRowRange()
{
// Snippet: DropRowRange(string,ByteString,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
string formattedName = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]").ToString();
ByteString rowKeyPrefix = ByteString.CopyFromUtf8("");
// Make the request
bigtableTableAdminClient.DropRowRange(formattedName, rowKeyPrefix);
// End snippet
}
/// <summary>Snippet for DropRowRangeAsync</summary>
public async Task DropRowRangeAsync_RequestObject()
{
// Snippet: DropRowRangeAsync(DropRowRangeRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();
// Initialize request argument(s)
DropRowRangeRequest request = new DropRowRangeRequest
{
Name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]").ToString(),
};
// Make the request
await bigtableTableAdminClient.DropRowRangeAsync(request);
// End snippet
}
/// <summary>Snippet for DropRowRange</summary>
public void DropRowRange_RequestObject()
{
// Snippet: DropRowRange(DropRowRangeRequest,CallSettings)
// Create client
BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
// Initialize request argument(s)
DropRowRangeRequest request = new DropRowRangeRequest
{
Name = new TableName("[PROJECT]", "[INSTANCE]", "[TABLE]").ToString(),
};
// Make the request
bigtableTableAdminClient.DropRowRange(request);
// End snippet
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001;
using System;
using System.Reflection;
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
public static int Status;
public bool? this[string p1, float p2, short[] p3]
{
get
{
MemberClass<T>.Status = 1;
return null;
}
set
{
MemberClass<T>.Status = 2;
}
}
public byte this[dynamic[] p1, ulong[] p2, dynamic p3]
{
get
{
MemberClass<T>.Status = 1;
return (byte)3;
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic this[MyClass p1, char? p2, MyEnum[] p3]
{
get
{
MemberClass<T>.Status = 1;
return p1;
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic[] this[MyClass p1, MyStruct? p2, MyEnum[] p3]
{
get
{
MemberClass<T>.Status = 1;
return new dynamic[]
{
p1, p2
}
;
}
set
{
MemberClass<T>.Status = 2;
}
}
public double[] this[float p1]
{
get
{
MemberClass<T>.Status = 1;
return new double[]
{
1.4, double.Epsilon, double.NaN
}
;
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic this[int?[] p1]
{
get
{
MemberClass<T>.Status = 1;
return p1;
}
set
{
MemberClass<T>.Status = 2;
}
}
public MyClass[] this[MyEnum p1]
{
get
{
MemberClass<T>.Status = 1;
return new MyClass[]
{
null, new MyClass()
{
Field = 3
}
}
;
}
set
{
MemberClass<T>.Status = 2;
}
}
public T this[string p1]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
public MyClass this[string p1, T p2]
{
get
{
MemberClass<T>.Status = 1;
return new MyClass();
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic this[T p1]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
public T this[dynamic p1, T p2]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
public T this[T p1, short p2, dynamic p3, string p4]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
}
public class MemberClassMultipleParams<T, U, V>
{
public static int Status;
public T this[V v, U u]
{
get
{
MemberClassMultipleParams<T, U, V>.Status = 1;
return default(T);
}
set
{
MemberClassMultipleParams<T, U, V>.Status = 2;
}
}
}
public class MemberClassWithClassConstraint<T>
where T : class
{
public static int Status;
public int this[int x]
{
get
{
MemberClassWithClassConstraint<T>.Status = 3;
return 1;
}
set
{
MemberClassWithClassConstraint<T>.Status = 4;
}
}
public T this[decimal dec, dynamic d]
{
get
{
MemberClassWithClassConstraint<T>.Status = 1;
return null;
}
set
{
MemberClassWithClassConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithNewConstraint<T>
where T : new()
{
public static int Status;
public dynamic this[T t]
{
get
{
MemberClassWithNewConstraint<T>.Status = 1;
return new T();
}
set
{
MemberClassWithNewConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithAnotherTypeConstraint<T, U>
where T : U
{
public static int Status;
public U this[dynamic d]
{
get
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 3;
return default(U);
}
set
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 4;
}
}
public dynamic this[int x, U u, dynamic d]
{
get
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 1;
return default(T);
}
set
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 2;
}
}
}
#region Negative tests - you should not be able to construct this with a dynamic object
public class C
{
}
public interface I
{
}
public class MemberClassWithUDClassConstraint<T>
where T : C, new()
{
public static int Status;
public C this[T t]
{
get
{
MemberClassWithUDClassConstraint<T>.Status = 1;
return new T();
}
set
{
MemberClassWithUDClassConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithStructConstraint<T>
where T : struct
{
public static int Status;
public dynamic this[int x]
{
get
{
MemberClassWithStructConstraint<T>.Status = 1;
return x;
}
set
{
MemberClassWithStructConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithInterfaceConstraint<T>
where T : I
{
public static int Status;
public dynamic this[int x, T v]
{
get
{
MemberClassWithInterfaceConstraint<T>.Status = 1;
return default(T);
}
set
{
MemberClassWithInterfaceConstraint<T>.Status = 2;
}
}
}
#endregion
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001;
// <Title> Tests generic class indexer used in + operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string p1 = null;
int result = dy[string.Empty] + dy[p1] + 1;
if (result == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002;
// <Title> Tests generic class indexer used in implicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(15,20\).*CS0649</Expects>
//<Expects Status=warning>\(29,20\).*CS0649</Expects>
using System;
public class Test
{
public class InnerTest1
{
public int field;
public static implicit operator InnerTest2(InnerTest1 t1)
{
MemberClass<InnerTest1> mc = new MemberClass<InnerTest1>();
dynamic dy = mc;
InnerTest1 p2 = t1;
return dy[dy, p2];
}
}
public class InnerTest2
{
public int field;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
InnerTest1 t1 = new InnerTest1();
InnerTest2 result1 = t1; //implicit
return (result1 == null && MemberClass<InnerTest1>.Status == 1) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003;
// <Title> Tests generic class indexer used in implicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public class InnerTest1
{
public byte field;
public static explicit operator InnerTest1(byte t1)
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
dynamic[] p1 = null;
ulong[] p2 = null;
dynamic p3 = null;
dy[p1, p2, p3] = (byte)10;
return new InnerTest1()
{
field = dy[p1, p2, p3]
}
;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
byte b = 1;
InnerTest1 result = (InnerTest1)b;
if (result.field == 3 && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005;
// <Title> Tests generic class indexer used in using block and using expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.IO;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var mc = new MemberClass<string>();
dynamic dy = mc;
var mc2 = new MemberClass<bool>();
dynamic dy2 = mc2;
string result = null;
using (MemoryStream sm = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(sm))
{
sw.Write((string)(dy[string.Empty] ?? "Test"));
sw.Flush();
sm.Position = 0;
using (StreamReader sr = new StreamReader(sm, (bool)dy2[false]))
{
result = sr.ReadToEnd();
}
}
}
if (result == "Test" && MemberClass<string>.Status == 1 && MemberClass<bool>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006;
// <Title> Tests generic class indexer used in the for-condition.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassMultipleParams<int, string, Test> mc = new MemberClassMultipleParams<int, string, Test>();
dynamic dy = mc;
string u = null;
Test v = null;
int index = 10;
for (int i = 10; i > dy[v, u]; i--)
{
index--;
}
//
int ret = M();
if (index == 0 && MemberClassMultipleParams<int, string, Test>.Status == 1)
return ret;
return 1;
}
private static int M()
{
MemberClassWithClassConstraint<Test> mc = new MemberClassWithClassConstraint<Test>();
dynamic dy = mc;
int index = 0;
for (int i = 0; i < 10; i = i + dy[i])
{
dy[i] = i;
index++;
}
if (index == 10 && MemberClassWithClassConstraint<Test>.Status == 3)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008;
// <Title> Tests generic class indexer used in the while/do expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string p1 = null;
float p2 = 1.23f;
short[] p3 = null;
int index = 0;
do
{
index++;
if (index == 10)
break;
}
while (dy[p1, p2, p3] ?? true);
if (index == 10 && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009;
// <Title> Tests generic class indexer used in switch expression.</Title>
// <Description> Won't fix: no dynamic in switch expression </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
bool isChecked = false;
switch ((int)dy["Test"])
{
case 0:
isChecked = true;
break;
default:
break;
}
if (isChecked && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010;
// <Title> Tests generic class indexer used in switch section statement list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string a = "Test";
MyClass p1 = new MyClass()
{
Field = 10
}
;
char? p2 = null;
MyEnum[] p3 = new MyEnum[]
{
MyEnum.Second
}
;
dynamic result = null;
switch (a)
{
case "Test":
dy[p1, p2, p3] = 10;
result = dy[p1, p2, p3];
break;
default:
break;
}
if (((MyClass)result).Field == 10)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011;
// <Title> Tests generic class indexer used in switch default section statement list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string a = "Test1";
MyClass p1 = new MyClass()
{
Field = 10
}
;
MyStruct? p2 = new MyStruct()
{
Number = 11
}
;
MyEnum[] p3 = new MyEnum[10];
dynamic[] result = null;
switch (a)
{
case "Test":
break;
default:
result = dy[p1, p2, p3];
dy[p1, p2, p3] = new dynamic[10];
break;
}
if (result.Length != 2 && MemberClass<int>.Status != 2)
return 1;
if (((MyClass)result[0]).Field == 10 && ((MyStruct)result[1]).Number == 11)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass014.genclass014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass014.genclass014;
// <Title> Tests generic class indexer used in try/catch/finally.</Title>
// <Description>
// try/catch/finally that uses an anonymous method and refer two dynamic parameters.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<int>();
dynamic result = -1;
try
{
Func<string, dynamic> func = delegate (string x)
{
throw new TimeoutException(dy[x].ToString());
}
;
result = func("Test");
return 1;
}
catch (TimeoutException e)
{
if (e.Message != "0")
return 1;
}
finally
{
result = dy[new int?[3]];
}
if (result.Length == 3 && result[0] == null && result[1] == null && result[2] == null && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass015.genclass015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass015.genclass015;
// <Title> Tests generic class indexer used in iterator that calls to a lambda expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections;
public class Test
{
private static dynamic s_dy = new MemberClass<string>();
private static int s_num = 0;
[Fact(Skip = "870811")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
foreach (MyClass[] me in t.Increment())
{
if (MemberClass<string>.Status != 1 || me.Length != 2)
return 1;
}
return 0;
}
public IEnumerable Increment()
{
while (s_num++ < 4)
{
Func<MyEnum, MyClass[]> func = (MyEnum p1) => s_dy[p1];
yield return func((MyEnum)s_num);
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016;
// <Title> Tests generic class indexer used in object initializer inside a collection initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections;
using System.Collections.Generic;
public class Test
{
private string _field = string.Empty;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<string>();
decimal dec = 123M;
List<Test> list = new List<Test>()
{
new Test()
{
_field = dy[dec, dy]
}
};
if (list.Count == 1 && list[0]._field == null && MemberClassWithClassConstraint<string>.Status == 1)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017;
// <Title> Tests generic class indexer used in anonymous type.</Title>
// <Description>
// anonymous type inside a query expression that introduces dynamic variables.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Test
{
private int _field;
public Test()
{
_field = 10;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
List<string> list = new List<string>()
{
"0", "4", null, "6", "4", "4", null
}
;
// string s = "test";
dynamic dy = new MemberClassWithAnotherTypeConstraint<string, string>();
dynamic dy2 = new MemberClassWithNewConstraint<Test>();
Test t = new Test()
{
_field = 1
}
;
var result = list.Where(p => p == dy[dy2]).Select(p => new
{
A = dy2[t],
B = dy[dy2]
}
).ToList();
if (result.Count == 2 && MemberClassWithAnotherTypeConstraint<string, string>.Status == 3 && MemberClassWithNewConstraint<Test>.Status == 1)
{
foreach (var m in result)
{
if (((Test)m.A)._field != 10 || m.B != null)
{
return 1;
}
}
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018;
// <Title> Tests generic class indexer used in static generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return TestMethod<Test>();
}
private static int TestMethod<T>()
{
MemberClassWithNewConstraint<MyClass> mc = new MemberClassWithNewConstraint<MyClass>();
dynamic dy = mc;
MyClass p1 = null;
dy[p1] = dy;
if (MemberClassWithNewConstraint<MyClass>.Status != 2)
return 1;
dynamic p2 = dy[p1];
if (p2.GetType() == typeof(MyClass) && MemberClassWithNewConstraint<MyClass>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020;
// <Title> Tests generic class indexer used in static method body.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : C
{
private int _field;
public Test()
{
_field = 11;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassWithUDClassConstraint<Test> mc = new MemberClassWithUDClassConstraint<Test>();
dynamic dy = mc;
Test t = null;
dy[t] = new C();
if (MemberClassWithUDClassConstraint<Test>.Status != 2)
return 1;
t = new Test()
{
_field = 10
}
;
Test result = (Test)dy[t];
if (result._field != 11 || MemberClassWithUDClassConstraint<Test>.Status != 1)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021;
// <Title> Tests generic class indexer used in static method body.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassWithStructConstraint<char> mc = new MemberClassWithStructConstraint<char>();
dynamic dy = mc;
dy[int.MinValue] = new Test();
if (MemberClassWithStructConstraint<char>.Status != 2)
return 1;
dynamic result = dy[int.MaxValue];
if (result != int.MaxValue || MemberClassWithStructConstraint<char>.Status != 1)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022;
// <Title> Tests generic class indexer used in static method body.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : I
{
public class InnerTest : Test
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassWithInterfaceConstraint<InnerTest> mc = new MemberClassWithInterfaceConstraint<InnerTest>();
dynamic dy = mc;
dy[int.MinValue, new InnerTest()] = new Test();
if (MemberClassWithInterfaceConstraint<InnerTest>.Status != 2)
return 1;
dynamic result = dy[int.MaxValue, null];
if (result != null || MemberClassWithInterfaceConstraint<InnerTest>.Status != 1)
return 1;
return 0;
}
}
//</Code>
}
| |
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 MyFirstS2SAppWeb
{
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 registered for this add-in</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 add-in event
/// </summary>
/// <param name="properties">Properties of an add-in 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 registered for this add-in</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 registered for this add-in</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 add-in. 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 add-in 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 add-in 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 add-in 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 add-in.
/// </summary>
/// <returns>True if this is a high trust add-in.</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 add-in 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
}
}
| |
namespace EtlViewer.Viewer.Controls
{
using EtlViewer.Internal;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
/// <summary>
/// Represents a combination of a standard button on the left and a drop-down button on the right.
/// </summary>
[TemplatePartAttribute(Name = "PART_Popup", Type = typeof(Popup))]
[TemplatePartAttribute(Name = "PART_Button", Type = typeof(Button))]
class SplitButton : MenuItem
{
private Button splitButtonHeaderSite;
/// <summary>
/// Identifies the CornerRadius dependency property.
/// </summary>
public static readonly DependencyProperty CornerRadiusProperty;
private static readonly RoutedEvent ButtonClickEvent;
static SplitButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(typeof(SplitButton)));
CornerRadiusProperty = Border.CornerRadiusProperty.AddOwner(typeof(SplitButton));
IsSubmenuOpenProperty.OverrideMetadata(typeof(SplitButton),
new FrameworkPropertyMetadata(
BooleanBoxes.FalseBox,
new PropertyChangedCallback(OnIsSubmenuOpenChanged),
new CoerceValueCallback(CoerceIsSubmenuOpen)));
ButtonClickEvent = EventManager.RegisterRoutedEvent("ButtonClick", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(SplitButton));
KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(KeyboardNavigationMode.Local));
KeyboardNavigation.ControlTabNavigationProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(KeyboardNavigationMode.None));
KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(SplitButton), new FrameworkPropertyMetadata(KeyboardNavigationMode.None));
EventManager.RegisterClassHandler(typeof(SplitButton), MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClick));
EventManager.RegisterClassHandler(typeof(SplitButton), Mouse.MouseDownEvent, new MouseButtonEventHandler(OnMouseButtonDown), true);
}
protected override void OnKeyDown(KeyEventArgs e)
{
bool isPressed = this.IsPressed;
if (e.Key == Key.Space || e.Key == Key.Enter)
{
this.OnButtonClick();
}
else if(e.Key == Key.Down)
{
this.IsSubmenuOpen = true;
}
base.OnKeyDown(e);
}
/// <summary>
/// Gets or sets a value that represents the degree to which the corners of a <see cref="SplitButton"/> are rounded.
/// </summary>
public CornerRadius CornerRadius
{
get { return (CornerRadius)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
/// <summary>
/// Occurs when the button portion of a <see cref="SplitButton"/> is clicked.
/// </summary>
public event RoutedEventHandler ButtonClick
{
add { base.AddHandler(ButtonClickEvent, value); }
remove { base.RemoveHandler(ButtonClickEvent, value); }
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
splitButtonHeaderSite = this.GetTemplateChild("PART_Button") as Button;
if (splitButtonHeaderSite != null)
{
splitButtonHeaderSite.Click += OnHeaderButtonClick;
}
this.GotKeyboardFocus += SplitButton_GotKeyboardFocus;
}
void SplitButton_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
}
private void OnHeaderButtonClick(Object sender, RoutedEventArgs e)
{
this.IsSubmenuOpen = false;
OnButtonClick();
}
protected virtual void OnButtonClick()
{
base.RaiseEvent(new RoutedEventArgs(ButtonClickEvent, this));
if (Command != null)
{
this.Command.Execute(null);
}
}
private static void OnIsSubmenuOpenChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
SplitButton splitButton = sender as SplitButton;
if ((Boolean)e.NewValue)
{
if (Mouse.Captured != splitButton)
{
Mouse.Capture(splitButton, CaptureMode.SubTree);
}
}
else
{
if (Mouse.Captured == splitButton)
{
Mouse.Capture(null);
}
if (splitButton.IsKeyboardFocused)
{
splitButton.Focus();
}
}
}
/// <summary>
/// Set the IsSubmenuOpen property value at the right time.
/// </summary>
private static Object CoerceIsSubmenuOpen(DependencyObject element, Object value)
{
SplitButton splitButton = element as SplitButton;
if ((Boolean)value)
{
if (!splitButton.IsLoaded)
{
splitButton.Loaded += delegate(Object sender, RoutedEventArgs e)
{
splitButton.CoerceValue(IsSubmenuOpenProperty);
};
return BooleanBoxes.FalseBox;
}
}
return (Boolean)value && splitButton.HasItems;
}
private static void OnMenuItemClick(Object sender, RoutedEventArgs e)
{
SplitButton splitButton = sender as SplitButton;
MenuItem menuItem = e.OriginalSource as MenuItem;
// To make the ButtonClickEvent get fired as we expected, you should mark the ClickEvent
// as handled to prevent the event from poping up to the button portion of the SplitButton.
if (menuItem != null && !typeof(MenuItem).IsAssignableFrom(menuItem.Parent.GetType()))
{
e.Handled = true;
}
if (menuItem != null && splitButton != null)
{
if (splitButton.IsSubmenuOpen)
{
splitButton.CloseSubmenu();
}
}
}
private static void OnMouseButtonDown(Object sender, MouseButtonEventArgs e)
{
SplitButton splitButton = sender as SplitButton;
if (!splitButton.IsKeyboardFocusWithin)
{
splitButton.Focus();
return;
}
if (Mouse.Captured == splitButton && e.OriginalSource == splitButton)
{
splitButton.CloseSubmenu();
return;
}
if (e.Source is MenuItem)
{
MenuItem menuItem = e.Source as MenuItem;
if (menuItem != null)
{
if (!menuItem.HasItems)
{
splitButton.CloseSubmenu();
menuItem.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent, menuItem));
}
}
}
}
private void CloseSubmenu()
{
if (this.IsSubmenuOpen)
{
ClearValue(SplitButton.IsSubmenuOpenProperty);
if (this.IsSubmenuOpen)
{
this.IsSubmenuOpen = false;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.