context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
namespace System.Xml.Xsl.XPath
{
using T = XmlQueryTypeFactory;
internal class XPathQilFactory : QilPatternFactory
{
public XPathQilFactory(QilFactory f, bool debug) : base(f, debug)
{
}
// Helper methods used in addition to QilPatternFactory's ones
public QilNode Error(string res, QilNode args)
{
return Error(InvokeFormatMessage(String(res), args));
}
public QilNode Error(ISourceLineInfo lineInfo, string res, params string[] args)
{
return Error(String(XslLoadException.CreateMessage(lineInfo, res, args)));
}
public QilIterator FirstNode(QilNode n)
{
CheckNodeSet(n);
QilIterator i = For(DocOrderDistinct(n));
return For(Filter(i, Eq(PositionOf(i), Int32(1))));
}
public bool IsAnyType(QilNode n)
{
XmlQueryType xt = n.XmlType;
bool result = !(xt.IsStrict || xt.IsNode);
Debug.Assert(result == (xt.TypeCode == XmlTypeCode.Item || xt.TypeCode == XmlTypeCode.AnyAtomicType), "What else can it be?");
return result;
}
[Conditional("DEBUG")]
public void CheckNode(QilNode n)
{
Debug.Assert(n != null && n.XmlType.IsSingleton && n.XmlType.IsNode, "Must be a singleton node");
}
[Conditional("DEBUG")]
public void CheckNodeSet(QilNode n)
{
Debug.Assert(n != null && n.XmlType.IsNode, "Must be a node-set");
}
[Conditional("DEBUG")]
public void CheckNodeNotRtf(QilNode n)
{
Debug.Assert(n != null && n.XmlType.IsSingleton && n.XmlType.IsNode && n.XmlType.IsNotRtf, "Must be a singleton node and not an Rtf");
}
[Conditional("DEBUG")]
public void CheckString(QilNode n)
{
Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.StringX), "Must be a singleton string");
}
[Conditional("DEBUG")]
public void CheckStringS(QilNode n)
{
Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.StringXS), "Must be a sequence of strings");
}
[Conditional("DEBUG")]
public void CheckDouble(QilNode n)
{
Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.DoubleX), "Must be a singleton Double");
}
[Conditional("DEBUG")]
public void CheckBool(QilNode n)
{
Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.BooleanX), "Must be a singleton Bool");
}
// Return true if inferred type of the given expression is never a subtype of T.NodeS
public bool CannotBeNodeSet(QilNode n)
{
XmlQueryType xt = n.XmlType;
// Do not report compile error if n is a VarPar, whose inferred type forbids nodes (SQLBUDT 339398)
return xt.IsAtomicValue && !xt.IsEmpty && !(n is QilIterator);
}
public QilNode SafeDocOrderDistinct(QilNode n)
{
XmlQueryType xt = n.XmlType;
if (xt.MaybeMany)
{
if (xt.IsNode && xt.IsNotRtf)
{
// node-set
return DocOrderDistinct(n);
}
else if (!xt.IsAtomicValue)
{
QilIterator i;
return Loop(i = Let(n),
Conditional(Gt(Length(i), Int32(1)),
DocOrderDistinct(TypeAssert(i, T.NodeNotRtfS)),
i
)
);
}
}
return n;
}
public QilNode InvokeFormatMessage(QilNode res, QilNode args)
{
CheckString(res);
CheckStringS(args);
return XsltInvokeEarlyBound(QName("format-message"),
XsltMethods.FormatMessage, T.StringX, new QilNode[] { res, args }
);
}
#region Comparisons
public QilNode InvokeEqualityOperator(QilNodeType op, QilNode left, QilNode right)
{
Debug.Assert(op == QilNodeType.Eq || op == QilNodeType.Ne);
double opCode;
left = TypeAssert(left, T.ItemS);
right = TypeAssert(right, T.ItemS);
switch (op)
{
case QilNodeType.Eq: opCode = (double)XsltLibrary.ComparisonOperator.Eq; break;
default: opCode = (double)XsltLibrary.ComparisonOperator.Ne; break;
}
return XsltInvokeEarlyBound(QName("EqualityOperator"),
XsltMethods.EqualityOperator, T.BooleanX, new QilNode[] { Double(opCode), left, right }
);
}
public QilNode InvokeRelationalOperator(QilNodeType op, QilNode left, QilNode right)
{
Debug.Assert(op == QilNodeType.Lt || op == QilNodeType.Le || op == QilNodeType.Gt || op == QilNodeType.Ge);
double opCode;
left = TypeAssert(left, T.ItemS);
right = TypeAssert(right, T.ItemS);
switch (op)
{
case QilNodeType.Lt: opCode = (double)XsltLibrary.ComparisonOperator.Lt; break;
case QilNodeType.Le: opCode = (double)XsltLibrary.ComparisonOperator.Le; break;
case QilNodeType.Gt: opCode = (double)XsltLibrary.ComparisonOperator.Gt; break;
default: opCode = (double)XsltLibrary.ComparisonOperator.Ge; break;
}
return XsltInvokeEarlyBound(QName("RelationalOperator"),
XsltMethods.RelationalOperator, T.BooleanX, new QilNode[] { Double(opCode), left, right }
);
}
#endregion
#region Type Conversions
[Conditional("DEBUG")]
private void ExpectAny(QilNode n)
{
Debug.Assert(IsAnyType(n), "Unexpected expression type: " + n.XmlType.ToString());
}
public QilNode ConvertToType(XmlTypeCode requiredType, QilNode n)
{
switch (requiredType)
{
case XmlTypeCode.String: return ConvertToString(n);
case XmlTypeCode.Double: return ConvertToNumber(n);
case XmlTypeCode.Boolean: return ConvertToBoolean(n);
case XmlTypeCode.Node: return EnsureNodeSet(n);
case XmlTypeCode.Item: return n;
default: Debug.Fail("Unexpected XmlTypeCode: " + requiredType); return null;
}
}
// XPath spec $4.2, string()
public QilNode ConvertToString(QilNode n)
{
switch (n.XmlType.TypeCode)
{
case XmlTypeCode.Boolean:
return (
n.NodeType == QilNodeType.True ? (QilNode)String("true") :
n.NodeType == QilNodeType.False ? (QilNode)String("false") :
/*default: */ (QilNode)Conditional(n, String("true"), String("false"))
);
case XmlTypeCode.Double:
return (n.NodeType == QilNodeType.LiteralDouble
? (QilNode)String(XPathConvert.DoubleToString((double)(QilLiteral)n))
: (QilNode)XsltConvert(n, T.StringX)
);
case XmlTypeCode.String:
return n;
default:
if (n.XmlType.IsNode)
{
return XPathNodeValue(SafeDocOrderDistinct(n));
}
ExpectAny(n);
return XsltConvert(n, T.StringX);
}
}
// XPath spec $4.3, boolean()
public QilNode ConvertToBoolean(QilNode n)
{
switch (n.XmlType.TypeCode)
{
case XmlTypeCode.Boolean:
return n;
case XmlTypeCode.Double:
// (x < 0 || 0 < x) == (x != 0) && !Double.IsNaN(x)
QilIterator i;
return (n.NodeType == QilNodeType.LiteralDouble
? Boolean((double)(QilLiteral)n < 0 || 0 < (double)(QilLiteral)n)
: Loop(i = Let(n), Or(Lt(i, Double(0)), Lt(Double(0), i)))
);
case XmlTypeCode.String:
return (n.NodeType == QilNodeType.LiteralString
? Boolean(((string)(QilLiteral)n).Length != 0)
: Ne(StrLength(n), Int32(0))
);
default:
if (n.XmlType.IsNode)
{
return Not(IsEmpty(n));
}
ExpectAny(n);
return XsltConvert(n, T.BooleanX);
}
}
// XPath spec $4.4, number()
public QilNode ConvertToNumber(QilNode n)
{
switch (n.XmlType.TypeCode)
{
case XmlTypeCode.Boolean:
return (
n.NodeType == QilNodeType.True ? (QilNode)Double(1) :
n.NodeType == QilNodeType.False ? (QilNode)Double(0) :
/*default: */ (QilNode)Conditional(n, Double(1), Double(0))
);
case XmlTypeCode.Double:
return n;
case XmlTypeCode.String:
return XsltConvert(n, T.DoubleX);
default:
if (n.XmlType.IsNode)
{
return XsltConvert(XPathNodeValue(SafeDocOrderDistinct(n)), T.DoubleX);
}
ExpectAny(n);
return XsltConvert(n, T.DoubleX);
}
}
public QilNode ConvertToNode(QilNode n)
{
if (n.XmlType.IsNode && n.XmlType.IsNotRtf && n.XmlType.IsSingleton)
{
return n;
}
return XsltConvert(n, T.NodeNotRtf);
}
public QilNode ConvertToNodeSet(QilNode n)
{
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return n;
}
return XsltConvert(n, T.NodeNotRtfS);
}
// Returns null if the given expression is never a node-set
public QilNode TryEnsureNodeSet(QilNode n)
{
if (n.XmlType.IsNode && n.XmlType.IsNotRtf)
{
return n;
}
if (CannotBeNodeSet(n))
{
return null;
}
// Ensure it is not an Rtf at runtime
return InvokeEnsureNodeSet(n);
}
// Throws an exception if the given expression is never a node-set
public QilNode EnsureNodeSet(QilNode n)
{
QilNode result = TryEnsureNodeSet(n);
if (result == null)
{
throw new XPathCompileException(SR.XPath_NodeSetExpected);
}
return result;
}
public QilNode InvokeEnsureNodeSet(QilNode n)
{
return XsltInvokeEarlyBound(QName("ensure-node-set"),
XsltMethods.EnsureNodeSet, T.NodeSDod, new QilNode[] { n }
);
}
#endregion
#region Other XPath Functions
public QilNode Id(QilNode context, QilNode id)
{
CheckNodeNotRtf(context);
if (id.XmlType.IsSingleton)
{
return Deref(context, ConvertToString(id));
}
QilIterator i;
return Loop(i = For(id), Deref(context, ConvertToString(i)));
}
public QilNode InvokeStartsWith(QilNode str1, QilNode str2)
{
CheckString(str1);
CheckString(str2);
return XsltInvokeEarlyBound(QName("starts-with"),
XsltMethods.StartsWith, T.BooleanX, new QilNode[] { str1, str2 }
);
}
public QilNode InvokeContains(QilNode str1, QilNode str2)
{
CheckString(str1);
CheckString(str2);
return XsltInvokeEarlyBound(QName("contains"),
XsltMethods.Contains, T.BooleanX, new QilNode[] { str1, str2 }
);
}
public QilNode InvokeSubstringBefore(QilNode str1, QilNode str2)
{
CheckString(str1);
CheckString(str2);
return XsltInvokeEarlyBound(QName("substring-before"),
XsltMethods.SubstringBefore, T.StringX, new QilNode[] { str1, str2 }
);
}
public QilNode InvokeSubstringAfter(QilNode str1, QilNode str2)
{
CheckString(str1);
CheckString(str2);
return XsltInvokeEarlyBound(QName("substring-after"),
XsltMethods.SubstringAfter, T.StringX, new QilNode[] { str1, str2 }
);
}
public QilNode InvokeSubstring(QilNode str, QilNode start)
{
CheckString(str);
CheckDouble(start);
return XsltInvokeEarlyBound(QName("substring"),
XsltMethods.Substring2, T.StringX, new QilNode[] { str, start }
);
}
public QilNode InvokeSubstring(QilNode str, QilNode start, QilNode length)
{
CheckString(str);
CheckDouble(start);
CheckDouble(length);
return XsltInvokeEarlyBound(QName("substring"),
XsltMethods.Substring3, T.StringX, new QilNode[] { str, start, length }
);
}
public QilNode InvokeNormalizeSpace(QilNode str)
{
CheckString(str);
return XsltInvokeEarlyBound(QName("normalize-space"),
XsltMethods.NormalizeSpace, T.StringX, new QilNode[] { str }
);
}
public QilNode InvokeTranslate(QilNode str1, QilNode str2, QilNode str3)
{
CheckString(str1);
CheckString(str2);
CheckString(str3);
return XsltInvokeEarlyBound(QName("translate"),
XsltMethods.Translate, T.StringX, new QilNode[] { str1, str2, str3 }
);
}
public QilNode InvokeLang(QilNode lang, QilNode context)
{
CheckString(lang);
CheckNodeNotRtf(context);
return XsltInvokeEarlyBound(QName(nameof(lang)),
XsltMethods.Lang, T.BooleanX, new QilNode[] { lang, context }
);
}
public QilNode InvokeFloor(QilNode value)
{
CheckDouble(value);
return XsltInvokeEarlyBound(QName("floor"),
XsltMethods.Floor, T.DoubleX, new QilNode[] { value }
);
}
public QilNode InvokeCeiling(QilNode value)
{
CheckDouble(value);
return XsltInvokeEarlyBound(QName("ceiling"),
XsltMethods.Ceiling, T.DoubleX, new QilNode[] { value }
);
}
public QilNode InvokeRound(QilNode value)
{
CheckDouble(value);
return XsltInvokeEarlyBound(QName("round"),
XsltMethods.Round, T.DoubleX, new QilNode[] { value }
);
}
#endregion
}
}
| |
#pragma warning disable 169
namespace NEventStore
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using NEventStore.Persistence;
using NEventStore.Persistence.AcceptanceTests;
using NEventStore.Persistence.AcceptanceTests.BDD;
using Xunit;
using ALinq;
using NSubstitute;
public class when_building_a_stream : on_the_event_stream
{
private const int MinRevision = 2;
private const int MaxRevision = 7;
private readonly int _eachCommitHas = 2.Events();
private ICommit[] _committed;
protected override Task Context()
{
_committed = new[]
{
BuildCommitStub(2, 1, _eachCommitHas), // 1-2
BuildCommitStub(4, 2, _eachCommitHas), // 3-4
BuildCommitStub(6, 3, _eachCommitHas), // 5-6
BuildCommitStub(8, 3, _eachCommitHas) // 7-8
};
_committed[0].Headers["Common"] = string.Empty;
_committed[1].Headers["Common"] = string.Empty;
_committed[2].Headers["Common"] = string.Empty;
_committed[3].Headers["Common"] = string.Empty;
_committed[0].Headers["Unique"] = string.Empty;
//A.CallTo(() => Persistence.GetFrom(BucketId, StreamId, MinRevision, MaxRevision)).Returns(_committed.ToAsync());
Persistence.GetFrom(BucketId, StreamId, MinRevision, MaxRevision).Returns(_committed.ToAsync());
return Task.FromResult(true);
}
protected override Task Because()
{
Stream = new OptimisticEventStream(BucketId, StreamId, Persistence, SystemTimeProvider);
Stream.Initialize(MinRevision, MaxRevision).Wait() ;
return Task.FromResult(true);
}
[Fact]
public void should_have_the_correct_stream_identifier()
{
Stream.StreamId.Should().Be(StreamId);
}
[Fact]
public void should_have_the_correct_head_stream_revision()
{
Stream.StreamRevision.Should().Be(MaxRevision);
}
[Fact]
public void should_have_the_correct_head_commit_sequence()
{
Stream.CommitSequence.Should().Be(_committed.Last().CommitSequence);
}
[Fact]
public void should_not_include_events_below_the_minimum_revision_indicated()
{
Stream.CommittedEvents.First().Should().Be(_committed.First().Events.Last());
}
[Fact]
public void should_not_include_events_above_the_maximum_revision_indicated()
{
Stream.CommittedEvents.Last().Should().Be(_committed.Last().Events.First());
}
[Fact]
public void should_have_all_of_the_committed_events_up_to_the_stream_revision_specified()
{
Stream.CommittedEvents.Count.Should().Be(MaxRevision - MinRevision + 1);
}
[Fact]
public void should_contain_the_headers_from_the_underlying_commits()
{
Stream.CommittedHeaders.Count.Should().Be(2);
}
}
public class when_the_head_event_revision_is_less_than_the_max_desired_revision : on_the_event_stream
{
private readonly int _eventsPerCommit = 2.Events();
private ICommit[] _committed;
protected override Task Context()
{
_committed = new[]
{
BuildCommitStub(2, 1, _eventsPerCommit), // 1-2
BuildCommitStub(4, 2, _eventsPerCommit), // 3-4
BuildCommitStub(6, 3, _eventsPerCommit), // 5-6
BuildCommitStub(8, 3, _eventsPerCommit) // 7-8
};
//A.CallTo(() => Persistence.GetFrom(BucketId, StreamId, 0, int.MaxValue)).Returns(_committed.AsAsyncEnumerable());
Persistence.GetFrom(BucketId, StreamId, 0, int.MaxValue).Returns(_committed.AsAsyncEnumerable());
return Task.FromResult(true);
}
protected override async Task Because()
{
Stream = new OptimisticEventStream(BucketId, StreamId, Persistence, SystemTimeProvider);
await Stream.Initialize(0, int.MaxValue);
}
[Fact]
public void should_set_the_stream_revision_to_the_revision_of_the_most_recent_event()
{
Stream.StreamRevision.Should().Be(_committed.Last().StreamRevision);
}
}
public class when_adding_a_null_event_message : on_the_event_stream
{
protected override Task Because()
{
Stream.Add(null);
return Task.FromResult(true);
}
[Fact]
public void should_be_ignored()
{
Stream.UncommittedEvents.Should().BeEmpty();
}
}
public class when_adding_an_unpopulated_event_message : on_the_event_stream
{
protected override Task Because()
{
Stream.Add(new EventMessage {Body = null});
return Task.FromResult(true);
}
[Fact]
public void should_be_ignored()
{
Stream.UncommittedEvents.Should().BeEmpty();
}
}
public class when_adding_a_fully_populated_event_message : on_the_event_stream
{
protected override Task Because()
{
Stream.Add(new EventMessage {Body = "populated"});
return Task.FromResult(true);
}
[Fact]
public void should_add_the_event_to_the_set_of_uncommitted_events()
{
Stream.UncommittedEvents.Count.Should().Be(1);
}
}
public class when_adding_multiple_populated_event_messages : on_the_event_stream
{
protected override Task Because()
{
Stream.Add(new EventMessage {Body = "populated"});
Stream.Add(new EventMessage {Body = "also populated"});
return Task.FromResult(true);
}
[Fact]
public void should_add_all_of_the_events_provided_to_the_set_of_uncommitted_events()
{
Stream.UncommittedEvents.Count.Should().Be(2);
}
}
public class when_adding_a_simple_object_as_an_event_message : on_the_event_stream
{
private const string MyEvent = "some event data";
protected override Task Because()
{
Stream.Add(new EventMessage {Body = MyEvent});
return Task.FromResult(true);
}
[Fact]
public void should_add_the_uncommited_event_to_the_set_of_uncommitted_events()
{
Stream.UncommittedEvents.Count.Should().Be(1);
}
[Fact]
public void should_wrap_the_uncommited_event_in_an_EventMessage_object()
{
Stream.UncommittedEvents.First().Body.Should().Be(MyEvent);
}
}
public class when_clearing_any_uncommitted_changes : on_the_event_stream
{
protected override Task Context()
{
Stream.Add(new EventMessage {Body = string.Empty});
return Task.FromResult(true);
}
protected override Task Because()
{
Stream.ClearChanges();
return Task.FromResult(true);
}
[Fact]
public void should_clear_all_uncommitted_events()
{
Stream.UncommittedEvents.Count.Should().Be(0);
}
}
public class when_committing_an_empty_changeset : on_the_event_stream
{
protected override async Task Because()
{
await Stream.CommitChanges(Guid.NewGuid());
}
[Fact]
public void should_not_call_the_underlying_infrastructure()
{
//A.CallTo(() => Persistence.Commit(A<CommitAttempt>._)).MustNotHaveHappened();
Persistence.DidNotReceive().Commit(Arg.Any<CommitAttempt>());
}
[Fact]
public void should_not_increment_the_current_stream_revision()
{
Stream.StreamRevision.Should().Be(0);
}
[Fact]
public void should_not_increment_the_current_commit_sequence()
{
Stream.CommitSequence.Should().Be(0);
}
}
public class when_committing_any_uncommitted_changes : on_the_event_stream
{
private readonly Guid _commitId = Guid.NewGuid();
private readonly Dictionary<string, object> _headers = new Dictionary<string, object> {{"key", "value"}};
private readonly EventMessage _uncommitted = new EventMessage {Body = string.Empty};
private CommitAttempt _constructed;
protected override Task Context()
{
Persistence
.Commit(Arg.Any<CommitAttempt>())
.Returns(c =>
{
var attempt = c.Arg<CommitAttempt>();
_constructed = attempt;
return new Commit(
attempt.BucketId,
attempt.StreamId,
attempt.StreamRevision,
attempt.CommitId,
attempt.CommitSequence,
attempt.CommitStamp,
new LongCheckpoint(0).Value,
attempt.Headers,
attempt.Events
);
});
//A.CallTo(() => Persistence.Commit(A<CommitAttempt>._))
// .Invokes((CommitAttempt _) => _constructed = _)
// .ReturnsLazily((CommitAttempt attempt) => new Commit(
// attempt.BucketId,
// attempt.StreamId,
// attempt.StreamRevision,
// attempt.CommitId,
// attempt.CommitSequence,
// attempt.CommitStamp,
// new LongCheckpoint(0).Value,
// attempt.Headers,
// attempt.Events));
Stream.Add(_uncommitted);
foreach (var item in _headers)
{
Stream.UncommittedHeaders[item.Key] = item.Value;
}
return Task.FromResult(true);
}
protected override async Task Because()
{
await Stream.CommitChanges(_commitId);
}
[Fact]
public void should_have_committed()
{
//A.CallTo(() => Persistence.Commit(A<CommitAttempt>._)).MustHaveHappened(Repeated.Exactly.Once);
_constructed.Should().NotBeNull();
}
[Fact]
public void should_provide_a_commit_to_the_underlying_infrastructure()
{
//A.CallTo(() => Persistence.Commit(A<CommitAttempt>._)).MustHaveHappened(Repeated.Exactly.Once);
Persistence.Received(1).Commit(Arg.Any<CommitAttempt>());
}
[Fact]
public void should_build_the_commit_with_the_correct_bucket_identifier()
{
_constructed.BucketId.Should().Be(BucketId);
}
[Fact]
public void should_build_the_commit_with_the_correct_stream_identifier()
{
_constructed.StreamId.Should().Be(StreamId);
}
[Fact]
public void should_build_the_commit_with_the_correct_stream_revision()
{
_constructed.StreamRevision.Should().Be(DefaultStreamRevision);
}
[Fact]
public void should_build_the_commit_with_the_correct_commit_identifier()
{
_constructed.CommitId.Should().Be(_commitId);
}
[Fact]
public void should_build_the_commit_with_an_incremented_commit_sequence()
{
_constructed.CommitSequence.Should().Be(DefaultCommitSequence);
}
[Fact]
public void should_build_the_commit_with_the_correct_commit_stamp()
{
SystemTimeProvider.UtcNow.Should().Be(_constructed.CommitStamp);
}
[Fact]
public void should_build_the_commit_with_the_headers_provided()
{
_constructed.Headers[_headers.First().Key].Should().Be(_headers.First().Value);
}
[Fact]
public void should_build_the_commit_containing_all_uncommitted_events()
{
_constructed.Events.Count.Should().Be(_headers.Count);
}
[Fact]
public void should_build_the_commit_using_the_event_messages_provided()
{
_constructed.Events.First().Should().Be(_uncommitted);
}
[Fact]
public void should_contain_a_copy_of_the_headers_provided()
{
_constructed.Headers.Should().NotBeEmpty();
}
[Fact]
public void should_update_the_stream_revision()
{
Stream.StreamRevision.Should().Be(_constructed.StreamRevision);
}
[Fact]
public void should_update_the_commit_sequence()
{
Stream.CommitSequence.Should().Be(_constructed.CommitSequence);
}
[Fact]
public void should_add_the_uncommitted_events_the_committed_events()
{
Stream.CommittedEvents.Last().Should().Be(_uncommitted);
}
[Fact]
public void should_clear_the_uncommitted_events_on_the_stream()
{
Stream.UncommittedEvents.Should().BeEmpty();
}
[Fact]
public void should_clear_the_uncommitted_headers_on_the_stream()
{
Stream.UncommittedHeaders.Should().BeEmpty();
}
[Fact]
public void should_copy_the_uncommitted_headers_to_the_committed_stream_headers()
{
Stream.CommittedHeaders.Count.Should().Be(_headers.Count);
}
}
/// <summary>
/// This behavior is primarily to support a NoSQL storage solution where CommitId is not being used as the "primary key"
/// in a NoSQL environment, we'll most likely use StreamId + CommitSequence, which also enables optimistic concurrency.
/// </summary>
public class when_committing_with_an_identifier_that_was_previously_read : on_the_event_stream
{
private ICommit[] _committed;
private Guid _dupliateCommitId;
private Exception _thrown;
protected override async Task Context()
{
_committed = new[] {BuildCommitStub(1, 1, 1)};
_dupliateCommitId = _committed[0].CommitId;
//A.CallTo(() => Persistence.GetFrom(BucketId, StreamId, 0, int.MaxValue)).Returns(_committed.AsAsyncEnumerable());
Persistence.GetFrom(BucketId, StreamId, 0, int.MaxValue).Returns(_committed.AsAsyncEnumerable());
Stream = new OptimisticEventStream(BucketId, StreamId, Persistence, SystemTimeProvider);
await Stream.Initialize(0, int.MaxValue);
}
protected override async Task Because()
{
_thrown = await Catch.Exception(async () => await Stream.CommitChanges(_dupliateCommitId));
}
[Fact]
public void should_throw_a_DuplicateCommitException()
{
_thrown.Should().BeOfType<DuplicateCommitException>();
}
}
public class when_committing_after_another_thread_or_process_has_moved_the_stream_head : on_the_event_stream
{
private const int StreamRevision = 1;
private readonly EventMessage _uncommitted = new EventMessage { Body = string.Empty };
private ICommit[] _committed;
private ICommit[] _discoveredOnCommit;
private CommitAttempt _constructed;
private Exception _thrown;
protected override async Task Context()
{
_committed = new[] {BuildCommitStub(1, 1, 1)};
_discoveredOnCommit = new[] {BuildCommitStub(3, 2, 2)};
//A.CallTo(() => Persistence.Commit(A<CommitAttempt>._)).Throws(new ConcurrencyException());
//A.CallTo(() => Persistence.GetFrom(BucketId, StreamId, StreamRevision, int.MaxValue)).Returns(_committed.AsAsyncEnumerable());
//A.CallTo(() => Persistence.GetFrom(BucketId, StreamId, StreamRevision + 1, int.MaxValue)).Returns(_discoveredOnCommit.AsAsyncEnumerable());
Persistence
.When(x => x.Commit(Arg.Any<CommitAttempt>()))
.Do(x => { throw new ConcurrencyException(); });
Persistence.GetFrom(BucketId, StreamId, StreamRevision, int.MaxValue).Returns(_committed.AsAsyncEnumerable());
Persistence.GetFrom(BucketId, StreamId, StreamRevision + 1, int.MaxValue).Returns(_discoveredOnCommit.AsAsyncEnumerable());
Stream = new OptimisticEventStream(BucketId, StreamId, Persistence, SystemTimeProvider);
await Stream.Initialize(StreamRevision, int.MaxValue);
Stream.Add(_uncommitted);
//await Stream.CommitChanges(Guid.NewGuid());
}
protected override async Task Because()
{
_thrown = await Catch.Exception(async () => await Stream.CommitChanges(Guid.NewGuid()));
}
[Fact]
public void should_throw_a_ConcurrencyException()
{
_thrown.Should().BeOfType<ConcurrencyException>();
}
[Fact]
public void should_query_the_underlying_storage_to_discover_the_new_commits()
{
// A.CallTo(() => Persistence.GetFrom(BucketId, StreamId, StreamRevision + 1, int.MaxValue)).MustHaveHappened(Repeated.Exactly.Once);
Persistence.Received(1).GetFrom(BucketId, StreamId, StreamRevision + 1, int.MaxValue);
}
[Fact]
public void should_update_the_stream_revision_accordingly()
{
Stream.StreamRevision.Should().Be(_discoveredOnCommit[0].StreamRevision);
}
[Fact]
public void should_update_the_commit_sequence_accordingly()
{
Stream.CommitSequence.Should().Be(_discoveredOnCommit[0].CommitSequence);
}
[Fact]
public void should_add_the_newly_discovered_committed_events_to_the_set_of_committed_events_accordingly()
{
Stream.CommittedEvents.Count.Should().Be(_discoveredOnCommit[0].Events.Count + 1);
}
}
public class when_attempting_to_invoke_behavior_on_a_disposed_stream : on_the_event_stream
{
private Exception _thrown;
protected override Task Context()
{
Stream.Dispose();
return Task.FromResult(true);
}
protected override async Task Because()
{
_thrown = await Catch.Exception(async () => await Stream.CommitChanges(Guid.NewGuid()));
}
[Fact]
public void should_throw_a_ObjectDisposedException()
{
_thrown.Should().BeOfType<ObjectDisposedException>();
}
}
public class when_attempting_to_modify_the_event_collections : on_the_event_stream
{
[Fact]
public void should_throw_an_exception_when_adding_to_the_committed_collection()
{
Catch.Exception(() => Stream.CommittedEvents.Add(null)).Should().BeOfType<NotSupportedException>();
}
[Fact]
public void should_throw_an_exception_when_adding_to_the_uncommitted_collection()
{
Catch.Exception(() => Stream.UncommittedEvents.Add(null)).Should().BeOfType<NotSupportedException>();
}
[Fact]
public void should_throw_an_exception_when_clearing_the_committed_collection()
{
Catch.Exception(() => Stream.CommittedEvents.Clear()).Should().BeOfType<NotSupportedException>();
}
[Fact]
public void should_throw_an_exception_when_clearing_the_uncommitted_collection()
{
Catch.Exception(() => Stream.UncommittedEvents.Clear()).Should().BeOfType<NotSupportedException>();
}
[Fact]
public void should_throw_an_exception_when_removing_from_the_committed_collection()
{
Catch.Exception(() => Stream.CommittedEvents.Remove(null)).Should().BeOfType<NotSupportedException>();
}
[Fact]
public void should_throw_an_exception_when_removing_from_the_uncommitted_collection()
{
Catch.Exception(() => Stream.UncommittedEvents.Remove(null)).Should().BeOfType<NotSupportedException>();
}
}
public class when_persistance_store_commit_returns_null : on_the_event_stream
{
protected override Task Context()
{
// simulates pipeline pre-commit hook returning a false
//A.CallTo(() => Persistence.Commit(A<CommitAttempt>.Ignored)).Returns((ICommit)null);
Persistence.Commit(Arg.Any<CommitAttempt>()).Returns((ICommit)null);
return Task.FromResult(true);
}
protected override Task Because()
{
Stream = new OptimisticEventStream(BucketId, StreamId, Persistence, SystemTimeProvider);
Stream.Add(new EventMessage() { Body = "body" });
return Stream.CommitChanges(Guid.NewGuid());
}
[Fact]
public void should_not_contain_commited_events()
{
Stream.CommittedEvents.Count().Should().Be(0);
}
}
public abstract class on_the_event_stream : SpecificationBase, IClassFixture<FakeTimeFixture>
{
protected const int DefaultStreamRevision = 1;
protected const int DefaultCommitSequence = 1;
private ICommitEvents _persistence;
private OptimisticEventStream _stream;
protected const string BucketId = "bucket";
protected readonly string StreamId = Guid.NewGuid().ToString();
private SystemTimeProviderFake _systemTimeProvider;
protected ICommitEvents Persistence
{
get { return _persistence ?? (_persistence = Substitute.For<ICommitEvents>()); }
}
protected OptimisticEventStream Stream
{
get { return _stream ?? (_stream = new OptimisticEventStream(BucketId, StreamId, Persistence, SystemTimeProvider)); }
set { _stream = value; }
}
public SystemTimeProviderFake SystemTimeProvider
{
get
{
return _systemTimeProvider;
}
}
public void SetFixture(FakeTimeFixture data)
{
_systemTimeProvider = data.SystemTimeProvider;
}
protected ICommit BuildCommitStub(int revision, int sequence, int eventCount)
{
var events = new List<EventMessage>(eventCount);
for (int i = 0; i < eventCount; i++)
{
events.Add(new EventMessage());
}
return new Commit(Bucket.Default, StreamId, revision, Guid.NewGuid(), sequence, SystemTimeProvider.UtcNow, new LongCheckpoint(0).Value, null, events);
}
}
public class FakeTimeFixture
{
private SystemTimeProviderFake systemTimeProvider = new SystemTimeProviderFake();
public FakeTimeFixture()
{
SystemTimeProvider.SetResolver(() => new DateTime(2012, 1, 1, 13, 0, 0));
}
public SystemTimeProviderFake SystemTimeProvider
{
get
{
return systemTimeProvider;
}
}
}
}
#pragma warning restore 169
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation runbook draft. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
internal partial class RunbookDraftOperations : IServiceOperations<AutomationManagementClient>, IRunbookDraftOperations
{
/// <summary>
/// Initializes a new instance of the RunbookDraftOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RunbookDraftOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the publish runbook operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> BeginPublishAsync(string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.PublishedBy == null)
{
throw new ArgumentNullException("parameters.PublishedBy");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginPublishAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(parameters.Name);
url = url + "/draft/publish";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LongRunningOperationResultResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ocp-location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> BeginUpdateAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Stream == null)
{
throw new ArgumentNullException("parameters.Stream");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(parameters.Name);
url = url + "/draft/content";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Stream;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/powershell");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
result = new LongRunningOperationResultResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ocp-location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> BeginUpdateGraphAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Stream == null)
{
throw new ArgumentNullException("parameters.Stream");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdateGraphAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(parameters.Name);
url = url + "/draft/content";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = parameters.Stream;
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/powershell");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResultResponse result = null;
// Deserialize Response
result = new LongRunningOperationResultResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ocp-location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the content of runbook draft identified by runbook name.
/// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for
/// more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the runbook content operation.
/// </returns>
public async Task<RunbookContentResponse> ContentAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "ContentAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/content";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RunbookContentResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RunbookContentResponse();
result.Stream = responseContent;
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the runbook draft identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get runbook draft operation.
/// </returns>
public async Task<RunbookDraftGetResponse> GetAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RunbookDraftGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RunbookDraftGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
RunbookDraft runbookDraftInstance = new RunbookDraft();
result.RunbookDraft = runbookDraftInstance;
JToken inEditValue = responseDoc["inEdit"];
if (inEditValue != null && inEditValue.Type != JTokenType.Null)
{
bool inEditInstance = ((bool)inEditValue);
runbookDraftInstance.InEdit = inEditInstance;
}
JToken draftContentLinkValue = responseDoc["draftContentLink"];
if (draftContentLinkValue != null && draftContentLinkValue.Type != JTokenType.Null)
{
ContentLink draftContentLinkInstance = new ContentLink();
runbookDraftInstance.DraftContentLink = draftContentLinkInstance;
JToken uriValue = draftContentLinkValue["uri"];
if (uriValue != null && uriValue.Type != JTokenType.Null)
{
Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue));
draftContentLinkInstance.Uri = uriInstance;
}
JToken contentHashValue = draftContentLinkValue["contentHash"];
if (contentHashValue != null && contentHashValue.Type != JTokenType.Null)
{
ContentHash contentHashInstance = new ContentHash();
draftContentLinkInstance.ContentHash = contentHashInstance;
JToken algorithmValue = contentHashValue["algorithm"];
if (algorithmValue != null && algorithmValue.Type != JTokenType.Null)
{
string algorithmInstance = ((string)algorithmValue);
contentHashInstance.Algorithm = algorithmInstance;
}
JToken valueValue = contentHashValue["value"];
if (valueValue != null && valueValue.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue);
contentHashInstance.Value = valueInstance;
}
}
JToken versionValue = draftContentLinkValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
draftContentLinkInstance.Version = versionInstance;
}
}
JToken creationTimeValue = responseDoc["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
runbookDraftInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
runbookDraftInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]);
if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in parametersSequenceElement)
{
string parametersKey = ((string)property.Name);
JObject varToken = ((JObject)property.Value);
RunbookParameter runbookParameterInstance = new RunbookParameter();
runbookDraftInstance.Parameters.Add(parametersKey, runbookParameterInstance);
JToken typeValue = varToken["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
runbookParameterInstance.Type = typeInstance;
}
JToken isMandatoryValue = varToken["isMandatory"];
if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null)
{
bool isMandatoryInstance = ((bool)isMandatoryValue);
runbookParameterInstance.IsMandatory = isMandatoryInstance;
}
JToken positionValue = varToken["position"];
if (positionValue != null && positionValue.Type != JTokenType.Null)
{
int positionInstance = ((int)positionValue);
runbookParameterInstance.Position = positionInstance;
}
JToken defaultValueValue = varToken["defaultValue"];
if (defaultValueValue != null && defaultValueValue.Type != JTokenType.Null)
{
string defaultValueInstance = ((string)defaultValueValue);
runbookParameterInstance.DefaultValue = defaultValueInstance;
}
}
}
JToken outputTypesArray = responseDoc["outputTypes"];
if (outputTypesArray != null && outputTypesArray.Type != JTokenType.Null)
{
foreach (JToken outputTypesValue in ((JArray)outputTypesArray))
{
runbookDraftInstance.OutputTypes.Add(((string)outputTypesValue));
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the publish runbook operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> PublishAsync(string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken)
{
AutomationManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PublishAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse response = await client.RunbookDraft.BeginPublishAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Retrieve the runbook identified by runbook name. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='runbookName'>
/// Required. The runbook name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the undoedit runbook operation.
/// </returns>
public async Task<RunbookDraftUndoEditResponse> UndoEditAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (runbookName == null)
{
throw new ArgumentNullException("runbookName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("runbookName", runbookName);
TracingAdapter.Enter(invocationId, this, "UndoEditAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/runbooks/";
url = url + Uri.EscapeDataString(runbookName);
url = url + "/draft/undoEdit";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RunbookDraftUndoEditResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RunbookDraftUndoEditResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> UpdateAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
AutomationManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse response = await client.RunbookDraft.BeginUpdateAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Updates the runbook draft with runbookStream as its content. (see
/// http://aka.ms/azureautomationsdk/runbookdraftoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The runbook draft update parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResultResponse> UpdateGraphAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken)
{
AutomationManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateGraphAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse response = await client.RunbookDraft.BeginUpdateAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
}
}
| |
// 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.Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LeadingZeroCount_Vector64_Int16()
{
var test = new SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int16> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16 testClass)
{
var result = AdvSimd.LeadingZeroCount(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16 testClass)
{
fixed (Vector64<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector64((Int16*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Vector64<Int16> _clsVar1;
private Vector64<Int16> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
}
public SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.LeadingZeroCount(
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingZeroCount), new Type[] { typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingZeroCount), new Type[] { typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.LeadingZeroCount(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int16>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector64((Int16*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr);
var result = AdvSimd.LeadingZeroCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr));
var result = AdvSimd.LeadingZeroCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16();
var result = AdvSimd.LeadingZeroCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__LeadingZeroCount_Vector64_Int16();
fixed (Vector64<Int16>* pFld1 = &test._fld1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector64((Int16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.LeadingZeroCount(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector64((Int16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.LeadingZeroCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector64((Int16*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int16> op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.CountLeadingZeroBits(firstOp[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Helpers.CountLeadingZeroBits(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LeadingZeroCount)}<Int16>(Vector64<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.Globalization
{
internal partial class CultureData
{
// ICU constants
const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
const string ICU_COLLATION_KEYWORD = "@collation=";
/// <summary>
/// This method uses the sRealName field (which is initialized by the constructor before this is called) to
/// initialize the rest of the state of CultureData based on the underlying OS globalization library.
/// </summary>
[SecuritySafeCritical]
private unsafe bool InitCultureData()
{
Contract.Assert(_sRealName != null);
string alternateSortName = string.Empty;
string realNameBuffer = _sRealName;
// Basic validation
if (realNameBuffer.Contains("@"))
{
return false; // don't allow ICU variants to come in directly
}
// Replace _ (alternate sort) with @collation= for ICU
int index = realNameBuffer.IndexOf('_');
if (index > 0)
{
if (index >= (realNameBuffer.Length - 1) // must have characters after _
|| realNameBuffer.Substring(index + 1).Contains("_")) // only one _ allowed
{
return false; // fail
}
alternateSortName = realNameBuffer.Substring(index + 1);
realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName;
}
// Get the locale name from ICU
if (!GetLocaleName(realNameBuffer, out _sWindowsName))
{
return false; // fail
}
// Replace the ICU collation keyword with an _
index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
if (index >= 0)
{
_sName = _sWindowsName.Substring(0, index) + "_" + alternateSortName;
}
else
{
_sName = _sWindowsName;
}
_sRealName = _sName;
_iLanguage = this.ILANGUAGE;
if (_iLanguage == 0)
{
_iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
}
_bNeutral = (this.SISO3166CTRYNAME.Length == 0);
_sSpecificCulture = _bNeutral ? LocaleData.GetSpecificCultureName(_sRealName) : _sRealName;
// Remove the sort from sName unless custom culture
if (index>0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
{
_sName = _sWindowsName.Substring(0, index);
}
return true;
}
[SecuritySafeCritical]
internal static bool GetLocaleName(string localeName, out string windowsName)
{
// Get the locale name from ICU
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
if (!Interop.GlobalizationInterop.GetLocaleName(localeName, sb, sb.Capacity))
{
StringBuilderCache.Release(sb);
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
return true;
}
[SecuritySafeCritical]
internal static bool GetDefaultLocaleName(out string windowsName)
{
// Get the default (system) locale name from ICU
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
if (!Interop.GlobalizationInterop.GetDefaultLocaleName(sb, sb.Capacity))
{
StringBuilderCache.Release(sb);
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
return true;
}
private string GetLocaleInfo(LocaleStringData type)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
return GetLocaleInfo(_sWindowsName, type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
[SecuritySafeCritical]
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
Contract.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
case LocaleStringData.NegativeInfinitySymbol:
// not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
}
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
bool result = Interop.GlobalizationInterop.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity);
if (!result)
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
return String.Empty;
}
return StringBuilderCache.GetStringAndRelease(sb);
}
[SecuritySafeCritical]
private int GetLocaleInfo(LocaleNumberData type)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
switch (type)
{
case LocaleNumberData.CalendarType:
// returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
return 0;
}
int value = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
if (!result)
{
// Failed, just use 0
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
}
return value;
}
[SecuritySafeCritical]
private int[] GetLocaleInfo(LocaleGroupingData type)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
Contract.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
{
return new int[] { primaryGroupingSize };
}
return new int[] { primaryGroupingSize, secondaryGroupingSize };
}
private string GetTimeFormatString()
{
return GetTimeFormatString(false);
}
[SecuritySafeCritical]
private string GetTimeFormatString(bool shortFormat)
{
Contract.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
bool result = Interop.GlobalizationInterop.GetLocaleTimeFormat(_sWindowsName, shortFormat, sb, sb.Capacity);
if (!result)
{
// Failed, just use empty string
StringBuilderCache.Release(sb);
Contract.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return String.Empty;
}
return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb));
}
private int GetFirstDayOfWeek()
{
return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek);
}
private String[] GetTimeFormats()
{
string format = GetTimeFormatString(false);
return new string[] { format };
}
private String[] GetShortTimeFormats()
{
string format = GetTimeFormatString(true);
return new string[] { format };
}
private static CultureData GetCultureDataFromRegionName(String regionName)
{
// no support to lookup by region name, other than the hard-coded list in CultureData
return null;
}
private static string GetLanguageDisplayName(string cultureName)
{
return new CultureInfo(cultureName).m_cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
}
private static string GetRegionDisplayName(string isoCountryCode)
{
// use the fallback which is to return NativeName
return null;
}
private static CultureInfo GetUserDefaultCulture()
{
return CultureInfo.GetUserDefaultCulture();
}
private static string ConvertIcuTimeFormatString(string icuFormatString)
{
StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
bool amPmAdded = false;
for (int i = 0; i < icuFormatString.Length; i++)
{
switch(icuFormatString[i])
{
case ':':
case '.':
case 'H':
case 'h':
case 'm':
case 's':
sb.Append(icuFormatString[i]);
break;
case ' ':
case '\u00A0':
// Convert nonbreaking spaces into regular spaces
sb.Append(' ');
break;
case 'a': // AM/PM
if (!amPmAdded)
{
amPmAdded = true;
sb.Append("tt");
}
break;
}
}
return StringBuilderCache.GetStringAndRelease(sb);
}
private static string LCIDToLocaleName(int culture)
{
return LocaleData.LCIDToLocaleName(culture);
}
private static int LocaleNameToLCID(string cultureName)
{
int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid);
return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
}
private static int GetAnsiCodePage(string cultureName)
{
int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage);
return ansiCodePage == -1 ? CultureData.Invariant.IDEFAULTANSICODEPAGE : ansiCodePage;
}
private static int GetOemCodePage(string cultureName)
{
int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage);
return oemCodePage == -1 ? CultureData.Invariant.IDEFAULTOEMCODEPAGE : oemCodePage;
}
private static int GetMacCodePage(string cultureName)
{
int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage);
return macCodePage == -1 ? CultureData.Invariant.IDEFAULTMACCODEPAGE : macCodePage;
}
private static int GetEbcdicCodePage(string cultureName)
{
int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage);
return ebcdicCodePage == -1 ? CultureData.Invariant.IDEFAULTEBCDICCODEPAGE : ebcdicCodePage;
}
private static int GetGeoId(string cultureName)
{
int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId);
return geoId == -1 ? CultureData.Invariant.IGEOID : geoId;
}
private static int GetDigitSubstitution(string cultureName)
{
int digitSubstitution = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.DigitSubstitution);
return digitSubstitution == -1 ? (int) DigitShapes.None : digitSubstitution;
}
private static string GetThreeLetterWindowsLanguageName(string cultureName)
{
string langName = LocaleData.GetThreeLetterWindowsLangageName(cultureName);
return langName == null ? "ZZZ" /* default lang name */ : langName;
}
private static CultureInfo[] EnumCultures(CultureTypes types)
{
if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0)
{
return Array.Empty<CultureInfo>();
}
int bufferLength = Interop.GlobalizationInterop.GetLocales(null, 0);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
Char [] chars = new Char[bufferLength];
bufferLength = Interop.GlobalizationInterop.GetLocales(chars, bufferLength);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0;
bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0;
List<CultureInfo> list = new List<CultureInfo>();
if (enumNeutrals)
{
list.Add(CultureInfo.InvariantCulture);
}
int index = 0;
while (index < bufferLength)
{
int length = (int) chars[index++];
if (index + length <= bufferLength)
{
CultureInfo ci = CultureInfo.GetCultureInfo(new String(chars, index, length));
if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture))
{
list.Add(ci);
}
}
index += length;
}
return list.ToArray();
}
}
}
| |
//#define Trace
// ParallelDeflateOutputStream.cs
// ------------------------------------------------------------------
//
// A DeflateStream that does compression only, it uses a
// divide-and-conquer approach with multiple threads to exploit multiple
// CPUs for the DEFLATE computation.
//
// last saved: <2011-July-31 14:49:40>
//
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 by Dino Chiesa
// All rights reserved!
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading;
using Ionic.Zlib;
using System.IO;
#pragma warning disable
namespace Ionic.Zlib
{
internal class WorkItem
{
public byte[] buffer;
public byte[] compressed;
public int crc;
public int index;
public int ordinal;
public int inputBytesAvailable;
public int compressedBytesAvailable;
public ZlibCodec compressor;
public WorkItem(int size,
Ionic.Zlib.CompressionLevel compressLevel,
CompressionStrategy strategy,
int ix)
{
this.buffer= new byte[size];
// alloc 5 bytes overhead for every block (margin of safety= 2)
int n = size + ((size / 32768)+1) * 5 * 2;
this.compressed = new byte[n];
this.compressor = new ZlibCodec();
this.compressor.InitializeDeflate(compressLevel, false);
this.compressor.OutputBuffer = this.compressed;
this.compressor.InputBuffer = this.buffer;
this.index = ix;
}
}
/// <summary>
/// A class for compressing streams using the
/// Deflate algorithm with multiple threads.
/// </summary>
///
/// <remarks>
/// <para>
/// This class performs DEFLATE compression through writing. For
/// more information on the Deflate algorithm, see IETF RFC 1951,
/// "DEFLATE Compressed Data Format Specification version 1.3."
/// </para>
///
/// <para>
/// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>, except
/// that this class is for compression only, and this implementation uses an
/// approach that employs multiple worker threads to perform the DEFLATE. On
/// a multi-cpu or multi-core computer, the performance of this class can be
/// significantly higher than the single-threaded DeflateStream, particularly
/// for larger streams. How large? Anything over 10mb is a good candidate
/// for parallel compression.
/// </para>
///
/// <para>
/// The tradeoff is that this class uses more memory and more CPU than the
/// vanilla DeflateStream, and also is less efficient as a compressor. For
/// large files the size of the compressed data stream can be less than 1%
/// larger than the size of a compressed data stream from the vanialla
/// DeflateStream. For smaller files the difference can be larger. The
/// difference will also be larger if you set the BufferSize to be lower than
/// the default value. Your mileage may vary. Finally, for small files, the
/// ParallelDeflateOutputStream can be much slower than the vanilla
/// DeflateStream, because of the overhead associated to using the thread
/// pool.
/// </para>
///
/// </remarks>
/// <seealso cref="Ionic.Zlib.DeflateStream" />
public class ParallelDeflateOutputStream : System.IO.Stream
{
private static readonly int IO_BUFFER_SIZE_DEFAULT = 64 * 1024; // 128k
private static readonly int BufferPairsPerCore = 4;
private System.Collections.Generic.List<WorkItem> _pool;
private bool _leaveOpen;
private bool emitting;
private System.IO.Stream _outStream;
private int _maxBufferPairs;
private int _bufferSize = IO_BUFFER_SIZE_DEFAULT;
private AutoResetEvent _newlyCompressedBlob;
//private ManualResetEvent _writingDone;
//private ManualResetEvent _sessionReset;
private object _outputLock = new object();
private bool _isClosed;
private bool _firstWriteDone;
private int _currentlyFilling;
private int _lastFilled;
private int _lastWritten;
private int _latestCompressed;
private int _Crc32;
private Ionic.Crc.CRC32 _runningCrc;
private object _latestLock = new object();
private System.Collections.Generic.Queue<int> _toWrite;
private System.Collections.Generic.Queue<int> _toFill;
private Int64 _totalBytesProcessed;
private Ionic.Zlib.CompressionLevel _compressLevel;
private volatile Exception _pendingException;
private bool _handlingException;
private object _eLock = new Object(); // protects _pendingException
// This bitfield is used only when Trace is defined.
//private TraceBits _DesiredTrace = TraceBits.Write | TraceBits.WriteBegin |
//TraceBits.WriteDone | TraceBits.Lifecycle | TraceBits.Fill | TraceBits.Flush |
//TraceBits.Session;
//private TraceBits _DesiredTrace = TraceBits.WriteBegin | TraceBits.WriteDone | TraceBits.Synch | TraceBits.Lifecycle | TraceBits.Session ;
private TraceBits _DesiredTrace =
TraceBits.Session |
TraceBits.Compress |
TraceBits.WriteTake |
TraceBits.WriteEnter |
TraceBits.EmitEnter |
TraceBits.EmitDone |
TraceBits.EmitLock |
TraceBits.EmitSkip |
TraceBits.EmitBegin;
/// <summary>
/// Create a ParallelDeflateOutputStream.
/// </summary>
/// <remarks>
///
/// <para>
/// This stream compresses data written into it via the DEFLATE
/// algorithm (see RFC 1951), and writes out the compressed byte stream.
/// </para>
///
/// <para>
/// The instance will use the default compression level, the default
/// buffer sizes and the default number of threads and buffers per
/// thread.
/// </para>
///
/// <para>
/// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>,
/// except that this implementation uses an approach that employs
/// multiple worker threads to perform the DEFLATE. On a multi-cpu or
/// multi-core computer, the performance of this class can be
/// significantly higher than the single-threaded DeflateStream,
/// particularly for larger streams. How large? Anything over 10mb is
/// a good candidate for parallel compression.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a ParallelDeflateOutputStream to compress
/// data. It reads a file, compresses it, and writes the compressed data to
/// a second, output file.
///
/// <code>
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// String outputFile = fileToCompress + ".compressed";
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new ParallelDeflateOutputStream(raw))
/// {
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New ParallelDeflateOutputStream(raw)
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to which compressed data will be written.</param>
public ParallelDeflateOutputStream(System.IO.Stream stream)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, false)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream using the specified CompressionLevel.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level)
: this(stream, level, CompressionStrategy.Default, false)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
/// when the ParallelDeflateOutputStream is closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream, bool leaveOpen)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
/// when the ParallelDeflateOutputStream is closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level, bool leaveOpen)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream using the specified
/// CompressionLevel and CompressionStrategy, and specifying whether to
/// leave the captive stream open when the ParallelDeflateOutputStream is
/// closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
/// <param name="strategy">
/// By tweaking this parameter, you may be able to optimize the compression for
/// data with particular characteristics.
/// </param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream,
CompressionLevel level,
CompressionStrategy strategy,
bool leaveOpen)
{
TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "-------------------------------------------------------");
TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "Create {0:X8}", this.GetHashCode());
_outStream = stream;
_compressLevel= level;
Strategy = strategy;
_leaveOpen = leaveOpen;
this.MaxBufferPairs = 16; // default
}
/// <summary>
/// The ZLIB strategy to be used during compression.
/// </summary>
///
public CompressionStrategy Strategy
{
get;
private set;
}
/// <summary>
/// The maximum number of buffer pairs to use.
/// </summary>
///
/// <remarks>
/// <para>
/// This property sets an upper limit on the number of memory buffer
/// pairs to create. The implementation of this stream allocates
/// multiple buffers to facilitate parallel compression. As each buffer
/// fills up, this stream uses <see
/// cref="System.Threading.ThreadPool.QueueUserWorkItem(WaitCallback)">
/// ThreadPool.QueueUserWorkItem()</see>
/// to compress those buffers in a background threadpool thread. After a
/// buffer is compressed, it is re-ordered and written to the output
/// stream.
/// </para>
///
/// <para>
/// A higher number of buffer pairs enables a higher degree of
/// parallelism, which tends to increase the speed of compression on
/// multi-cpu computers. On the other hand, a higher number of buffer
/// pairs also implies a larger memory consumption, more active worker
/// threads, and a higher cpu utilization for any compression. This
/// property enables the application to limit its memory consumption and
/// CPU utilization behavior depending on requirements.
/// </para>
///
/// <para>
/// For each compression "task" that occurs in parallel, there are 2
/// buffers allocated: one for input and one for output. This property
/// sets a limit for the number of pairs. The total amount of storage
/// space allocated for buffering will then be (N*S*2), where N is the
/// number of buffer pairs, S is the size of each buffer (<see
/// cref="BufferSize"/>). By default, DotNetZip allocates 4 buffer
/// pairs per CPU core, so if your machine has 4 cores, and you retain
/// the default buffer size of 128k, then the
/// ParallelDeflateOutputStream will use 4 * 4 * 2 * 128kb of buffer
/// memory in total, or 4mb, in blocks of 128kb. If you then set this
/// property to 8, then the number will be 8 * 2 * 128kb of buffer
/// memory, or 2mb.
/// </para>
///
/// <para>
/// CPU utilization will also go up with additional buffers, because a
/// larger number of buffer pairs allows a larger number of background
/// threads to compress in parallel. If you find that parallel
/// compression is consuming too much memory or CPU, you can adjust this
/// value downward.
/// </para>
///
/// <para>
/// The default value is 16. Different values may deliver better or
/// worse results, depending on your priorities and the dynamic
/// performance characteristics of your storage and compute resources.
/// </para>
///
/// <para>
/// This property is not the number of buffer pairs to use; it is an
/// upper limit. An illustration: Suppose you have an application that
/// uses the default value of this property (which is 16), and it runs
/// on a machine with 2 CPU cores. In that case, DotNetZip will allocate
/// 4 buffer pairs per CPU core, for a total of 8 pairs. The upper
/// limit specified by this property has no effect.
/// </para>
///
/// <para>
/// The application can set this value at any time, but it is effective
/// only before the first call to Write(), which is when the buffers are
/// allocated.
/// </para>
/// </remarks>
public int MaxBufferPairs
{
get
{
return _maxBufferPairs;
}
set
{
if (value < 4)
throw new ArgumentException("MaxBufferPairs",
"Value must be 4 or greater.");
_maxBufferPairs = value;
}
}
/// <summary>
/// The size of the buffers used by the compressor threads.
/// </summary>
/// <remarks>
///
/// <para>
/// The default buffer size is 128k. The application can set this value
/// at any time, but it is effective only before the first Write().
/// </para>
///
/// <para>
/// Larger buffer sizes implies larger memory consumption but allows
/// more efficient compression. Using smaller buffer sizes consumes less
/// memory but may result in less effective compression. For example,
/// using the default buffer size of 128k, the compression delivered is
/// within 1% of the compression delivered by the single-threaded <see
/// cref="Ionic.Zlib.DeflateStream"/>. On the other hand, using a
/// BufferSize of 8k can result in a compressed data stream that is 5%
/// larger than that delivered by the single-threaded
/// <c>DeflateStream</c>. Excessively small buffer sizes can also cause
/// the speed of the ParallelDeflateOutputStream to drop, because of
/// larger thread scheduling overhead dealing with many many small
/// buffers.
/// </para>
///
/// <para>
/// The total amount of storage space allocated for buffering will be
/// (N*S*2), where N is the number of buffer pairs, and S is the size of
/// each buffer (this property). There are 2 buffers used by the
/// compressor, one for input and one for output. By default, DotNetZip
/// allocates 4 buffer pairs per CPU core, so if your machine has 4
/// cores, then the number of buffer pairs used will be 16. If you
/// accept the default value of this property, 128k, then the
/// ParallelDeflateOutputStream will use 16 * 2 * 128kb of buffer memory
/// in total, or 4mb, in blocks of 128kb. If you set this property to
/// 64kb, then the number will be 16 * 2 * 64kb of buffer memory, or
/// 2mb.
/// </para>
///
/// </remarks>
public int BufferSize
{
get { return _bufferSize;}
set
{
if (value < 1024)
throw new ArgumentOutOfRangeException("BufferSize",
"BufferSize must be greater than 1024 bytes");
_bufferSize = value;
}
}
/// <summary>
/// The CRC32 for the data that was written out, prior to compression.
/// </summary>
/// <remarks>
/// This value is meaningful only after a call to Close().
/// </remarks>
public int Crc32 { get { return _Crc32; } }
/// <summary>
/// The total number of uncompressed bytes processed by the ParallelDeflateOutputStream.
/// </summary>
/// <remarks>
/// This value is meaningful only after a call to Close().
/// </remarks>
public Int64 BytesProcessed { get { return _totalBytesProcessed; } }
private void _InitializePoolOfWorkItems()
{
_toWrite = new Queue<int>();
_toFill = new Queue<int>();
_pool = new System.Collections.Generic.List<WorkItem>();
int nTasks = BufferPairsPerCore * Environment.ProcessorCount;
nTasks = Math.Min(nTasks, _maxBufferPairs);
for(int i=0; i < nTasks; i++)
{
_pool.Add(new WorkItem(_bufferSize, _compressLevel, Strategy, i));
_toFill.Enqueue(i);
}
_newlyCompressedBlob = new AutoResetEvent(false);
_runningCrc = new Ionic.Crc.CRC32();
_currentlyFilling = -1;
_lastFilled = -1;
_lastWritten = -1;
_latestCompressed = -1;
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// To use the ParallelDeflateOutputStream to compress data, create a
/// ParallelDeflateOutputStream with CompressionMode.Compress, passing a
/// writable output stream. Then call Write() on that
/// ParallelDeflateOutputStream, providing uncompressed data as input. The
/// data sent to the output stream will be the compressed form of the data
/// written.
/// </para>
///
/// <para>
/// To decompress data, use the <see cref="Ionic.Zlib.DeflateStream"/> class.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
bool mustWait = false;
// This method does this:
// 0. handles any pending exceptions
// 1. write any buffers that are ready to be written,
// 2. fills a work buffer; when full, flip state to 'Filled',
// 3. if more data to be written, goto step 1
if (_isClosed)
throw new InvalidOperationException();
// dispense any exceptions that occurred on the BG threads
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (count == 0) return;
if (!_firstWriteDone)
{
// Want to do this on first Write, first session, and not in the
// constructor. We want to allow MaxBufferPairs to
// change after construction, but before first Write.
_InitializePoolOfWorkItems();
_firstWriteDone = true;
}
do
{
// may need to make buffers available
EmitPendingBuffers(false, mustWait);
mustWait = false;
// use current buffer, or get a new buffer to fill
int ix = -1;
if (_currentlyFilling >= 0)
{
ix = _currentlyFilling;
TraceOutput(TraceBits.WriteTake,
"Write notake wi({0}) lf({1})",
ix,
_lastFilled);
}
else
{
TraceOutput(TraceBits.WriteTake, "Write take?");
if (_toFill.Count == 0)
{
// no available buffers, so... need to emit
// compressed buffers.
mustWait = true;
continue;
}
ix = _toFill.Dequeue();
TraceOutput(TraceBits.WriteTake,
"Write take wi({0}) lf({1})",
ix,
_lastFilled);
++_lastFilled; // TODO: consider rollover?
}
WorkItem workitem = _pool[ix];
int limit = ((workitem.buffer.Length - workitem.inputBytesAvailable) > count)
? count
: (workitem.buffer.Length - workitem.inputBytesAvailable);
workitem.ordinal = _lastFilled;
TraceOutput(TraceBits.Write,
"Write lock wi({0}) ord({1}) iba({2})",
workitem.index,
workitem.ordinal,
workitem.inputBytesAvailable
);
// copy from the provided buffer to our workitem, starting at
// the tail end of whatever data we might have in there currently.
Buffer.BlockCopy(buffer,
offset,
workitem.buffer,
workitem.inputBytesAvailable,
limit);
count -= limit;
offset += limit;
workitem.inputBytesAvailable += limit;
if (workitem.inputBytesAvailable == workitem.buffer.Length)
{
// No need for interlocked.increment: the Write()
// method is documented as not multi-thread safe, so
// we can assume Write() calls come in from only one
// thread.
TraceOutput(TraceBits.Write,
"Write QUWI wi({0}) ord({1}) iba({2}) nf({3})",
workitem.index,
workitem.ordinal,
workitem.inputBytesAvailable );
if (!ThreadPool.QueueUserWorkItem( _DeflateOne, workitem ))
throw new Exception("Cannot enqueue workitem");
_currentlyFilling = -1; // will get a new buffer next time
}
else
_currentlyFilling = ix;
if (count > 0)
TraceOutput(TraceBits.WriteEnter, "Write more");
}
while (count > 0); // until no more to write
TraceOutput(TraceBits.WriteEnter, "Write exit");
return;
}
private void _FlushFinish()
{
// After writing a series of compressed buffers, each one closed
// with Flush.Sync, we now write the final one as Flush.Finish,
// and then stop.
byte[] buffer = new byte[128];
var compressor = new ZlibCodec();
int rc = compressor.InitializeDeflate(_compressLevel, false);
compressor.InputBuffer = null;
compressor.NextIn = 0;
compressor.AvailableBytesIn = 0;
compressor.OutputBuffer = buffer;
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
{
TraceOutput(TraceBits.EmitBegin,
"Emit begin flush bytes({0})",
buffer.Length - compressor.AvailableBytesOut);
_outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
TraceOutput(TraceBits.EmitDone,
"Emit done flush");
}
compressor.EndDeflate();
_Crc32 = _runningCrc.Crc32Result;
}
private void _Flush(bool lastInput)
{
if (_isClosed)
throw new InvalidOperationException();
if (emitting) return;
// compress any partial buffer
if (_currentlyFilling >= 0)
{
WorkItem workitem = _pool[_currentlyFilling];
_DeflateOne(workitem);
_currentlyFilling = -1; // get a new buffer next Write()
}
if (lastInput)
{
EmitPendingBuffers(true, false);
_FlushFinish();
}
else
{
EmitPendingBuffers(false, false);
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (_handlingException)
return;
_Flush(false);
}
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// You must call Close on the stream to guarantee that all of the data written in has
/// been compressed, and the compressed data has been written out.
/// </remarks>
public override void Close()
{
TraceOutput(TraceBits.Session, "Close {0:X8}", this.GetHashCode());
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (_handlingException)
return;
if (_isClosed) return;
_Flush(true);
if (!_leaveOpen)
_outStream.Close();
_isClosed= true;
}
// workitem 10030 - implement a new Dispose method
/// <summary>Dispose the object</summary>
/// <remarks>
/// <para>
/// Because ParallelDeflateOutputStream is IDisposable, the
/// application must call this method when finished using the instance.
/// </para>
/// <para>
/// This method is generally called implicitly upon exit from
/// a <c>using</c> scope in C# (<c>Using</c> in VB).
/// </para>
/// </remarks>
new public void Dispose()
{
TraceOutput(TraceBits.Lifecycle, "Dispose {0:X8}", this.GetHashCode());
Close();
_pool = null;
Dispose(true);
}
/// <summary>The Dispose method</summary>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
/// <summary>
/// Resets the stream for use with another stream.
/// </summary>
/// <remarks>
/// Because the ParallelDeflateOutputStream is expensive to create, it
/// has been designed so that it can be recycled and re-used. You have
/// to call Close() on the stream first, then you can call Reset() on
/// it, to use it again on another stream.
/// </remarks>
///
/// <param name="stream">
/// The new output stream for this era.
/// </param>
///
/// <example>
/// <code>
/// ParallelDeflateOutputStream deflater = null;
/// foreach (var inputFile in listOfFiles)
/// {
/// string outputFile = inputFile + ".compressed";
/// using (System.IO.Stream input = System.IO.File.OpenRead(inputFile))
/// {
/// using (var outStream = System.IO.File.Create(outputFile))
/// {
/// if (deflater == null)
/// deflater = new ParallelDeflateOutputStream(outStream,
/// CompressionLevel.Best,
/// CompressionStrategy.Default,
/// true);
/// deflater.Reset(outStream);
///
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// deflater.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public void Reset(Stream stream)
{
TraceOutput(TraceBits.Session, "-------------------------------------------------------");
TraceOutput(TraceBits.Session, "Reset {0:X8} firstDone({1})", this.GetHashCode(), _firstWriteDone);
if (!_firstWriteDone) return;
// reset all status
_toWrite.Clear();
_toFill.Clear();
foreach (var workitem in _pool)
{
_toFill.Enqueue(workitem.index);
workitem.ordinal = -1;
}
_firstWriteDone = false;
_totalBytesProcessed = 0L;
_runningCrc = new Ionic.Crc.CRC32();
_isClosed= false;
_currentlyFilling = -1;
_lastFilled = -1;
_lastWritten = -1;
_latestCompressed = -1;
_outStream = stream;
}
private void EmitPendingBuffers(bool doAll, bool mustWait)
{
// When combining parallel deflation with a ZipSegmentedStream, it's
// possible for the ZSS to throw from within this method. In that
// case, Close/Dispose will be called on this stream, if this stream
// is employed within a using or try/finally pair as required. But
// this stream is unaware of the pending exception, so the Close()
// method invokes this method AGAIN. This can lead to a deadlock.
// Therefore, failfast if re-entering.
if (emitting) return;
emitting = true;
if (doAll || mustWait)
_newlyCompressedBlob.WaitOne();
do
{
int firstSkip = -1;
int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0);
int nextToWrite = -1;
do
{
if (Monitor.TryEnter(_toWrite, millisecondsToWait))
{
nextToWrite = -1;
try
{
if (_toWrite.Count > 0)
nextToWrite = _toWrite.Dequeue();
}
finally
{
Monitor.Exit(_toWrite);
}
if (nextToWrite >= 0)
{
WorkItem workitem = _pool[nextToWrite];
if (workitem.ordinal != _lastWritten + 1)
{
// out of order. requeue and try again.
TraceOutput(TraceBits.EmitSkip,
"Emit skip wi({0}) ord({1}) lw({2}) fs({3})",
workitem.index,
workitem.ordinal,
_lastWritten,
firstSkip);
lock(_toWrite)
{
_toWrite.Enqueue(nextToWrite);
}
if (firstSkip == nextToWrite)
{
// We went around the list once.
// None of the items in the list is the one we want.
// Now wait for a compressor to signal again.
_newlyCompressedBlob.WaitOne();
firstSkip = -1;
}
else if (firstSkip == -1)
firstSkip = nextToWrite;
continue;
}
firstSkip = -1;
TraceOutput(TraceBits.EmitBegin,
"Emit begin wi({0}) ord({1}) cba({2})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable);
_outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
_runningCrc.Combine(workitem.crc, workitem.inputBytesAvailable);
_totalBytesProcessed += workitem.inputBytesAvailable;
workitem.inputBytesAvailable = 0;
TraceOutput(TraceBits.EmitDone,
"Emit done wi({0}) ord({1}) cba({2}) mtw({3})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable,
millisecondsToWait);
_lastWritten = workitem.ordinal;
_toFill.Enqueue(workitem.index);
// don't wait next time through
if (millisecondsToWait == -1) millisecondsToWait = 0;
}
}
else
nextToWrite = -1;
} while (nextToWrite >= 0);
} while (doAll && (_lastWritten != _latestCompressed));
emitting = false;
}
#if OLD
private void _PerpetualWriterMethod(object state)
{
TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod START");
try
{
do
{
// wait for the next session
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(begin) PWM");
_sessionReset.WaitOne();
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(done) PWM");
if (_isDisposed) break;
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.Reset() PWM");
_sessionReset.Reset();
// repeatedly write buffers as they become ready
WorkItem workitem = null;
Ionic.Zlib.CRC32 c= new Ionic.Zlib.CRC32();
do
{
workitem = _pool[_nextToWrite % _pc];
lock(workitem)
{
if (_noMoreInputForThisSegment)
TraceOutput(TraceBits.Write,
"Write drain wi({0}) stat({1}) canuse({2}) cba({3})",
workitem.index,
workitem.status,
(workitem.status == (int)WorkItem.Status.Compressed),
workitem.compressedBytesAvailable);
do
{
if (workitem.status == (int)WorkItem.Status.Compressed)
{
TraceOutput(TraceBits.WriteBegin,
"Write begin wi({0}) stat({1}) cba({2})",
workitem.index,
workitem.status,
workitem.compressedBytesAvailable);
workitem.status = (int)WorkItem.Status.Writing;
_outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
c.Combine(workitem.crc, workitem.inputBytesAvailable);
_totalBytesProcessed += workitem.inputBytesAvailable;
_nextToWrite++;
workitem.inputBytesAvailable= 0;
workitem.status = (int)WorkItem.Status.Done;
TraceOutput(TraceBits.WriteDone,
"Write done wi({0}) stat({1}) cba({2})",
workitem.index,
workitem.status,
workitem.compressedBytesAvailable);
Monitor.Pulse(workitem);
break;
}
else
{
int wcycles = 0;
// I've locked a workitem I cannot use.
// Therefore, wake someone else up, and then release the lock.
while (workitem.status != (int)WorkItem.Status.Compressed)
{
TraceOutput(TraceBits.WriteWait,
"Write waiting wi({0}) stat({1}) nw({2}) nf({3}) nomore({4})",
workitem.index,
workitem.status,
_nextToWrite, _nextToFill,
_noMoreInputForThisSegment );
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
wcycles++;
// wake up someone else
Monitor.Pulse(workitem);
// release and wait
Monitor.Wait(workitem);
if (workitem.status == (int)WorkItem.Status.Compressed)
TraceOutput(TraceBits.WriteWait,
"Write A-OK wi({0}) stat({1}) iba({2}) cba({3}) cyc({4})",
workitem.index,
workitem.status,
workitem.inputBytesAvailable,
workitem.compressedBytesAvailable,
wcycles);
}
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
}
}
while (true);
}
if (_noMoreInputForThisSegment)
TraceOutput(TraceBits.Write,
"Write nomore nw({0}) nf({1}) break({2})",
_nextToWrite, _nextToFill, (_nextToWrite == _nextToFill));
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
} while (true);
// Finish:
// After writing a series of buffers, closing each one with
// Flush.Sync, we now write the final one as Flush.Finish, and
// then stop.
byte[] buffer = new byte[128];
ZlibCodec compressor = new ZlibCodec();
int rc = compressor.InitializeDeflate(_compressLevel, false);
compressor.InputBuffer = null;
compressor.NextIn = 0;
compressor.AvailableBytesIn = 0;
compressor.OutputBuffer = buffer;
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
{
TraceOutput(TraceBits.WriteBegin,
"Write begin flush bytes({0})",
buffer.Length - compressor.AvailableBytesOut);
_outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
TraceOutput(TraceBits.WriteBegin,
"Write done flush");
}
compressor.EndDeflate();
_Crc32 = c.Crc32Result;
// signal that writing is complete:
TraceOutput(TraceBits.Synch, "Synch _writingDone.Set() PWM");
_writingDone.Set();
}
while (true);
}
catch (System.Exception exc1)
{
lock(_eLock)
{
// expose the exception to the main thread
if (_pendingException!=null)
_pendingException = exc1;
}
}
TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod FINIS");
}
#endif
private void _DeflateOne(Object wi)
{
// compress one buffer
WorkItem workitem = (WorkItem) wi;
try
{
int myItem = workitem.index;
Ionic.Crc.CRC32 crc = new Ionic.Crc.CRC32();
// calc CRC on the buffer
crc.SlurpBlock(workitem.buffer, 0, workitem.inputBytesAvailable);
// deflate it
DeflateOneSegment(workitem);
// update status
workitem.crc = crc.Crc32Result;
TraceOutput(TraceBits.Compress,
"Compress wi({0}) ord({1}) len({2})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable
);
lock(_latestLock)
{
if (workitem.ordinal > _latestCompressed)
_latestCompressed = workitem.ordinal;
}
lock (_toWrite)
{
_toWrite.Enqueue(workitem.index);
}
_newlyCompressedBlob.Set();
}
catch (System.Exception exc1)
{
lock(_eLock)
{
// expose the exception to the main thread
if (_pendingException!=null)
_pendingException = exc1;
}
}
}
private bool DeflateOneSegment(WorkItem workitem)
{
ZlibCodec compressor = workitem.compressor;
int rc= 0;
compressor.ResetDeflate();
compressor.NextIn = 0;
compressor.AvailableBytesIn = workitem.inputBytesAvailable;
// step 1: deflate the buffer
compressor.NextOut = 0;
compressor.AvailableBytesOut = workitem.compressed.Length;
do
{
compressor.Deflate(FlushType.None);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
// step 2: flush (sync)
rc = compressor.Deflate(FlushType.Sync);
workitem.compressedBytesAvailable= (int) compressor.TotalBytesOut;
return true;
}
[System.Diagnostics.ConditionalAttribute("Trace")]
private void TraceOutput(TraceBits bits, string format, params object[] varParams)
{
if ((bits & _DesiredTrace) != 0)
{
lock(_outputLock)
{
#if CONSOLE
int tid = Thread.CurrentThread.GetHashCode();
#if !SILVERLIGHT
Console.ForegroundColor = (ConsoleColor) (tid % 8 + 8);
#endif
Console.Write("{0:000} PDOS ", tid);
Console.WriteLine(format, varParams);
#if !SILVERLIGHT
Console.ResetColor();
#endif
#endif
}
}
}
// used only when Trace is defined
[Flags]
enum TraceBits : uint
{
None = 0,
NotUsed1 = 1,
EmitLock = 2,
EmitEnter = 4, // enter _EmitPending
EmitBegin = 8, // begin to write out
EmitDone = 16, // done writing out
EmitSkip = 32, // writer skipping a workitem
EmitAll = 58, // All Emit flags
Flush = 64,
Lifecycle = 128, // constructor/disposer
Session = 256, // Close/Reset
Synch = 512, // thread synchronization
Instance = 1024, // instance settings
Compress = 2048, // compress task
Write = 4096, // filling buffers, when caller invokes Write()
WriteEnter = 8192, // upon entry to Write()
WriteTake = 16384, // on _toFill.Take()
All = 0xffffffff,
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports Read operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanRead
{
get {return false;}
}
/// <summary>
/// Indicates whether the stream supports Write operations.
/// </summary>
/// <remarks>
/// Returns true if the provided stream is writable.
/// </remarks>
public override bool CanWrite
{
get { return _outStream.CanWrite; }
}
/// <summary>
/// Reading this property always throws a NotSupportedException.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Returns the current position of the output stream.
/// </summary>
/// <remarks>
/// <para>
/// Because the output gets written by a background thread,
/// the value may change asynchronously. Setting this
/// property always throws a NotSupportedException.
/// </para>
/// </remarks>
public override long Position
{
get { return _outStream.Position; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="buffer">
/// The buffer into which data would be read, IF THIS METHOD
/// ACTUALLY DID ANYTHING.
/// </param>
/// <param name="offset">
/// The offset within that data array at which to insert the
/// data that is read, IF THIS METHOD ACTUALLY DID
/// ANYTHING.
/// </param>
/// <param name="count">
/// The number of bytes to write, IF THIS METHOD ACTUALLY DID
/// ANYTHING.
/// </param>
/// <returns>nothing.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="offset">
/// The offset to seek to....
/// IF THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <param name="origin">
/// The reference specifying how to apply the offset.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <returns>nothing. It always throws.</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="value">
/// The new value for the stream length.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace StacksOfWax.VersionedApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Text;
using System.Collections;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Static methods used in creating messages
/// </summary>
public class MsgUtils
{
/// <summary>
/// Static string used when strings are clipped
/// </summary>
private static readonly string ELLIPSIS = "...";
/// <summary>
/// Returns the representation of a type as used in NUnitLite.
/// This is the same as Type.ToString() except for arrays,
/// which are displayed with their declared sizes.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string GetTypeRepresentation(object obj)
{
Array array = obj as Array;
if ( array == null )
return string.Format( "<{0}>", obj.GetType() );
StringBuilder sb = new StringBuilder();
Type elementType = array.GetType();
int nest = 0;
while (elementType.IsArray)
{
elementType = elementType.GetElementType();
++nest;
}
sb.Append(elementType.ToString());
sb.Append('[');
for (int r = 0; r < array.Rank; r++)
{
if (r > 0) sb.Append(',');
sb.Append(array.GetLength(r));
}
sb.Append(']');
while (--nest > 0)
sb.Append("[]");
return string.Format( "<{0}>", sb.ToString() );
}
/// <summary>
/// Converts any control characters in a string
/// to their escaped representation.
/// </summary>
/// <param name="s">The string to be converted</param>
/// <returns>The converted string</returns>
public static string EscapeControlChars(string s)
{
if (s != null)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
switch (c)
{
//case '\'':
// sb.Append("\\\'");
// break;
//case '\"':
// sb.Append("\\\"");
// break;
case '\\':
sb.Append("\\\\");
break;
case '\0':
sb.Append("\\0");
break;
case '\a':
sb.Append("\\a");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\v':
sb.Append("\\v");
break;
case '\x0085':
case '\x2028':
case '\x2029':
sb.AppendFormat("\\x{0:X4}", (int)c);
break;
default:
sb.Append(c);
break;
}
}
s = sb.ToString();
}
return s;
}
/// <summary>
/// Return the a string representation for a set of indices into an array
/// </summary>
/// <param name="indices">Array of indices for which a string is needed</param>
public static string GetArrayIndicesAsString(int[] indices)
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
for (int r = 0; r < indices.Length; r++)
{
if (r > 0) sb.Append(',');
sb.Append(indices[r].ToString());
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// Get an array of indices representing the point in a collection or
/// array corresponding to a single int index into the collection.
/// </summary>
/// <param name="collection">The collection to which the indices apply</param>
/// <param name="index">Index in the collection</param>
/// <returns>Array of indices</returns>
public static int[] GetArrayIndicesFromCollectionIndex(ICollection collection, int index)
{
Array array = collection as Array;
int rank = array == null ? 1 : array.Rank;
int[] result = new int[rank];
for (int r = rank; --r > 0; )
{
int l = array.GetLength(r);
result[r] = index % l;
index /= l;
}
result[0] = index;
return result;
}
/// <summary>
/// Clip a string to a given length, starting at a particular offset, returning the clipped
/// string with ellipses representing the removed parts
/// </summary>
/// <param name="s">The string to be clipped</param>
/// <param name="maxStringLength">The maximum permitted length of the result string</param>
/// <param name="clipStart">The point at which to start clipping</param>
/// <returns>The clipped string</returns>
public static string ClipString(string s, int maxStringLength, int clipStart)
{
int clipLength = maxStringLength;
StringBuilder sb = new StringBuilder();
if (clipStart > 0)
{
clipLength -= ELLIPSIS.Length;
sb.Append( ELLIPSIS );
}
if (s.Length - clipStart > clipLength)
{
clipLength -= ELLIPSIS.Length;
sb.Append( s.Substring( clipStart, clipLength ));
sb.Append(ELLIPSIS);
}
else if (clipStart > 0)
sb.Append( s.Substring(clipStart));
else
sb.Append( s );
return sb.ToString();
}
/// <summary>
/// Clip the expected and actual strings in a coordinated fashion,
/// so that they may be displayed together.
/// </summary>
/// <param name="expected"></param>
/// <param name="actual"></param>
/// <param name="maxDisplayLength"></param>
/// <param name="mismatch"></param>
public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch)
{
// Case 1: Both strings fit on line
int maxStringLength = Math.Max(expected.Length, actual.Length);
if (maxStringLength <= maxDisplayLength)
return;
// Case 2: Assume that the tail of each string fits on line
int clipLength = maxDisplayLength - ELLIPSIS.Length;
int clipStart = maxStringLength - clipLength;
// Case 3: If it doesn't, center the mismatch position
if ( clipStart > mismatch )
clipStart = Math.Max( 0, mismatch - clipLength / 2 );
expected = ClipString(expected, maxDisplayLength, clipStart);
actual = ClipString(actual, maxDisplayLength, clipStart);
}
/// <summary>
/// Shows the position two strings start to differ. Comparison
/// starts at the start index.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The actual string</param>
/// <param name="istart">The index in the strings at which comparison should start</param>
/// <param name="ignoreCase">Boolean indicating whether case should be ignored</param>
/// <returns>-1 if no mismatch found, or the index where mismatch found</returns>
static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase)
{
int length = Math.Min(expected.Length, actual.Length);
string s1 = ignoreCase ? expected.ToLower() : expected;
string s2 = ignoreCase ? actual.ToLower() : actual;
for (int i = istart; i < length; i++)
{
if (s1[i] != s2[i])
return i;
}
//
// Strings have same content up to the length of the shorter string.
// Mismatch occurs because string lengths are different, so show
// that they start differing where the shortest string ends
//
if (expected.Length != actual.Length)
return length;
//
// Same strings : We shouldn't get here
//
return -1;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnPermisosGrupo class.
/// </summary>
[Serializable]
public partial class PnPermisosGrupoCollection : ActiveList<PnPermisosGrupo, PnPermisosGrupoCollection>
{
public PnPermisosGrupoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnPermisosGrupoCollection</returns>
public PnPermisosGrupoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnPermisosGrupo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_permisos_grupos table.
/// </summary>
[Serializable]
public partial class PnPermisosGrupo : ActiveRecord<PnPermisosGrupo>, IActiveRecord
{
#region .ctors and Default Settings
public PnPermisosGrupo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnPermisosGrupo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnPermisosGrupo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnPermisosGrupo(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_permisos_grupos", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdPg = new TableSchema.TableColumn(schema);
colvarIdPg.ColumnName = "id_pg";
colvarIdPg.DataType = DbType.Int32;
colvarIdPg.MaxLength = 0;
colvarIdPg.AutoIncrement = true;
colvarIdPg.IsNullable = false;
colvarIdPg.IsPrimaryKey = true;
colvarIdPg.IsForeignKey = false;
colvarIdPg.IsReadOnly = false;
colvarIdPg.DefaultSetting = @"";
colvarIdPg.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPg);
TableSchema.TableColumn colvarIdPermiso = new TableSchema.TableColumn(schema);
colvarIdPermiso.ColumnName = "id_permiso";
colvarIdPermiso.DataType = DbType.Int32;
colvarIdPermiso.MaxLength = 0;
colvarIdPermiso.AutoIncrement = false;
colvarIdPermiso.IsNullable = false;
colvarIdPermiso.IsPrimaryKey = false;
colvarIdPermiso.IsForeignKey = true;
colvarIdPermiso.IsReadOnly = false;
colvarIdPermiso.DefaultSetting = @"";
colvarIdPermiso.ForeignKeyTableName = "PN_permisos";
schema.Columns.Add(colvarIdPermiso);
TableSchema.TableColumn colvarIdGrupo = new TableSchema.TableColumn(schema);
colvarIdGrupo.ColumnName = "id_grupo";
colvarIdGrupo.DataType = DbType.Int32;
colvarIdGrupo.MaxLength = 0;
colvarIdGrupo.AutoIncrement = false;
colvarIdGrupo.IsNullable = false;
colvarIdGrupo.IsPrimaryKey = false;
colvarIdGrupo.IsForeignKey = true;
colvarIdGrupo.IsReadOnly = false;
colvarIdGrupo.DefaultSetting = @"";
colvarIdGrupo.ForeignKeyTableName = "PN_grupos";
schema.Columns.Add(colvarIdGrupo);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_permisos_grupos",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdPg")]
[Bindable(true)]
public int IdPg
{
get { return GetColumnValue<int>(Columns.IdPg); }
set { SetColumnValue(Columns.IdPg, value); }
}
[XmlAttribute("IdPermiso")]
[Bindable(true)]
public int IdPermiso
{
get { return GetColumnValue<int>(Columns.IdPermiso); }
set { SetColumnValue(Columns.IdPermiso, value); }
}
[XmlAttribute("IdGrupo")]
[Bindable(true)]
public int IdGrupo
{
get { return GetColumnValue<int>(Columns.IdGrupo); }
set { SetColumnValue(Columns.IdGrupo, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a PnPermiso ActiveRecord object related to this PnPermisosGrupo
///
/// </summary>
public DalSic.PnPermiso PnPermiso
{
get { return DalSic.PnPermiso.FetchByID(this.IdPermiso); }
set { SetColumnValue("id_permiso", value.IdPermiso); }
}
/// <summary>
/// Returns a PnGrupo ActiveRecord object related to this PnPermisosGrupo
///
/// </summary>
public DalSic.PnGrupo PnGrupo
{
get { return DalSic.PnGrupo.FetchByID(this.IdGrupo); }
set { SetColumnValue("id_grupo", value.IdGrupo); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdPermiso,int varIdGrupo)
{
PnPermisosGrupo item = new PnPermisosGrupo();
item.IdPermiso = varIdPermiso;
item.IdGrupo = varIdGrupo;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdPg,int varIdPermiso,int varIdGrupo)
{
PnPermisosGrupo item = new PnPermisosGrupo();
item.IdPg = varIdPg;
item.IdPermiso = varIdPermiso;
item.IdGrupo = varIdGrupo;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdPgColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdPermisoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdGrupoColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdPg = @"id_pg";
public static string IdPermiso = @"id_permiso";
public static string IdGrupo = @"id_grupo";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.AccessControl;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;
using NuGet;
using Splat;
using Squirrel.Shell;
namespace Squirrel
{
public sealed partial class UpdateManager : IUpdateManager, IEnableLogger
{
readonly string rootAppDirectory;
readonly string applicationName;
readonly IFileDownloader urlDownloader;
readonly string updateUrlOrPath;
IDisposable updateLock;
public UpdateManager(string urlOrPath,
string applicationName = null,
string rootDirectory = null,
IFileDownloader urlDownloader = null)
{
Contract.Requires(!String.IsNullOrEmpty(urlOrPath));
Contract.Requires(!String.IsNullOrEmpty(applicationName));
updateUrlOrPath = urlOrPath;
this.applicationName = applicationName ?? UpdateManager.getApplicationName();
this.urlDownloader = urlDownloader ?? new FileDownloader();
if (rootDirectory != null) {
this.rootAppDirectory = Path.Combine(rootDirectory, this.applicationName);
return;
}
this.rootAppDirectory = Path.Combine(rootDirectory ?? GetLocalAppDataDirectory(), this.applicationName);
}
public async Task<UpdateInfo> CheckForUpdate(bool ignoreDeltaUpdates = false, Action<int> progress = null)
{
var checkForUpdate = new CheckForUpdateImpl(rootAppDirectory);
await acquireUpdateLock();
return await checkForUpdate.CheckForUpdate(Utility.LocalReleaseFileForAppDir(rootAppDirectory), updateUrlOrPath, ignoreDeltaUpdates, progress, urlDownloader);
}
public async Task DownloadReleases(IEnumerable<ReleaseEntry> releasesToDownload, Action<int> progress = null)
{
var downloadReleases = new DownloadReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
await downloadReleases.DownloadReleases(updateUrlOrPath, releasesToDownload, progress, urlDownloader);
}
public async Task<string> ApplyReleases(UpdateInfo updateInfo, Action<int> progress = null)
{
var applyReleases = new ApplyReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
return await applyReleases.ApplyReleases(updateInfo, false, false, progress);
}
public async Task FullInstall(bool silentInstall = false, Action<int> progress = null)
{
var updateInfo = await CheckForUpdate();
await DownloadReleases(updateInfo.ReleasesToApply);
var applyReleases = new ApplyReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
await applyReleases.ApplyReleases(updateInfo, silentInstall, true, progress);
}
public async Task FullUninstall()
{
var applyReleases = new ApplyReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
await applyReleases.FullUninstall();
}
public Task<RegistryKey> CreateUninstallerRegistryEntry(string uninstallCmd, string quietSwitch)
{
var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory);
return installHelpers.CreateUninstallerRegistryEntry(uninstallCmd, quietSwitch);
}
public Task<RegistryKey> CreateUninstallerRegistryEntry()
{
var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory);
return installHelpers.CreateUninstallerRegistryEntry();
}
public void RemoveUninstallerRegistryEntry()
{
var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory);
installHelpers.RemoveUninstallerRegistryEntry();
}
public void CreateShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly, string programArguments = null, string icon = null)
{
var installHelpers = new ApplyReleasesImpl(rootAppDirectory);
installHelpers.CreateShortcutsForExecutable(exeName, locations, updateOnly, programArguments, icon);
}
public Dictionary<ShortcutLocation, ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, string programArguments = null)
{
var installHelpers = new ApplyReleasesImpl(rootAppDirectory);
return installHelpers.GetShortcutsForExecutable(exeName, locations, programArguments);
}
public void RemoveShortcutsForExecutable(string exeName, ShortcutLocation locations)
{
var installHelpers = new ApplyReleasesImpl(rootAppDirectory);
installHelpers.RemoveShortcutsForExecutable(exeName, locations);
}
public SemanticVersion CurrentlyInstalledVersion(string executable = null)
{
executable = executable ??
Path.GetDirectoryName(typeof(UpdateManager).Assembly.Location);
if (!executable.StartsWith(rootAppDirectory, StringComparison.OrdinalIgnoreCase)) {
return null;
}
var appDirName = executable.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.FirstOrDefault(x => x.StartsWith("app-", StringComparison.OrdinalIgnoreCase));
if (appDirName == null) return null;
return appDirName.ToSemanticVersion();
}
public string ApplicationName {
get { return applicationName; }
}
public string RootAppDirectory {
get { return rootAppDirectory; }
}
public bool IsInstalledApp {
get { return Assembly.GetExecutingAssembly().Location.StartsWith(RootAppDirectory, StringComparison.OrdinalIgnoreCase); }
}
public void Dispose()
{
var disp = Interlocked.Exchange(ref updateLock, null);
if (disp != null) {
disp.Dispose();
}
}
static bool exiting = false;
public static void RestartApp(string exeToStart = null, string arguments = null)
{
// NB: Here's how this method works:
//
// 1. We're going to pass the *name* of our EXE and the params to
// Update.exe
// 2. Update.exe is going to grab our PID (via getting its parent),
// then wait for us to exit.
// 3. We exit cleanly, dropping any single-instance mutexes or
// whatever.
// 4. Update.exe unblocks, then we launch the app again, possibly
// launching a different version than we started with (this is why
// we take the app's *name* rather than a full path)
exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location);
var argsArg = arguments != null ?
String.Format("-a \"{0}\"", arguments) : "";
exiting = true;
Process.Start(getUpdateExe(), String.Format("--processStartAndWait {0} {1}", exeToStart, argsArg));
// NB: We have to give update.exe some time to grab our PID, but
// we can't use WaitForInputIdle because we probably don't have
// whatever WaitForInputIdle considers a message loop.
Thread.Sleep(500);
Environment.Exit(0);
}
public static string GetLocalAppDataDirectory(string assemblyLocation = null)
{
// Try to divine our our own install location via reading tea leaves
//
// * We're Update.exe, running in the app's install folder
// * We're Update.exe, running on initial install from SquirrelTemp
// * We're a C# EXE with Squirrel linked in
var assembly = Assembly.GetEntryAssembly();
if (assemblyLocation == null && assembly == null) {
// dunno lol
return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
}
assemblyLocation = assemblyLocation ?? assembly.Location;
if (Path.GetFileName(assemblyLocation).Equals("update.exe", StringComparison.OrdinalIgnoreCase)) {
// NB: Both the "SquirrelTemp" case and the "App's folder" case
// mean that the root app dir is one up
var oneFolderUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), "..");
return Path.GetFullPath(oneFolderUpFromAppFolder);
}
var twoFoldersUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), "..\\..");
return Path.GetFullPath(twoFoldersUpFromAppFolder);
}
~UpdateManager()
{
if (updateLock != null && !exiting) {
throw new Exception("You must dispose UpdateManager!");
}
}
Task<IDisposable> acquireUpdateLock()
{
if (updateLock != null) return Task.FromResult(updateLock);
return Task.Run(() => {
var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory)));
IDisposable theLock;
try {
theLock = ModeDetector.InUnitTestRunner() ?
Disposable.Create(() => {}) : new SingleGlobalInstance(key, TimeSpan.FromMilliseconds(2000));
} catch (TimeoutException) {
throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates");
}
var ret = Disposable.Create(() => {
theLock.Dispose();
updateLock = null;
});
updateLock = ret;
return ret;
});
}
static string getApplicationName()
{
var fi = new FileInfo(getUpdateExe());
return fi.Directory.Name;
}
static string getUpdateExe()
{
var assembly = Assembly.GetEntryAssembly();
// Are we update.exe?
if (assembly != null &&
Path.GetFileName(assembly.Location).Equals("update.exe", StringComparison.OrdinalIgnoreCase) &&
assembly.Location.IndexOf("app-", StringComparison.OrdinalIgnoreCase) == -1 &&
assembly.Location.IndexOf("SquirrelTemp", StringComparison.OrdinalIgnoreCase) == -1) {
return Path.GetFullPath(assembly.Location);
}
assembly = Assembly.GetExecutingAssembly();
var updateDotExe = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe");
var target = new FileInfo(updateDotExe);
if (!target.Exists) throw new Exception("Update.exe not found, not a Squirrel-installed app?");
return target.FullName;
}
}
}
| |
// Copyright 2020 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
//
// 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 DebuggerApi;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using YetiCommon;
using YetiCommon.CastleAspects;
using YetiVSI.DebugEngine.Exit;
using YetiVSI.Util;
namespace YetiVSI.DebugEngine
{
public interface IGgpDebugProgram : IDebugProgram3, IDebugMemoryBytes2
{
/// <summary>
/// Returns the DebugThread corresponding to an LLDBThread. If a cached DebugThread exists
/// with matching ID, that is returned. Otherwise, a new
/// DebugThread is created and added to the cache.
/// </summary>
IDebugThread GetDebugThread(RemoteThread lldbThread);
/// <summary>
/// Returns true if Visual Studio has called Terminate().
/// </summary>
bool TerminationRequested { get; }
/// <summary>
/// Returns true if Visual Studio has called Detach().
/// </summary>
bool DetachRequested { get; }
/// <summary>
/// Returns remote target for the current program.
/// </summary>
RemoteTarget Target { get; }
}
public interface IDebugProgramFactory
{
IGgpDebugProgram Create(IDebugEngineHandler debugEngineHandler,
DebugProgram.ThreadCreator threadCreator,
IDebugProcess2 process, Guid programId, SbProcess lldbProcess,
RemoteTarget lldbTarget,
IDebugModuleCache debugModuleCache, bool isCoreAttach);
}
// DebugProgram contains execution information about a process.
public class DebugProgram : SimpleDecoratorSelf<IGgpDebugProgram>, IGgpDebugProgram
{
public delegate IDebugThread ThreadCreator(RemoteThread lldbThread,
IGgpDebugProgram debugProgram);
public class Factory : IDebugProgramFactory
{
readonly JoinableTaskContext _taskContext;
readonly DebugDisassemblyStream.Factory _debugDisassemblyStreamFactory;
readonly DebugDocumentContext.Factory _documentContextFactory;
readonly DebugCodeContext.Factory _codeContextFactory;
readonly ThreadEnumFactory _threadsEnumFactory;
readonly ModuleEnumFactory _moduleEnumFactory;
readonly CodeContextEnumFactory _codeContextEnumFactory;
public Factory(JoinableTaskContext taskContext,
DebugDisassemblyStream.Factory debugDisassemblyStreamFactory,
DebugDocumentContext.Factory documentContextFactory,
DebugCodeContext.Factory codeContextFactory,
ThreadEnumFactory threadsEnumFactory,
ModuleEnumFactory moduleEnumFactory,
CodeContextEnumFactory codeContextEnumFactory)
{
_taskContext = taskContext;
_debugDisassemblyStreamFactory = debugDisassemblyStreamFactory;
_documentContextFactory = documentContextFactory;
_codeContextFactory = codeContextFactory;
_threadsEnumFactory = threadsEnumFactory;
_moduleEnumFactory = moduleEnumFactory;
_codeContextEnumFactory = codeContextEnumFactory;
}
public IGgpDebugProgram Create(IDebugEngineHandler debugEngineHandler,
ThreadCreator threadCreator,
IDebugProcess2 process, Guid programId, SbProcess lldbProcess,
RemoteTarget lldbTarget,
IDebugModuleCache debugModuleCache, bool isCoreAttach)
{
return new DebugProgram(_taskContext, threadCreator,
_debugDisassemblyStreamFactory,
_documentContextFactory, _codeContextFactory, _threadsEnumFactory,
_moduleEnumFactory, _codeContextEnumFactory, debugEngineHandler, process,
programId, lldbProcess, lldbTarget, debugModuleCache, isCoreAttach);
}
}
readonly Guid _id;
readonly IDebugProcess2 _process;
readonly SbProcess _lldbProcess;
readonly RemoteTarget _lldbTarget;
readonly Dictionary<uint, IDebugThread> _threadCache;
readonly bool _isCoreAttach;
readonly IDebugEngineHandler _debugEngineHandler;
readonly JoinableTaskContext _taskContext;
readonly ThreadCreator _threadCreator;
readonly DebugDisassemblyStream.Factory _debugDisassemblyStreamFactory;
readonly DebugDocumentContext.Factory _documentContextFactory;
readonly DebugCodeContext.Factory _codeContextFactory;
readonly IDebugModuleCache _debugModuleCache;
readonly ThreadEnumFactory _threadEnumFactory;
readonly ModuleEnumFactory _moduleEnumFactory;
readonly CodeContextEnumFactory _codeContextEnumFactory;
public RemoteTarget Target => _lldbTarget;
DebugProgram(
JoinableTaskContext taskContext,
ThreadCreator threadCreator,
DebugDisassemblyStream.Factory debugDisassemblyStreamFactory,
DebugDocumentContext.Factory documentContextFactory,
DebugCodeContext.Factory codeContextFactory,
ThreadEnumFactory threadEnumFactory,
ModuleEnumFactory moduleEnumFactory,
CodeContextEnumFactory codeContextEnumFactory,
IDebugEngineHandler debugEngineHandler,
IDebugProcess2 process,
Guid programId,
SbProcess lldbProcess,
RemoteTarget lldbTarget,
IDebugModuleCache debugModuleCache,
bool isCoreAttach)
{
_id = programId;
_process = process;
_lldbProcess = lldbProcess;
_lldbTarget = lldbTarget;
_threadCache = new Dictionary<uint, IDebugThread>();
_isCoreAttach = isCoreAttach;
_debugEngineHandler = debugEngineHandler;
_taskContext = taskContext;
_threadCreator = threadCreator;
_debugDisassemblyStreamFactory = debugDisassemblyStreamFactory;
_documentContextFactory = documentContextFactory;
_codeContextFactory = codeContextFactory;
_threadEnumFactory = threadEnumFactory;
_moduleEnumFactory = moduleEnumFactory;
_codeContextEnumFactory = codeContextEnumFactory;
_debugModuleCache = debugModuleCache;
}
#region IGgpDebugProgram functions
public IDebugThread GetDebugThread(RemoteThread lldbThread)
{
if (lldbThread == null)
{
return null;
}
lock (_threadCache)
{
IDebugThread debugThread;
uint threadId = (uint)lldbThread.GetThreadId();
if (!_threadCache.TryGetValue(threadId, out debugThread))
{
debugThread = _threadCreator(lldbThread, Self);
_threadCache.Add(threadId, debugThread);
_debugEngineHandler.SendEvent(new ThreadCreateEvent(), Self, debugThread);
}
return debugThread;
}
}
public bool TerminationRequested { get; private set; }
public bool DetachRequested { get; private set; }
#endregion
#region IDebugProgram3 functions
public int Attach(IDebugEventCallback2 callback)
{
return VSConstants.E_NOTIMPL;
}
public int CanDetach()
{
return VSConstants.S_OK;
}
public int CauseBreak()
{
if (_lldbProcess.Stop())
{
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
public int Continue(IDebugThread2 thread)
{
if (_isCoreAttach)
{
return AD7Constants.E_CRASHDUMP_UNSUPPORTED;
}
if (_lldbProcess.Continue())
{
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
public int Detach()
{
DetachRequested = true;
if (!_lldbProcess.Detach())
{
DetachRequested = false;
return VSConstants.E_FAIL;
}
// Send the ProgramDestroyEvent immediately, so that Visual Studio can't cause a
// deadlock by waiting for the event while preventing us from accessing the main thread.
// TODO: Block and wait for LldbEventHandler to send the event
_debugEngineHandler.Abort(this, ExitInfo.Normal(ExitReason.DebuggerDetached));
return VSConstants.S_OK;
}
public int EnumCodeContexts(
IDebugDocumentPosition2 docPos, out IEnumDebugCodeContexts2 contextsEnum)
{
contextsEnum = null;
var startPositions = new TEXT_POSITION[1];
var result = docPos.GetRange(startPositions, null);
if (result != VSConstants.S_OK)
{
Trace.WriteLine("Error: Unable to retrieve starting position.");
return result;
}
string fileName;
docPos.GetFileName(out fileName);
var codeContexts = new List<IDebugCodeContext2>();
// TODO: Find a less hacky way of doing this
var tempBreakpoint = _lldbTarget.BreakpointCreateByLocation(fileName,
startPositions[0].dwLine + 1);
if (tempBreakpoint == null)
{
Trace.WriteLine("Error: Failed to set temporary breakpoint used to map document " +
"position to code contexts.");
return VSConstants.E_FAIL;
}
try
{
var numLocations = tempBreakpoint.GetNumLocations();
for (uint i = 0; i < numLocations; ++i)
{
var location = tempBreakpoint.GetLocationAtIndex(i);
var address = location.GetAddress();
if (address != null)
{
var lineEntry = address.GetLineEntry();
var codeContext = _codeContextFactory.Create(
target: _lldbTarget,
address: address.GetLoadAddress(_lldbTarget),
functionName: null,
documentContext: _documentContextFactory.Create(lineEntry));
codeContexts.Add(codeContext);
}
else
{
Trace.WriteLine("Warning: Failed to obtain address for code context " +
"from temporary breakpoint location. Code context skipped.");
}
}
}
finally
{
_lldbTarget.BreakpointDelete(tempBreakpoint.GetId());
}
contextsEnum = _codeContextEnumFactory.Create(codeContexts);
return VSConstants.S_OK;
}
public int EnumCodePaths(
string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int source,
out IEnumCodePaths2 pathsEnum, out IDebugCodeContext2 safety)
{
pathsEnum = null;
safety = null;
return VSConstants.E_NOTIMPL;
}
public int EnumModules(out IEnumDebugModules2 modulesEnum)
{
var sbModules = GetSbModules();
_debugModuleCache.RemoveAllExcept(sbModules);
var modules = sbModules.Select(m => _debugModuleCache.GetOrCreate(m, Self));
modulesEnum = _moduleEnumFactory.Create(modules);
return VSConstants.S_OK;
}
public int EnumThreads(out IEnumDebugThreads2 threadsEnum)
{
lock (_threadCache)
{
var remoteThreads = GetRemoteThreads();
// If we fail to get the list of threads, return the current cache instead. If we
// send a ThreadCreateEvent, and then fail to return that thread on the next
// EnumThreads call, that thread will be lost forever.
if (remoteThreads.Count == 0)
{
threadsEnum = _threadEnumFactory.Create(_threadCache.Values);
return VSConstants.S_OK;
}
// Update the thread cache, and remove any stale entries.
var deadIds = _threadCache.Keys.ToList();
foreach (var remoteThread in remoteThreads)
{
var currentThread = GetDebugThread(remoteThread);
uint threadId;
currentThread.GetThreadId(out threadId);
deadIds.Remove(threadId);
}
foreach (var threadId in deadIds)
{
IDebugThread thread;
if (_threadCache.TryGetValue(threadId, out thread))
{
_debugEngineHandler.SendEvent(new ThreadDestroyEvent(0), Self, thread);
_threadCache.Remove(threadId);
}
}
threadsEnum = _threadEnumFactory.Create(_threadCache.Values);
}
return VSConstants.S_OK;
}
public int Execute()
{
return VSConstants.E_NOTIMPL;
}
public int GetDebugProperty(out IDebugProperty2 property)
{
property = null;
return VSConstants.E_NOTIMPL;
}
public int GetDisassemblyStream(
enum_DISASSEMBLY_STREAM_SCOPE scope, IDebugCodeContext2 codeContext,
out IDebugDisassemblyStream2 disassemblyStream)
{
disassemblyStream = _debugDisassemblyStreamFactory.Create(
scope, codeContext, _lldbTarget);
return VSConstants.S_OK;
}
public int GetENCUpdate(out object update)
{
update = null;
return VSConstants.E_NOTIMPL;
}
public int GetEngineInfo(out string engine, out Guid engineGuid)
{
engine = YetiConstants.YetiTitle;
engineGuid = YetiConstants.DebugEngineGuid;
return VSConstants.S_OK;
}
public int GetMemoryBytes(out IDebugMemoryBytes2 memoryBytes)
{
memoryBytes = Self;
return VSConstants.S_OK;
}
public int GetName(out string name)
{
_taskContext.ThrowIfNotOnMainThread();
return _process.GetName(enum_GETNAME_TYPE.GN_BASENAME, out name);
}
public int GetProcess(out IDebugProcess2 process)
{
_taskContext.ThrowIfNotOnMainThread();
process = _process;
return VSConstants.S_OK;
}
public int GetProgramId(out Guid guid)
{
guid = _id;
return VSConstants.S_OK;
}
public int Step(IDebugThread2 thread, enum_STEPKIND sk, enum_STEPUNIT step)
{
if (_isCoreAttach)
{
return AD7Constants.E_CRASHDUMP_UNSUPPORTED;
}
var lldbThread = ((IDebugThread)thread).GetRemoteThread();
switch (step)
{
case enum_STEPUNIT.STEP_STATEMENT:
switch (sk)
{
case enum_STEPKIND.STEP_INTO:
lldbThread.StepInto();
break;
case enum_STEPKIND.STEP_OVER:
lldbThread.StepOver();
break;
case enum_STEPKIND.STEP_OUT:
lldbThread.StepOut();
break;
default:
return VSConstants.E_NOTIMPL;
}
return VSConstants.S_OK;
case enum_STEPUNIT.STEP_INSTRUCTION:
switch (sk)
{
case enum_STEPKIND.STEP_OVER:
lldbThread.StepInstruction(true);
break;
case enum_STEPKIND.STEP_INTO:
lldbThread.StepInstruction(false);
break;
case enum_STEPKIND.STEP_OUT:
lldbThread.StepOut();
break;
default:
return VSConstants.E_NOTIMPL;
}
return VSConstants.S_OK;
}
return VSConstants.E_NOTIMPL;
}
public int Terminate()
{
TerminationRequested = true;
//TODO: remove the legacy launch flow.
if (!_lldbProcess.Kill())
{
// Visual Studio waits for the ProgramDestroyEvent regardless of whether
// Terminate() succeeds, so we send the event on failure as well as on success.
_debugEngineHandler.Abort(
this,
ExitInfo.Error(new TerminateProcessException(ErrorStrings.FailedToStopGame)));
return VSConstants.E_FAIL;
}
// Send the ProgramDestroyEvent immediately, so that Visual Studio can't cause a
// deadlock by waiting for the event while preventing us from accessing the main thread.
// TODO: Block and wait for LldbEventHandler to send the event
_debugEngineHandler.Abort(this, ExitInfo.Normal(ExitReason.DebuggerTerminated));
return VSConstants.S_OK;
}
public int WriteDump(enum_DUMPTYPE dumpType, string dumpUrl)
{
_lldbProcess.SaveCore(dumpUrl, out SbError error);
if (error.Fail())
{
string errorMessage = error.GetCString();
string fullErrorDescription = errorMessage.Contains("no ObjectFile plugins")
? ErrorStrings.WritingDumpNotSupported(errorMessage)
: ErrorStrings.FailedToWriteDump(errorMessage);
MessageBox.Show(fullErrorDescription,
"Save Dump As...",
MessageBoxButton.OK,
MessageBoxImage.Error);
Trace.WriteLine($"Error: {errorMessage}");
}
return VSConstants.S_OK;
}
// Confusingly, at least in the Attach case with LLDB, the SDM calls
// this when continuing rather than Continue.
public int ExecuteOnThread(IDebugThread2 pThread)
{
_taskContext.ThrowIfNotOnMainThread();
return Continue(pThread);
}
#endregion
// Gets a list of all the SbModules.
List<SbModule> GetSbModules()
{
var modules = new List<SbModule>();
var numModules = _lldbTarget.GetNumModules();
for (int i = 0; i < numModules; i++)
{
var module = _lldbTarget.GetModuleAtIndex(i);
if (module == null)
{
Trace.WriteLine($"Unable to retrieve module {i}");
continue;
}
modules.Add(module);
}
return modules;
}
// Gets a list of all the RemoteThreads. If there is an issue retreiving any of the threads,
// instead of returning a partial list, an empty list is returned.
List<RemoteThread> GetRemoteThreads()
{
var threads = new List<RemoteThread>();
var numberThreads = _lldbProcess.GetNumThreads();
for (int i = 0; i < numberThreads; i++)
{
var thread = _lldbProcess.GetThreadAtIndex(i);
if (thread == null)
{
Trace.WriteLine($"Failed to get thread at index: {i}");
return new List<RemoteThread>();
}
threads.Add(thread);
}
return threads;
}
#region IDebugMemoryBytes2 functions
public int ReadAt(IDebugMemoryContext2 startMemoryContext, uint countToRead, byte[] memory,
out uint countRead, ref uint countUnreadable)
{
// |countUnreadable| can be null when calling from C++ according to Microsoft's doc.
// However, countUnreadable == null will always return false in C# as an uint can never
// be null. Accessing |countUnreadable| here might cause a NullReferenceException.
// According to Microsoft's doc, |countUnreadable| is useful when there are
// non -consecutive blocks of memory that are readable. For example, if we want to read
// 100 bytes at a certain address and only the first 50 bytes and the last 20 bytes are
// readable. |countRead| would be 50 and |countUnreadable| should be 30. However,
// LLDB's ReadMemory() doesn't provide this kind of output, so this is not
// straightforward to implement.
// TODO We should estimate |countUnreadable| from page boundaries.
// Otherwise, the memory view might be missing some valid contents in the beginnings
// of mapped regions.
// Note: We need to make sure we never return S_OK while setting countRead and
// countUnreadable to zero. That can send the memory view into an infinite loop
// and freeze Visual Studio ((internal)).
var context = (IGgpDebugCodeContext)startMemoryContext;
ulong bytesRead = _lldbProcess.ReadMemory(
context.Address, memory, countToRead, out SbError error);
if (error.Fail())
{
Trace.WriteLine($"Warning: ReadMemory failed: {error.GetCString()}");
countRead = 0;
return VSConstants.E_FAIL;
}
if (bytesRead == 0 || bytesRead > uint.MaxValue)
{
Trace.WriteLine($"Warning: ReadMemory failed: read {bytesRead} bytes");
countRead = 0;
return VSConstants.E_FAIL;
}
countRead = (uint)bytesRead;
return VSConstants.S_OK;
}
public int WriteAt(IDebugMemoryContext2 startMemoryContext, uint count, byte[] buffer)
{
var context = (IGgpDebugCodeContext)startMemoryContext;
ulong bytesWritten = _lldbProcess.WriteMemory(
context.Address, buffer, count, out SbError error);
if (error.Fail())
{
Trace.WriteLine($"Error: {error.GetCString()}");
return VSConstants.E_FAIL;
}
if (bytesWritten != count)
{
Trace.WriteLine(
$"Warning: WriteMemory failed: wrote {bytesWritten} out of {count} bytes.");
return VSConstants.S_FALSE;
}
return VSConstants.S_OK;
}
public int GetSize(out ulong size)
{
size = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
public class TerminateProcessException : Exception, IUserVisibleError
{
public TerminateProcessException(string message) : base(message) { }
public TerminateProcessException(string message, Exception inner) : base(message, inner)
{ }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Microsoft.Xml
{
using System;
internal enum ValueHandleConstStringType
{
String = 0,
Number = 1,
Array = 2,
Object = 3,
Boolean = 4,
Null = 5,
}
internal static class ValueHandleLength
{
public const int Int8 = 1;
public const int Int16 = 2;
public const int Int32 = 4;
public const int Int64 = 8;
public const int UInt64 = 8;
public const int Single = 4;
public const int Double = 8;
public const int Decimal = 16;
public const int DateTime = 8;
public const int TimeSpan = 8;
public const int Guid = 16;
public const int UniqueId = 16;
}
internal enum ValueHandleType
{
Empty,
True,
False,
Zero,
One,
Int8,
Int16,
Int32,
Int64,
UInt64,
Single,
Double,
Decimal,
DateTime,
TimeSpan,
Guid,
UniqueId,
UTF8,
EscapedUTF8,
Base64,
Dictionary,
List,
Char,
Unicode,
QName,
ConstString
}
internal class ValueHandle
{
private XmlBufferReader _bufferReader;
private ValueHandleType _type;
private int _offset;
private int _length;
private static Base64Encoding s_base64Encoding;
private static string[] s_constStrings = {
"string",
"number",
"array",
"object",
"boolean",
"null",
};
public ValueHandle(XmlBufferReader bufferReader)
{
_bufferReader = bufferReader;
_type = ValueHandleType.Empty;
}
private static Base64Encoding Base64Encoding
{
get
{
if (s_base64Encoding == null)
s_base64Encoding = new Base64Encoding();
return s_base64Encoding;
}
}
public void SetConstantValue(ValueHandleConstStringType constStringType)
{
_type = ValueHandleType.ConstString;
_offset = (int)constStringType;
}
public void SetValue(ValueHandleType type)
{
_type = type;
}
public void SetDictionaryValue(int key)
{
SetValue(ValueHandleType.Dictionary, key, 0);
}
public void SetCharValue(int ch)
{
SetValue(ValueHandleType.Char, ch, 0);
}
public void SetQNameValue(int prefix, int key)
{
SetValue(ValueHandleType.QName, key, prefix);
}
public void SetValue(ValueHandleType type, int offset, int length)
{
_type = type;
_offset = offset;
_length = length;
}
public bool IsWhitespace()
{
switch (_type)
{
case ValueHandleType.UTF8:
return _bufferReader.IsWhitespaceUTF8(_offset, _length);
case ValueHandleType.Dictionary:
return _bufferReader.IsWhitespaceKey(_offset);
case ValueHandleType.Char:
int ch = GetChar();
if (ch > char.MaxValue)
return false;
return XmlConverter.IsWhitespace((char)ch);
case ValueHandleType.EscapedUTF8:
return _bufferReader.IsWhitespaceUTF8(_offset, _length);
case ValueHandleType.Unicode:
return _bufferReader.IsWhitespaceUnicode(_offset, _length);
case ValueHandleType.True:
case ValueHandleType.False:
case ValueHandleType.Zero:
case ValueHandleType.One:
return false;
case ValueHandleType.ConstString:
return s_constStrings[_offset].Length == 0;
default:
return _length == 0;
}
}
public Type ToType()
{
switch (_type)
{
case ValueHandleType.False:
case ValueHandleType.True:
return typeof(bool);
case ValueHandleType.Zero:
case ValueHandleType.One:
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return typeof(int);
case ValueHandleType.Int64:
return typeof(long);
case ValueHandleType.UInt64:
return typeof(ulong);
case ValueHandleType.Single:
return typeof(float);
case ValueHandleType.Double:
return typeof(double);
case ValueHandleType.Decimal:
return typeof(decimal);
case ValueHandleType.DateTime:
return typeof(DateTime);
case ValueHandleType.Empty:
case ValueHandleType.UTF8:
case ValueHandleType.Unicode:
case ValueHandleType.EscapedUTF8:
case ValueHandleType.Dictionary:
case ValueHandleType.Char:
case ValueHandleType.QName:
case ValueHandleType.ConstString:
return typeof(string);
case ValueHandleType.Base64:
return typeof(byte[]);
case ValueHandleType.List:
return typeof(object[]);
case ValueHandleType.UniqueId:
return typeof(UniqueId);
case ValueHandleType.Guid:
return typeof(Guid);
case ValueHandleType.TimeSpan:
return typeof(TimeSpan);
default:
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
public Boolean ToBoolean()
{
ValueHandleType type = _type;
if (type == ValueHandleType.False)
return false;
if (type == ValueHandleType.True)
return true;
if (type == ValueHandleType.UTF8)
return XmlConverter.ToBoolean(_bufferReader.Buffer, _offset, _length);
if (type == ValueHandleType.Int8)
{
int value = GetInt8();
if (value == 0)
return false;
if (value == 1)
return true;
}
return XmlConverter.ToBoolean(GetString());
}
public int ToInt()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.Int64)
{
long value = GetInt64();
if (value >= int.MinValue && value <= int.MaxValue)
{
return (int)value;
}
}
if (type == ValueHandleType.UInt64)
{
ulong value = GetUInt64();
if (value <= int.MaxValue)
{
return (int)value;
}
}
if (type == ValueHandleType.UTF8)
return XmlConverter.ToInt32(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToInt32(GetString());
}
public long ToLong()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.Int64)
return GetInt64();
if (type == ValueHandleType.UInt64)
{
ulong value = GetUInt64();
if (value <= long.MaxValue)
{
return (long)value;
}
}
if (type == ValueHandleType.UTF8)
{
return XmlConverter.ToInt64(_bufferReader.Buffer, _offset, _length);
}
return XmlConverter.ToInt64(GetString());
}
public ulong ToULong()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)
{
long value = ToLong();
if (value >= 0)
return (ulong)value;
}
if (type == ValueHandleType.UInt64)
return GetUInt64();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToUInt64(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToUInt64(GetString());
}
public Single ToSingle()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Single)
return GetSingle();
if (type == ValueHandleType.Double)
{
double value = GetDouble();
if ((value >= Single.MinValue && value <= Single.MaxValue) || double.IsInfinity(value) || double.IsNaN(value))
return (Single)value;
}
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToSingle(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToSingle(GetString());
}
public Double ToDouble()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Double)
return GetDouble();
if (type == ValueHandleType.Single)
return GetSingle();
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToDouble(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToDouble(GetString());
}
public Decimal ToDecimal()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Decimal)
return GetDecimal();
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)
return ToLong();
if (type == ValueHandleType.UInt64)
return GetUInt64();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToDecimal(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToDecimal(GetString());
}
public DateTime ToDateTime()
{
if (_type == ValueHandleType.DateTime)
{
return XmlConverter.ToDateTime(GetInt64());
}
if (_type == ValueHandleType.UTF8)
{
return XmlConverter.ToDateTime(_bufferReader.Buffer, _offset, _length);
}
return XmlConverter.ToDateTime(GetString());
}
public UniqueId ToUniqueId()
{
if (_type == ValueHandleType.UniqueId)
return GetUniqueId();
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToUniqueId(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToUniqueId(GetString());
}
public TimeSpan ToTimeSpan()
{
if (_type == ValueHandleType.TimeSpan)
return new TimeSpan(GetInt64());
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToTimeSpan(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToTimeSpan(GetString());
}
public Guid ToGuid()
{
if (_type == ValueHandleType.Guid)
return GetGuid();
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToGuid(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToGuid(GetString());
}
public override string ToString()
{
return GetString();
}
public byte[] ToByteArray()
{
if (_type == ValueHandleType.Base64)
{
byte[] buffer = new byte[_length];
GetBase64(buffer, 0, _length);
return buffer;
}
if (_type == ValueHandleType.UTF8 && (_length % 4) == 0)
{
try
{
int expectedLength = _length / 4 * 3;
if (_length > 0)
{
if (_bufferReader.Buffer[_offset + _length - 1] == '=')
{
expectedLength--;
if (_bufferReader.Buffer[_offset + _length - 2] == '=')
expectedLength--;
}
}
byte[] buffer = new byte[expectedLength];
int actualLength = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, _length, buffer, 0);
if (actualLength != buffer.Length)
{
byte[] newBuffer = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, actualLength);
buffer = newBuffer;
}
return buffer;
}
catch (FormatException)
{
// Something unhappy with the characters, fall back to the hard way
}
}
try
{
return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString()));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, exception.InnerException));
}
}
public string GetString()
{
ValueHandleType type = _type;
if (type == ValueHandleType.UTF8)
return GetCharsText();
switch (type)
{
case ValueHandleType.False:
return "false";
case ValueHandleType.True:
return "true";
case ValueHandleType.Zero:
return "0";
case ValueHandleType.One:
return "1";
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return XmlConverter.ToString(ToInt());
case ValueHandleType.Int64:
return XmlConverter.ToString(GetInt64());
case ValueHandleType.UInt64:
return XmlConverter.ToString(GetUInt64());
case ValueHandleType.Single:
return XmlConverter.ToString(GetSingle());
case ValueHandleType.Double:
return XmlConverter.ToString(GetDouble());
case ValueHandleType.Decimal:
return XmlConverter.ToString(GetDecimal());
case ValueHandleType.DateTime:
return XmlConverter.ToString(ToDateTime());
case ValueHandleType.Empty:
return string.Empty;
case ValueHandleType.UTF8:
return GetCharsText();
case ValueHandleType.Unicode:
return GetUnicodeCharsText();
case ValueHandleType.EscapedUTF8:
return GetEscapedCharsText();
case ValueHandleType.Char:
return GetCharText();
case ValueHandleType.Dictionary:
return GetDictionaryString().Value;
case ValueHandleType.Base64:
byte[] bytes = ToByteArray();
DiagnosticUtility.DebugAssert(bytes != null, "");
return Base64Encoding.GetString(bytes, 0, bytes.Length);
case ValueHandleType.List:
return XmlConverter.ToString(ToList());
case ValueHandleType.UniqueId:
return XmlConverter.ToString(ToUniqueId());
case ValueHandleType.Guid:
return XmlConverter.ToString(ToGuid());
case ValueHandleType.TimeSpan:
return XmlConverter.ToString(ToTimeSpan());
case ValueHandleType.QName:
return GetQNameDictionaryText();
case ValueHandleType.ConstString:
return s_constStrings[_offset];
default:
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
// ASSUMPTION (Microsoft): all chars in str will be ASCII
public bool Equals2(string str, bool checkLower)
{
if (_type != ValueHandleType.UTF8)
return GetString() == str;
if (_length != str.Length)
return false;
byte[] buffer = _bufferReader.Buffer;
for (int i = 0; i < _length; ++i)
{
DiagnosticUtility.DebugAssert(str[i] < 128, "");
byte ch = buffer[i + _offset];
if (ch == str[i])
continue;
if (checkLower && char.ToLowerInvariant((char)ch) == str[i])
continue;
return false;
}
return true;
}
public object[] ToList()
{
return _bufferReader.GetList(_offset, _length);
}
public object ToObject()
{
switch (_type)
{
case ValueHandleType.False:
case ValueHandleType.True:
return ToBoolean();
case ValueHandleType.Zero:
case ValueHandleType.One:
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return ToInt();
case ValueHandleType.Int64:
return ToLong();
case ValueHandleType.UInt64:
return GetUInt64();
case ValueHandleType.Single:
return ToSingle();
case ValueHandleType.Double:
return ToDouble();
case ValueHandleType.Decimal:
return ToDecimal();
case ValueHandleType.DateTime:
return ToDateTime();
case ValueHandleType.Empty:
case ValueHandleType.UTF8:
case ValueHandleType.Unicode:
case ValueHandleType.EscapedUTF8:
case ValueHandleType.Dictionary:
case ValueHandleType.Char:
case ValueHandleType.ConstString:
return ToString();
case ValueHandleType.Base64:
return ToByteArray();
case ValueHandleType.List:
return ToList();
case ValueHandleType.UniqueId:
return ToUniqueId();
case ValueHandleType.Guid:
return ToGuid();
case ValueHandleType.TimeSpan:
return ToTimeSpan();
default:
throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual)
{
if (_type == ValueHandleType.Base64)
{
actual = Math.Min(_length, count);
GetBase64(buffer, offset, actual);
_offset += actual;
_length -= actual;
return true;
}
if (_type == ValueHandleType.UTF8 && count >= 3 && (_length % 4) == 0)
{
try
{
int charCount = Math.Min(count / 3 * 4, _length);
actual = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, charCount, buffer, offset);
_offset += charCount;
_length -= charCount;
return true;
}
catch (FormatException)
{
// Something unhappy with the characters, fall back to the hard way
}
}
actual = 0;
return false;
}
public bool TryReadChars(char[] chars, int offset, int count, out int actual)
{
DiagnosticUtility.DebugAssert(offset + count <= chars.Length, string.Format("offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'", offset, count, chars.Length));
if (_type == ValueHandleType.Unicode)
return TryReadUnicodeChars(chars, offset, count, out actual);
if (_type != ValueHandleType.UTF8)
{
actual = 0;
return false;
}
int charOffset = offset;
int charCount = count;
byte[] bytes = _bufferReader.Buffer;
int byteOffset = _offset;
int byteCount = _length;
bool insufficientSpaceInCharsArray = false;
while (true)
{
while (charCount > 0 && byteCount > 0)
{
// fast path for codepoints U+0000 - U+007F
byte b = bytes[byteOffset];
if (b >= 0x80)
break;
chars[charOffset] = (char)b;
byteOffset++;
byteCount--;
charOffset++;
charCount--;
}
if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray)
break;
int actualByteCount;
int actualCharCount;
UTF8Encoding encoding = new UTF8Encoding(false, true);
try
{
// If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing
if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))
{
actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);
actualByteCount = byteCount;
}
else
{
Decoder decoder = encoding.GetDecoder();
// Since x bytes can never generate more than x characters this is a safe estimate as to what will fit
actualByteCount = Math.Min(charCount, byteCount);
// We use a decoder so we don't error if we fall across a character boundary
actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);
// We might've gotten zero characters though if < 4 bytes were requested because
// codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char
// codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8
// and represented as TWO chars (high+low surrogate)
// (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)
while (actualCharCount == 0)
{
// Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte
// if we don't bail out since the while loop will advance actualByteCount only after reading the byte.
if (actualByteCount >= 3 && charCount < 2)
{
// If we reach here, it means that we're:
// - trying to decode more than 3 bytes and,
// - there is only one char left of charCount where we're stuffing decoded characters.
// In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars
// (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once
// and an ArgumentException will be thrown complaining that there's not enough space in the output char array.
// actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters
insufficientSpaceInCharsArray = true;
break;
}
else
{
DiagnosticUtility.DebugAssert(byteOffset + actualByteCount < bytes.Length,
string.Format("byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}", byteOffset, actualByteCount, bytes.Length));
// Request a few more bytes to get at least one character
actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);
actualByteCount++;
}
}
// Now that we actually retrieved some characters, figure out how many bytes it actually was
actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);
}
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));
}
// Advance
byteOffset += actualByteCount;
byteCount -= actualByteCount;
charOffset += actualCharCount;
charCount -= actualCharCount;
}
_offset = byteOffset;
_length = byteCount;
actual = (count - charCount);
return true;
}
private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual)
{
int charCount = Math.Min(count, _length / sizeof(char));
for (int i = 0; i < charCount; i++)
{
chars[offset + i] = (char)_bufferReader.GetInt16(_offset + i * sizeof(char));
}
_offset += charCount * sizeof(char);
_length -= charCount * sizeof(char);
actual = charCount;
return true;
}
public bool TryGetDictionaryString(out XmlDictionaryString value)
{
if (_type == ValueHandleType.Dictionary)
{
value = GetDictionaryString();
return true;
}
else
{
value = null;
return false;
}
}
public bool TryGetByteArrayLength(out int length)
{
if (_type == ValueHandleType.Base64)
{
length = _length;
return true;
}
length = 0;
return false;
}
private string GetCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UTF8, "");
if (_length == 1 && _bufferReader.GetByte(_offset) == '1')
return "1";
return _bufferReader.GetString(_offset, _length);
}
private string GetUnicodeCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Unicode, "");
return _bufferReader.GetUnicodeString(_offset, _length);
}
private string GetEscapedCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.EscapedUTF8, "");
return _bufferReader.GetEscapedString(_offset, _length);
}
private string GetCharText()
{
int ch = GetChar();
if (ch > char.MaxValue)
{
SurrogateChar surrogate = new SurrogateChar(ch);
char[] chars = new char[2];
chars[0] = surrogate.HighChar;
chars[1] = surrogate.LowChar;
return new string(chars, 0, 2);
}
else
{
return ((char)ch).ToString();
}
}
private int GetChar()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Char, "");
return _offset;
}
private int GetInt8()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int8, "");
return _bufferReader.GetInt8(_offset);
}
private int GetInt16()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int16, "");
return _bufferReader.GetInt16(_offset);
}
private int GetInt32()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int32, "");
return _bufferReader.GetInt32(_offset);
}
private long GetInt64()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int64 || _type == ValueHandleType.TimeSpan || _type == ValueHandleType.DateTime, "");
return _bufferReader.GetInt64(_offset);
}
private ulong GetUInt64()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UInt64, "");
return _bufferReader.GetUInt64(_offset);
}
private float GetSingle()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Single, "");
return _bufferReader.GetSingle(_offset);
}
private double GetDouble()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Double, "");
return _bufferReader.GetDouble(_offset);
}
private decimal GetDecimal()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Decimal, "");
return _bufferReader.GetDecimal(_offset);
}
private UniqueId GetUniqueId()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UniqueId, "");
return _bufferReader.GetUniqueId(_offset);
}
private Guid GetGuid()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Guid, "");
return _bufferReader.GetGuid(_offset);
}
private void GetBase64(byte[] buffer, int offset, int count)
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Base64, "");
_bufferReader.GetBase64(_offset, buffer, offset, count);
}
private XmlDictionaryString GetDictionaryString()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Dictionary, "");
return _bufferReader.GetDictionaryString(_offset);
}
private string GetQNameDictionaryText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.QName, "");
return string.Concat(PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(_length)), ":", _bufferReader.GetDictionaryString(_offset));
}
}
}
| |
using System;
using System.Collections;
using System.Data;
namespace Rainbow.Framework.Scheduler
{
//Author: Federico Dal Maso
//e-mail: ifof@libero.it
//date: 2003-06-17
/// <summary>
/// Implementation of IScheduler with in-memory cache.
/// CacheScheduler uses an internal SortedList fill with a queue of nearest to occur tasks (ordered by dueTime)
/// Timer can check tasks list very often because it has to check only first element of sortedList and not send any request to database.
/// When a task occurs (because of DueTime expires) task is executed and removed from db and from cache.
/// When a module add a task, it's added to db and to cache.
/// When and only when cache is empty, scheduler performs a SELECT in db and refill the cache.
/// </summary>
public class CachedScheduler : SimpleScheduler
{
private class TaskComparer : IComparer
{
/// <summary>
/// Compare two tasks first order by dueTime. If dueTimes are equal they are ordered by IDTask.
/// Used in sortedlist.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(object x, object y)
{
SchedulerTask xtsk = x as SchedulerTask;
SchedulerTask ytsk = y as SchedulerTask;
if (x == null || y == null)
throw new ArgumentException("object is not a SchedulerTask");
if (xtsk.DueTime < ytsk.DueTime)
return -1;
if (xtsk.DueTime > ytsk.DueTime)
return 1;
if (xtsk.DueTime == ytsk.DueTime)
{
if (xtsk.IDTask < ytsk.IDTask)
return -1;
if (xtsk.IDTask > ytsk.IDTask)
return 1;
if (xtsk.IDTask == ytsk.IDTask)
return 0;
}
throw new ArgumentException("Impossible exception"); //... to compile.
}
}
/// <summary>
///
/// </summary>
protected SortedList _cache;
private static volatile CachedScheduler _theScheduler = null; //the scheduler instance
/// <summary>
/// Get the scheduler, using a singleton pattern.
/// </summary>
/// <param name="applicationMapPath">usually HttpContext.Current.Server.MapPath(PortalSettings.ApplicationPath)</param>
/// <param name="connection">db connection</param>
/// <param name="period">scheduler timer milliseconds</param>
/// <param name="cacheSize">max number of in-memory tasks</param>
/// <returns></returns>
public static CachedScheduler GetScheduler(string applicationMapPath, IDbConnection connection, long period,
int cacheSize)
{
//Sigleton
if (_theScheduler == null)
{
lock (typeof (CachedScheduler))
{
if (_theScheduler == null)
_theScheduler = new CachedScheduler(applicationMapPath, connection, period, cacheSize);
}
}
return _theScheduler;
}
/// <summary>
///
/// </summary>
/// <param name="applicationMapPath"></param>
/// <param name="connection"></param>
/// <param name="period"></param>
/// <param name="cacheSize"></param>
protected CachedScheduler(string applicationMapPath, IDbConnection connection, long period, int cacheSize)
: base(applicationMapPath, connection, period)
{
_cache = new SortedList(new TaskComparer(), cacheSize);
FillCache();
}
/// <summary>
/// Fill internal tasks cache
/// </summary>
public void FillCache()
{
using (IDataReader dr = localSchDB.GetOrderedTask())
{
SchedulerTask tsk;
while (dr.Read() && _cache.Count < _cache.Capacity)
{
tsk = new SchedulerTask(dr);
lock (_cache.SyncRoot)
{
_cache.Add(tsk, tsk);
}
}
dr.Close();
}
}
/// <summary>
/// Insert a new task
/// </summary>
/// <param name="task"></param>
/// <remarks>After a new task is inserted it obtains a IDTask. Before it's -1.</remarks>
/// <returns></returns>
public override SchedulerTask InsertTask(SchedulerTask task)
{
if (task.IDTask != -1)
throw new SchedulerException("Could not insert an inserted task");
task.SetIDTask(localSchDB.InsertTask(task));
if (_cache.Count != 0 && task.DueTime < ((SchedulerTask) _cache.GetKey(_cache.Count - 1)).DueTime)
{
lock (_cache.SyncRoot)
{
_cache.RemoveAt(_cache.Count - 1);
_cache.Add(task, task);
}
}
return task;
}
/// <summary>
/// Remove tasks
/// </summary>
/// <param name="task"></param>
public override void RemoveTask(SchedulerTask task)
{
if (task.IDTask == -1)
return;
//remoce from DB
base.RemoveTask(task);
//remove from cache
lock (_cache.SyncRoot)
{
_cache.Remove(task);
}
}
/// <summary>
/// Performs a schedulation. Called by timer.
/// </summary>
/// <param name="timerState"></param>
protected override void Schedule(object timerState)
{
lock (this)
{
localTimerState.Counter++;
Stop(); //Stop timer while scheduler works
while (_cache.Count != 0)
{
SchedulerTask task = (SchedulerTask) _cache.GetKey(0);
if (task.DueTime > DateTime.Now)
break;
try
{
ExecuteTask(task);
}
catch
{
//TODO: We have to apply some policy here...
//i.e. Move failed tasks on a log, call a Module feedback interface,....
//now task is removed always
}
RemoveTask(task);
}
if (_cache.Count == 0)
{
FillCache();
if (_cache.Count == 0)
return; //avoid loop in case of empty tasks-queue in db.
Schedule(timerState);
}
Start(); //restart timer
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Compute
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Memory;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Resource;
/// <summary>
/// Compute task holder interface used to avoid generics.
/// </summary>
internal interface IComputeTaskHolder
{
/// <summary>
/// Perform map step.
/// </summary>
/// <param name="inStream">Stream with IN data (topology info).</param>
/// <param name="outStream">Stream for OUT data (map result).</param>
/// <returns>Map with produced jobs.</returns>
void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream);
/// <summary>
/// Process local job result.
/// </summary>
/// <param name="jobId">Job pointer.</param>
/// <returns>Policy.</returns>
int JobResultLocal(ComputeJobHolder jobId);
/// <summary>
/// Process remote job result.
/// </summary>
/// <param name="jobId">Job pointer.</param>
/// <param name="stream">Stream.</param>
/// <returns>Policy.</returns>
int JobResultRemote(ComputeJobHolder jobId, PlatformMemoryStream stream);
/// <summary>
/// Perform task reduce.
/// </summary>
void Reduce();
/// <summary>
/// Complete task.
/// </summary>
/// <param name="taskHandle">Task handle.</param>
void Complete(long taskHandle);
/// <summary>
/// Complete task with error.
/// </summary>
/// <param name="taskHandle">Task handle.</param>
/// <param name="stream">Stream with serialized exception.</param>
void CompleteWithError(long taskHandle, PlatformMemoryStream stream);
}
/// <summary>
/// Compute task holder.
/// </summary>
internal class ComputeTaskHolder<TA, T, TR> : IComputeTaskHolder
{
/** Empty results. */
private static readonly IList<IComputeJobResult<T>> EmptyRes =
new ReadOnlyCollection<IComputeJobResult<T>>(new List<IComputeJobResult<T>>());
/** Compute instance. */
private readonly ComputeImpl _compute;
/** Actual task. */
private readonly IComputeTask<TA, T, TR> _task;
/** Task argument. */
private readonly TA _arg;
/** Results cache flag. */
private readonly bool _resCache;
/** Task future. */
private readonly Future<TR> _fut = new Future<TR>();
/** Jobs whose results are cached. */
private ISet<object> _resJobs;
/** Cached results. */
private IList<IComputeJobResult<T>> _ress;
/** Handles for jobs which are not serialized right away. */
private volatile List<long> _jobHandles;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="compute">Compute.</param>
/// <param name="task">Task.</param>
/// <param name="arg">Argument.</param>
public ComputeTaskHolder(Ignite grid, ComputeImpl compute, IComputeTask<TA, T, TR> task, TA arg)
{
_compute = compute;
_arg = arg;
_task = task;
ResourceTypeDescriptor resDesc = ResourceProcessor.Descriptor(task.GetType());
IComputeResourceInjector injector = task as IComputeResourceInjector;
if (injector != null)
injector.Inject(grid);
else
resDesc.InjectIgnite(task, grid);
_resCache = !resDesc.TaskNoResultCache;
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User code can throw any exception")]
public void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream)
{
IList<IClusterNode> subgrid;
ClusterGroupImpl prj = (ClusterGroupImpl)_compute.ClusterGroup;
var ignite = (Ignite) prj.Ignite;
// 1. Unmarshal topology info if topology changed.
var reader = prj.Marshaller.StartUnmarshal(inStream);
if (reader.ReadBoolean())
{
long topVer = reader.ReadLong();
List<IClusterNode> nodes = new List<IClusterNode>(reader.ReadInt());
int nodesCnt = reader.ReadInt();
subgrid = new List<IClusterNode>(nodesCnt);
for (int i = 0; i < nodesCnt; i++)
{
IClusterNode node = ignite.GetNode(reader.ReadGuid());
nodes.Add(node);
if (reader.ReadBoolean())
subgrid.Add(node);
}
// Update parent projection to help other task callers avoid this overhead.
// Note that there is a chance that topology changed even further and this update fails.
// It means that some of subgrid nodes could have left the Grid. This is not critical
// for us, because Java will handle it gracefully.
prj.UpdateTopology(topVer, nodes);
}
else
{
IList<IClusterNode> nodes = prj.NodesNoRefresh();
Debug.Assert(nodes != null, "At least one topology update should have occurred.");
subgrid = IgniteUtils.Shuffle(nodes);
}
// 2. Perform map.
IDictionary<IComputeJob<T>, IClusterNode> map;
Exception err;
try
{
map = _task.Map(subgrid, _arg);
err = null;
}
catch (Exception e)
{
map = null;
err = e;
// Java can receive another exception in case of marshalling failure but it is not important.
Finish(default(TR), e);
}
// 3. Write map result to the output stream.
PortableWriterImpl writer = prj.Marshaller.StartMarshal(outStream);
try
{
if (err == null)
{
writer.WriteBoolean(true); // Success flag.
if (map == null)
writer.WriteBoolean(false); // Map produced no result.
else
{
writer.WriteBoolean(true); // Map produced result.
writer.WriteInt(map.Count); // Amount of mapped jobs.
var jobHandles = new List<long>(map.Count);
foreach (KeyValuePair<IComputeJob<T>, IClusterNode> mapEntry in map)
{
var job = new ComputeJobHolder(_compute.ClusterGroup.Ignite as Ignite, mapEntry.Key.ToNonGeneric());
IClusterNode node = mapEntry.Value;
var jobHandle = ignite.HandleRegistry.Allocate(job);
jobHandles.Add(jobHandle);
writer.WriteLong(jobHandle);
if (node.IsLocal)
writer.WriteBoolean(false); // Job is not serialized.
else
{
writer.WriteBoolean(true); // Job is serialized.
writer.WriteObject(job);
}
writer.WriteGuid(node.Id);
}
_jobHandles = jobHandles;
}
}
else
{
writer.WriteBoolean(false); // Map failed.
// Write error as string because it is not important for Java, we need only to print
// a message in the log.
writer.WriteString("Map step failed [errType=" + err.GetType().Name +
", errMsg=" + err.Message + ']');
}
}
catch (Exception e)
{
// Something went wrong during marshaling.
Finish(default(TR), e);
outStream.Reset();
writer.WriteBoolean(false); // Map failed.
writer.WriteString(e.Message); // Write error message.
}
finally
{
prj.Marshaller.FinishMarshal(writer);
}
}
/** <inheritDoc /> */
public int JobResultLocal(ComputeJobHolder job)
{
return (int)JobResult0(job.JobResult);
}
/** <inheritDoc /> */
[SuppressMessage("ReSharper", "PossibleInvalidOperationException")]
public int JobResultRemote(ComputeJobHolder job, PlatformMemoryStream stream)
{
// 1. Unmarshal result.
PortableReaderImpl reader = _compute.Marshaller.StartUnmarshal(stream);
Guid nodeId = reader.ReadGuid().Value;
bool cancelled = reader.ReadBoolean();
try
{
object err;
var data = PortableUtils.ReadWrappedInvocationResult(reader, out err);
// 2. Process the result.
return (int) JobResult0(new ComputeJobResultImpl(data, (Exception) err, job.Job, nodeId, cancelled));
}
catch (Exception e)
{
Finish(default(TR), e);
if (!(e is IgniteException))
throw new IgniteException("Failed to process job result: " + e.Message, e);
throw;
}
}
/** <inheritDoc /> */
public void Reduce()
{
try
{
TR taskRes = _task.Reduce(_resCache ? _ress : EmptyRes);
Finish(taskRes, null);
}
catch (Exception e)
{
Finish(default(TR), e);
if (!(e is IgniteException))
throw new IgniteException("Failed to reduce task: " + e.Message, e);
throw;
}
}
/** <inheritDoc /> */
public void Complete(long taskHandle)
{
Clean(taskHandle);
}
/// <summary>
/// Complete task with error.
/// </summary>
/// <param name="taskHandle">Task handle.</param>
/// <param name="e">Error.</param>
public void CompleteWithError(long taskHandle, Exception e)
{
Finish(default(TR), e);
Clean(taskHandle);
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User object deserialization can throw any exception")]
public void CompleteWithError(long taskHandle, PlatformMemoryStream stream)
{
PortableReaderImpl reader = _compute.Marshaller.StartUnmarshal(stream);
Exception err;
try
{
if (reader.ReadBoolean())
{
PortableResultWrapper res = reader.ReadObject<PortableUserObject>()
.Deserialize<PortableResultWrapper>();
err = (Exception) res.Result;
}
else
err = ExceptionUtils.GetException(reader.ReadString(), reader.ReadString());
}
catch (Exception e)
{
err = new IgniteException("Task completed with error, but it cannot be unmarshalled: " + e.Message, e);
}
CompleteWithError(taskHandle, err);
}
/// <summary>
/// Task completion future.
/// </summary>
internal IFuture<TR> Future
{
get { return _fut; }
}
/// <summary>
/// Manually set job handles. Used by closures because they have separate flow for map step.
/// </summary>
/// <param name="jobHandles">Job handles.</param>
internal void JobHandles(List<long> jobHandles)
{
_jobHandles = jobHandles;
}
/// <summary>
/// Process job result.
/// </summary>
/// <param name="res">Result.</param>
private ComputeJobResultPolicy JobResult0(IComputeJobResult<object> res)
{
try
{
IList<IComputeJobResult<T>> ress0;
// 1. Prepare old results.
if (_resCache)
{
if (_resJobs == null)
{
_resJobs = new HashSet<object>();
_ress = new List<IComputeJobResult<T>>();
}
ress0 = _ress;
}
else
ress0 = EmptyRes;
// 2. Invoke user code.
var policy = _task.Result(new ComputeJobResultGenericWrapper<T>(res), ress0);
// 3. Add result to the list only in case of success.
if (_resCache)
{
var job = res.Job().Unwrap();
if (!_resJobs.Add(job))
{
// Duplicate result => find and replace it with the new one.
var oldRes = _ress.Single(item => item.Job() == job);
_ress.Remove(oldRes);
}
_ress.Add(new ComputeJobResultGenericWrapper<T>(res));
}
return policy;
}
catch (Exception e)
{
Finish(default(TR), e);
if (!(e is IgniteException))
throw new IgniteException("Failed to process job result: " + e.Message, e);
throw;
}
}
/// <summary>
/// Finish task.
/// </summary>
/// <param name="res">Result.</param>
/// <param name="err">Error.</param>
private void Finish(TR res, Exception err)
{
_fut.OnDone(res, err);
}
/// <summary>
/// Clean-up task resources.
/// </summary>
/// <param name="taskHandle"></param>
private void Clean(long taskHandle)
{
var handles = _jobHandles;
var handleRegistry = _compute.Marshaller.Ignite.HandleRegistry;
if (handles != null)
foreach (var handle in handles)
handleRegistry.Release(handle, true);
handleRegistry.Release(taskHandle, true);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Network;
using Microsoft.WindowsAzure.Management.Network.Models;
namespace Microsoft.WindowsAzure.Management.Network
{
/// <summary>
/// The Service Management API includes operations for managing the virtual
/// networks for your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for
/// more information)
/// </summary>
public static partial class NetworkOperationsExtensions
{
/// <summary>
/// The Begin Setting Network Configuration operation asynchronously
/// configures the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse BeginSettingConfiguration(this INetworkOperations operations, NetworkSetConfigurationParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkOperations)s).BeginSettingConfigurationAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Begin Setting Network Configuration operation asynchronously
/// configures the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// operation.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> BeginSettingConfigurationAsync(this INetworkOperations operations, NetworkSetConfigurationParameters parameters)
{
return operations.BeginSettingConfigurationAsync(parameters, CancellationToken.None);
}
/// <summary>
/// The Get Network Configuration operation retrieves the network
/// configuration file for the given subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <returns>
/// The Get Network Configuration operation response.
/// </returns>
public static NetworkGetConfigurationResponse GetConfiguration(this INetworkOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkOperations)s).GetConfigurationAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Network Configuration operation retrieves the network
/// configuration file for the given subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <returns>
/// The Get Network Configuration operation response.
/// </returns>
public static Task<NetworkGetConfigurationResponse> GetConfigurationAsync(this INetworkOperations operations)
{
return operations.GetConfigurationAsync(CancellationToken.None);
}
/// <summary>
/// The List Virtual network sites operation retrieves the virtual
/// networks configured for the subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <returns>
/// The response structure for the Network Operations List operation.
/// </returns>
public static NetworkListResponse List(this INetworkOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List Virtual network sites operation retrieves the virtual
/// networks configured for the subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <returns>
/// The response structure for the Network Operations List operation.
/// </returns>
public static Task<NetworkListResponse> ListAsync(this INetworkOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
/// <summary>
/// The Set Network Configuration operation asynchronously configures
/// the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static OperationStatusResponse SetConfiguration(this INetworkOperations operations, NetworkSetConfigurationParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((INetworkOperations)s).SetConfigurationAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Set Network Configuration operation asynchronously configures
/// the virtual network. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Network.INetworkOperations.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Set Network Configuration
/// operation.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<OperationStatusResponse> SetConfigurationAsync(this INetworkOperations operations, NetworkSetConfigurationParameters parameters)
{
return operations.SetConfigurationAsync(parameters, CancellationToken.None);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the LabImprimeResultado class.
/// </summary>
[Serializable]
public partial class LabImprimeResultadoCollection : ReadOnlyList<LabImprimeResultado, LabImprimeResultadoCollection>
{
public LabImprimeResultadoCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the LAB_ImprimeResultado view.
/// </summary>
[Serializable]
public partial class LabImprimeResultado : ReadOnlyRecord<LabImprimeResultado>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("LAB_ImprimeResultado", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdProtocolo = new TableSchema.TableColumn(schema);
colvarIdProtocolo.ColumnName = "idProtocolo";
colvarIdProtocolo.DataType = DbType.Int32;
colvarIdProtocolo.MaxLength = 0;
colvarIdProtocolo.AutoIncrement = false;
colvarIdProtocolo.IsNullable = false;
colvarIdProtocolo.IsPrimaryKey = false;
colvarIdProtocolo.IsForeignKey = false;
colvarIdProtocolo.IsReadOnly = false;
schema.Columns.Add(colvarIdProtocolo);
TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema);
colvarIdEfector.ColumnName = "idEfector";
colvarIdEfector.DataType = DbType.Int32;
colvarIdEfector.MaxLength = 0;
colvarIdEfector.AutoIncrement = false;
colvarIdEfector.IsNullable = false;
colvarIdEfector.IsPrimaryKey = false;
colvarIdEfector.IsForeignKey = false;
colvarIdEfector.IsReadOnly = false;
schema.Columns.Add(colvarIdEfector);
TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema);
colvarApellido.ColumnName = "apellido";
colvarApellido.DataType = DbType.String;
colvarApellido.MaxLength = 100;
colvarApellido.AutoIncrement = false;
colvarApellido.IsNullable = false;
colvarApellido.IsPrimaryKey = false;
colvarApellido.IsForeignKey = false;
colvarApellido.IsReadOnly = false;
schema.Columns.Add(colvarApellido);
TableSchema.TableColumn colvarNumeroDocumento = new TableSchema.TableColumn(schema);
colvarNumeroDocumento.ColumnName = "numeroDocumento";
colvarNumeroDocumento.DataType = DbType.Int32;
colvarNumeroDocumento.MaxLength = 0;
colvarNumeroDocumento.AutoIncrement = false;
colvarNumeroDocumento.IsNullable = false;
colvarNumeroDocumento.IsPrimaryKey = false;
colvarNumeroDocumento.IsForeignKey = false;
colvarNumeroDocumento.IsReadOnly = false;
schema.Columns.Add(colvarNumeroDocumento);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.AnsiString;
colvarFecha.MaxLength = 10;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = true;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarPrioridad = new TableSchema.TableColumn(schema);
colvarPrioridad.ColumnName = "prioridad";
colvarPrioridad.DataType = DbType.String;
colvarPrioridad.MaxLength = 50;
colvarPrioridad.AutoIncrement = false;
colvarPrioridad.IsNullable = false;
colvarPrioridad.IsPrimaryKey = false;
colvarPrioridad.IsForeignKey = false;
colvarPrioridad.IsReadOnly = false;
schema.Columns.Add(colvarPrioridad);
TableSchema.TableColumn colvarOrigen = new TableSchema.TableColumn(schema);
colvarOrigen.ColumnName = "origen";
colvarOrigen.DataType = DbType.String;
colvarOrigen.MaxLength = 50;
colvarOrigen.AutoIncrement = false;
colvarOrigen.IsNullable = false;
colvarOrigen.IsPrimaryKey = false;
colvarOrigen.IsForeignKey = false;
colvarOrigen.IsReadOnly = false;
schema.Columns.Add(colvarOrigen);
TableSchema.TableColumn colvarUnidadEdad = new TableSchema.TableColumn(schema);
colvarUnidadEdad.ColumnName = "unidadEdad";
colvarUnidadEdad.DataType = DbType.AnsiString;
colvarUnidadEdad.MaxLength = 5;
colvarUnidadEdad.AutoIncrement = false;
colvarUnidadEdad.IsNullable = true;
colvarUnidadEdad.IsPrimaryKey = false;
colvarUnidadEdad.IsForeignKey = false;
colvarUnidadEdad.IsReadOnly = false;
schema.Columns.Add(colvarUnidadEdad);
TableSchema.TableColumn colvarArea = new TableSchema.TableColumn(schema);
colvarArea.ColumnName = "area";
colvarArea.DataType = DbType.String;
colvarArea.MaxLength = 50;
colvarArea.AutoIncrement = false;
colvarArea.IsNullable = false;
colvarArea.IsPrimaryKey = false;
colvarArea.IsForeignKey = false;
colvarArea.IsReadOnly = false;
schema.Columns.Add(colvarArea);
TableSchema.TableColumn colvarGrupo = new TableSchema.TableColumn(schema);
colvarGrupo.ColumnName = "grupo";
colvarGrupo.DataType = DbType.String;
colvarGrupo.MaxLength = 500;
colvarGrupo.AutoIncrement = false;
colvarGrupo.IsNullable = false;
colvarGrupo.IsPrimaryKey = false;
colvarGrupo.IsForeignKey = false;
colvarGrupo.IsReadOnly = false;
schema.Columns.Add(colvarGrupo);
TableSchema.TableColumn colvarItem = new TableSchema.TableColumn(schema);
colvarItem.ColumnName = "item";
colvarItem.DataType = DbType.String;
colvarItem.MaxLength = 500;
colvarItem.AutoIncrement = false;
colvarItem.IsNullable = false;
colvarItem.IsPrimaryKey = false;
colvarItem.IsForeignKey = false;
colvarItem.IsReadOnly = false;
schema.Columns.Add(colvarItem);
TableSchema.TableColumn colvarEsTitulo = new TableSchema.TableColumn(schema);
colvarEsTitulo.ColumnName = "esTitulo";
colvarEsTitulo.DataType = DbType.AnsiString;
colvarEsTitulo.MaxLength = 2;
colvarEsTitulo.AutoIncrement = false;
colvarEsTitulo.IsNullable = false;
colvarEsTitulo.IsPrimaryKey = false;
colvarEsTitulo.IsForeignKey = false;
colvarEsTitulo.IsReadOnly = false;
schema.Columns.Add(colvarEsTitulo);
TableSchema.TableColumn colvarUnidad = new TableSchema.TableColumn(schema);
colvarUnidad.ColumnName = "unidad";
colvarUnidad.DataType = DbType.String;
colvarUnidad.MaxLength = 100;
colvarUnidad.AutoIncrement = false;
colvarUnidad.IsNullable = false;
colvarUnidad.IsPrimaryKey = false;
colvarUnidad.IsForeignKey = false;
colvarUnidad.IsReadOnly = false;
schema.Columns.Add(colvarUnidad);
TableSchema.TableColumn colvarNumero = new TableSchema.TableColumn(schema);
colvarNumero.ColumnName = "numero";
colvarNumero.DataType = DbType.AnsiString;
colvarNumero.MaxLength = 50;
colvarNumero.AutoIncrement = false;
colvarNumero.IsNullable = true;
colvarNumero.IsPrimaryKey = false;
colvarNumero.IsForeignKey = false;
colvarNumero.IsReadOnly = false;
schema.Columns.Add(colvarNumero);
TableSchema.TableColumn colvarMetodo = new TableSchema.TableColumn(schema);
colvarMetodo.ColumnName = "metodo";
colvarMetodo.DataType = DbType.String;
colvarMetodo.MaxLength = 100;
colvarMetodo.AutoIncrement = false;
colvarMetodo.IsNullable = false;
colvarMetodo.IsPrimaryKey = false;
colvarMetodo.IsForeignKey = false;
colvarMetodo.IsReadOnly = false;
schema.Columns.Add(colvarMetodo);
TableSchema.TableColumn colvarValorReferencia = new TableSchema.TableColumn(schema);
colvarValorReferencia.ColumnName = "valorReferencia";
colvarValorReferencia.DataType = DbType.String;
colvarValorReferencia.MaxLength = 500;
colvarValorReferencia.AutoIncrement = false;
colvarValorReferencia.IsNullable = true;
colvarValorReferencia.IsPrimaryKey = false;
colvarValorReferencia.IsForeignKey = false;
colvarValorReferencia.IsReadOnly = false;
schema.Columns.Add(colvarValorReferencia);
TableSchema.TableColumn colvarSolicitante = new TableSchema.TableColumn(schema);
colvarSolicitante.ColumnName = "solicitante";
colvarSolicitante.DataType = DbType.String;
colvarSolicitante.MaxLength = 205;
colvarSolicitante.AutoIncrement = false;
colvarSolicitante.IsNullable = true;
colvarSolicitante.IsPrimaryKey = false;
colvarSolicitante.IsForeignKey = false;
colvarSolicitante.IsReadOnly = false;
schema.Columns.Add(colvarSolicitante);
TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema);
colvarEdad.ColumnName = "edad";
colvarEdad.DataType = DbType.Int32;
colvarEdad.MaxLength = 0;
colvarEdad.AutoIncrement = false;
colvarEdad.IsNullable = false;
colvarEdad.IsPrimaryKey = false;
colvarEdad.IsForeignKey = false;
colvarEdad.IsReadOnly = false;
schema.Columns.Add(colvarEdad);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "sexo";
colvarSexo.DataType = DbType.String;
colvarSexo.MaxLength = 1;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = false;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
schema.Columns.Add(colvarSexo);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema);
colvarFechaNacimiento.ColumnName = "fechaNacimiento";
colvarFechaNacimiento.DataType = DbType.AnsiString;
colvarFechaNacimiento.MaxLength = 10;
colvarFechaNacimiento.AutoIncrement = false;
colvarFechaNacimiento.IsNullable = true;
colvarFechaNacimiento.IsPrimaryKey = false;
colvarFechaNacimiento.IsForeignKey = false;
colvarFechaNacimiento.IsReadOnly = false;
schema.Columns.Add(colvarFechaNacimiento);
TableSchema.TableColumn colvarHc = new TableSchema.TableColumn(schema);
colvarHc.ColumnName = "HC";
colvarHc.DataType = DbType.Int32;
colvarHc.MaxLength = 0;
colvarHc.AutoIncrement = false;
colvarHc.IsNullable = false;
colvarHc.IsPrimaryKey = false;
colvarHc.IsForeignKey = false;
colvarHc.IsReadOnly = false;
schema.Columns.Add(colvarHc);
TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema);
colvarDomicilio.ColumnName = "domicilio";
colvarDomicilio.DataType = DbType.String;
colvarDomicilio.MaxLength = 4000;
colvarDomicilio.AutoIncrement = false;
colvarDomicilio.IsNullable = true;
colvarDomicilio.IsPrimaryKey = false;
colvarDomicilio.IsForeignKey = false;
colvarDomicilio.IsReadOnly = false;
schema.Columns.Add(colvarDomicilio);
TableSchema.TableColumn colvarSector = new TableSchema.TableColumn(schema);
colvarSector.ColumnName = "sector";
colvarSector.DataType = DbType.AnsiString;
colvarSector.MaxLength = 50;
colvarSector.AutoIncrement = false;
colvarSector.IsNullable = false;
colvarSector.IsPrimaryKey = false;
colvarSector.IsForeignKey = false;
colvarSector.IsReadOnly = false;
schema.Columns.Add(colvarSector);
TableSchema.TableColumn colvarHiv = new TableSchema.TableColumn(schema);
colvarHiv.ColumnName = "hiv";
colvarHiv.DataType = DbType.Boolean;
colvarHiv.MaxLength = 0;
colvarHiv.AutoIncrement = false;
colvarHiv.IsNullable = true;
colvarHiv.IsPrimaryKey = false;
colvarHiv.IsForeignKey = false;
colvarHiv.IsReadOnly = false;
schema.Columns.Add(colvarHiv);
TableSchema.TableColumn colvarSala = new TableSchema.TableColumn(schema);
colvarSala.ColumnName = "sala";
colvarSala.DataType = DbType.AnsiString;
colvarSala.MaxLength = 50;
colvarSala.AutoIncrement = false;
colvarSala.IsNullable = false;
colvarSala.IsPrimaryKey = false;
colvarSala.IsForeignKey = false;
colvarSala.IsReadOnly = false;
schema.Columns.Add(colvarSala);
TableSchema.TableColumn colvarCama = new TableSchema.TableColumn(schema);
colvarCama.ColumnName = "cama";
colvarCama.DataType = DbType.AnsiString;
colvarCama.MaxLength = 50;
colvarCama.AutoIncrement = false;
colvarCama.IsNullable = false;
colvarCama.IsPrimaryKey = false;
colvarCama.IsForeignKey = false;
colvarCama.IsReadOnly = false;
schema.Columns.Add(colvarCama);
TableSchema.TableColumn colvarEmbarazo = new TableSchema.TableColumn(schema);
colvarEmbarazo.ColumnName = "embarazo";
colvarEmbarazo.DataType = DbType.AnsiString;
colvarEmbarazo.MaxLength = 1;
colvarEmbarazo.AutoIncrement = false;
colvarEmbarazo.IsNullable = false;
colvarEmbarazo.IsPrimaryKey = false;
colvarEmbarazo.IsForeignKey = false;
colvarEmbarazo.IsReadOnly = false;
schema.Columns.Add(colvarEmbarazo);
TableSchema.TableColumn colvarResultado = new TableSchema.TableColumn(schema);
colvarResultado.ColumnName = "resultado";
colvarResultado.DataType = DbType.String;
colvarResultado.MaxLength = 4000;
colvarResultado.AutoIncrement = false;
colvarResultado.IsNullable = true;
colvarResultado.IsPrimaryKey = false;
colvarResultado.IsForeignKey = false;
colvarResultado.IsReadOnly = false;
schema.Columns.Add(colvarResultado);
TableSchema.TableColumn colvarOrdenArea = new TableSchema.TableColumn(schema);
colvarOrdenArea.ColumnName = "ordenArea";
colvarOrdenArea.DataType = DbType.Int32;
colvarOrdenArea.MaxLength = 0;
colvarOrdenArea.AutoIncrement = false;
colvarOrdenArea.IsNullable = false;
colvarOrdenArea.IsPrimaryKey = false;
colvarOrdenArea.IsForeignKey = false;
colvarOrdenArea.IsReadOnly = false;
schema.Columns.Add(colvarOrdenArea);
TableSchema.TableColumn colvarOrden = new TableSchema.TableColumn(schema);
colvarOrden.ColumnName = "orden";
colvarOrden.DataType = DbType.Int32;
colvarOrden.MaxLength = 0;
colvarOrden.AutoIncrement = false;
colvarOrden.IsNullable = false;
colvarOrden.IsPrimaryKey = false;
colvarOrden.IsForeignKey = false;
colvarOrden.IsReadOnly = false;
schema.Columns.Add(colvarOrden);
TableSchema.TableColumn colvarEfector = new TableSchema.TableColumn(schema);
colvarEfector.ColumnName = "Efector";
colvarEfector.DataType = DbType.String;
colvarEfector.MaxLength = 100;
colvarEfector.AutoIncrement = false;
colvarEfector.IsNullable = false;
colvarEfector.IsPrimaryKey = false;
colvarEfector.IsForeignKey = false;
colvarEfector.IsReadOnly = false;
schema.Columns.Add(colvarEfector);
TableSchema.TableColumn colvarOrden1 = new TableSchema.TableColumn(schema);
colvarOrden1.ColumnName = "orden1";
colvarOrden1.DataType = DbType.Int32;
colvarOrden1.MaxLength = 0;
colvarOrden1.AutoIncrement = false;
colvarOrden1.IsNullable = false;
colvarOrden1.IsPrimaryKey = false;
colvarOrden1.IsForeignKey = false;
colvarOrden1.IsReadOnly = false;
schema.Columns.Add(colvarOrden1);
TableSchema.TableColumn colvarProfesionalVal = new TableSchema.TableColumn(schema);
colvarProfesionalVal.ColumnName = "profesional_val";
colvarProfesionalVal.DataType = DbType.String;
colvarProfesionalVal.MaxLength = 500;
colvarProfesionalVal.AutoIncrement = false;
colvarProfesionalVal.IsNullable = false;
colvarProfesionalVal.IsPrimaryKey = false;
colvarProfesionalVal.IsForeignKey = false;
colvarProfesionalVal.IsReadOnly = false;
schema.Columns.Add(colvarProfesionalVal);
TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema);
colvarObservaciones.ColumnName = "observaciones";
colvarObservaciones.DataType = DbType.String;
colvarObservaciones.MaxLength = 500;
colvarObservaciones.AutoIncrement = false;
colvarObservaciones.IsNullable = false;
colvarObservaciones.IsPrimaryKey = false;
colvarObservaciones.IsForeignKey = false;
colvarObservaciones.IsReadOnly = false;
schema.Columns.Add(colvarObservaciones);
TableSchema.TableColumn colvarMuestra = new TableSchema.TableColumn(schema);
colvarMuestra.ColumnName = "muestra";
colvarMuestra.DataType = DbType.String;
colvarMuestra.MaxLength = 500;
colvarMuestra.AutoIncrement = false;
colvarMuestra.IsNullable = true;
colvarMuestra.IsPrimaryKey = false;
colvarMuestra.IsForeignKey = false;
colvarMuestra.IsReadOnly = false;
schema.Columns.Add(colvarMuestra);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("LAB_ImprimeResultado",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public LabImprimeResultado()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public LabImprimeResultado(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public LabImprimeResultado(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public LabImprimeResultado(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("IdProtocolo")]
[Bindable(true)]
public int IdProtocolo
{
get
{
return GetColumnValue<int>("idProtocolo");
}
set
{
SetColumnValue("idProtocolo", value);
}
}
[XmlAttribute("IdEfector")]
[Bindable(true)]
public int IdEfector
{
get
{
return GetColumnValue<int>("idEfector");
}
set
{
SetColumnValue("idEfector", value);
}
}
[XmlAttribute("Apellido")]
[Bindable(true)]
public string Apellido
{
get
{
return GetColumnValue<string>("apellido");
}
set
{
SetColumnValue("apellido", value);
}
}
[XmlAttribute("NumeroDocumento")]
[Bindable(true)]
public int NumeroDocumento
{
get
{
return GetColumnValue<int>("numeroDocumento");
}
set
{
SetColumnValue("numeroDocumento", value);
}
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public string Fecha
{
get
{
return GetColumnValue<string>("fecha");
}
set
{
SetColumnValue("fecha", value);
}
}
[XmlAttribute("Prioridad")]
[Bindable(true)]
public string Prioridad
{
get
{
return GetColumnValue<string>("prioridad");
}
set
{
SetColumnValue("prioridad", value);
}
}
[XmlAttribute("Origen")]
[Bindable(true)]
public string Origen
{
get
{
return GetColumnValue<string>("origen");
}
set
{
SetColumnValue("origen", value);
}
}
[XmlAttribute("UnidadEdad")]
[Bindable(true)]
public string UnidadEdad
{
get
{
return GetColumnValue<string>("unidadEdad");
}
set
{
SetColumnValue("unidadEdad", value);
}
}
[XmlAttribute("Area")]
[Bindable(true)]
public string Area
{
get
{
return GetColumnValue<string>("area");
}
set
{
SetColumnValue("area", value);
}
}
[XmlAttribute("Grupo")]
[Bindable(true)]
public string Grupo
{
get
{
return GetColumnValue<string>("grupo");
}
set
{
SetColumnValue("grupo", value);
}
}
[XmlAttribute("Item")]
[Bindable(true)]
public string Item
{
get
{
return GetColumnValue<string>("item");
}
set
{
SetColumnValue("item", value);
}
}
[XmlAttribute("EsTitulo")]
[Bindable(true)]
public string EsTitulo
{
get
{
return GetColumnValue<string>("esTitulo");
}
set
{
SetColumnValue("esTitulo", value);
}
}
[XmlAttribute("Unidad")]
[Bindable(true)]
public string Unidad
{
get
{
return GetColumnValue<string>("unidad");
}
set
{
SetColumnValue("unidad", value);
}
}
[XmlAttribute("Numero")]
[Bindable(true)]
public string Numero
{
get
{
return GetColumnValue<string>("numero");
}
set
{
SetColumnValue("numero", value);
}
}
[XmlAttribute("Metodo")]
[Bindable(true)]
public string Metodo
{
get
{
return GetColumnValue<string>("metodo");
}
set
{
SetColumnValue("metodo", value);
}
}
[XmlAttribute("ValorReferencia")]
[Bindable(true)]
public string ValorReferencia
{
get
{
return GetColumnValue<string>("valorReferencia");
}
set
{
SetColumnValue("valorReferencia", value);
}
}
[XmlAttribute("Solicitante")]
[Bindable(true)]
public string Solicitante
{
get
{
return GetColumnValue<string>("solicitante");
}
set
{
SetColumnValue("solicitante", value);
}
}
[XmlAttribute("Edad")]
[Bindable(true)]
public int Edad
{
get
{
return GetColumnValue<int>("edad");
}
set
{
SetColumnValue("edad", value);
}
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public string Sexo
{
get
{
return GetColumnValue<string>("sexo");
}
set
{
SetColumnValue("sexo", value);
}
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get
{
return GetColumnValue<string>("nombre");
}
set
{
SetColumnValue("nombre", value);
}
}
[XmlAttribute("FechaNacimiento")]
[Bindable(true)]
public string FechaNacimiento
{
get
{
return GetColumnValue<string>("fechaNacimiento");
}
set
{
SetColumnValue("fechaNacimiento", value);
}
}
[XmlAttribute("Hc")]
[Bindable(true)]
public int Hc
{
get
{
return GetColumnValue<int>("HC");
}
set
{
SetColumnValue("HC", value);
}
}
[XmlAttribute("Domicilio")]
[Bindable(true)]
public string Domicilio
{
get
{
return GetColumnValue<string>("domicilio");
}
set
{
SetColumnValue("domicilio", value);
}
}
[XmlAttribute("Sector")]
[Bindable(true)]
public string Sector
{
get
{
return GetColumnValue<string>("sector");
}
set
{
SetColumnValue("sector", value);
}
}
[XmlAttribute("Hiv")]
[Bindable(true)]
public bool? Hiv
{
get
{
return GetColumnValue<bool?>("hiv");
}
set
{
SetColumnValue("hiv", value);
}
}
[XmlAttribute("Sala")]
[Bindable(true)]
public string Sala
{
get
{
return GetColumnValue<string>("sala");
}
set
{
SetColumnValue("sala", value);
}
}
[XmlAttribute("Cama")]
[Bindable(true)]
public string Cama
{
get
{
return GetColumnValue<string>("cama");
}
set
{
SetColumnValue("cama", value);
}
}
[XmlAttribute("Embarazo")]
[Bindable(true)]
public string Embarazo
{
get
{
return GetColumnValue<string>("embarazo");
}
set
{
SetColumnValue("embarazo", value);
}
}
[XmlAttribute("Resultado")]
[Bindable(true)]
public string Resultado
{
get
{
return GetColumnValue<string>("resultado");
}
set
{
SetColumnValue("resultado", value);
}
}
[XmlAttribute("OrdenArea")]
[Bindable(true)]
public int OrdenArea
{
get
{
return GetColumnValue<int>("ordenArea");
}
set
{
SetColumnValue("ordenArea", value);
}
}
[XmlAttribute("Orden")]
[Bindable(true)]
public int Orden
{
get
{
return GetColumnValue<int>("orden");
}
set
{
SetColumnValue("orden", value);
}
}
[XmlAttribute("Efector")]
[Bindable(true)]
public string Efector
{
get
{
return GetColumnValue<string>("Efector");
}
set
{
SetColumnValue("Efector", value);
}
}
[XmlAttribute("Orden1")]
[Bindable(true)]
public int Orden1
{
get
{
return GetColumnValue<int>("orden1");
}
set
{
SetColumnValue("orden1", value);
}
}
[XmlAttribute("ProfesionalVal")]
[Bindable(true)]
public string ProfesionalVal
{
get
{
return GetColumnValue<string>("profesional_val");
}
set
{
SetColumnValue("profesional_val", value);
}
}
[XmlAttribute("Observaciones")]
[Bindable(true)]
public string Observaciones
{
get
{
return GetColumnValue<string>("observaciones");
}
set
{
SetColumnValue("observaciones", value);
}
}
[XmlAttribute("Muestra")]
[Bindable(true)]
public string Muestra
{
get
{
return GetColumnValue<string>("muestra");
}
set
{
SetColumnValue("muestra", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdProtocolo = @"idProtocolo";
public static string IdEfector = @"idEfector";
public static string Apellido = @"apellido";
public static string NumeroDocumento = @"numeroDocumento";
public static string Fecha = @"fecha";
public static string Prioridad = @"prioridad";
public static string Origen = @"origen";
public static string UnidadEdad = @"unidadEdad";
public static string Area = @"area";
public static string Grupo = @"grupo";
public static string Item = @"item";
public static string EsTitulo = @"esTitulo";
public static string Unidad = @"unidad";
public static string Numero = @"numero";
public static string Metodo = @"metodo";
public static string ValorReferencia = @"valorReferencia";
public static string Solicitante = @"solicitante";
public static string Edad = @"edad";
public static string Sexo = @"sexo";
public static string Nombre = @"nombre";
public static string FechaNacimiento = @"fechaNacimiento";
public static string Hc = @"HC";
public static string Domicilio = @"domicilio";
public static string Sector = @"sector";
public static string Hiv = @"hiv";
public static string Sala = @"sala";
public static string Cama = @"cama";
public static string Embarazo = @"embarazo";
public static string Resultado = @"resultado";
public static string OrdenArea = @"ordenArea";
public static string Orden = @"orden";
public static string Efector = @"Efector";
public static string Orden1 = @"orden1";
public static string ProfesionalVal = @"profesional_val";
public static string Observaciones = @"observaciones";
public static string Muestra = @"muestra";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels
{
using System;
using System.Diagnostics.Contracts;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Common.Concurrency;
using DotNetty.Common.Utilities;
public abstract class AbstractChannel : /*DefaultAttributeMap, */ IChannel
{
//static readonly InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannel.class);
protected static readonly ClosedChannelException ClosedChannelException = new ClosedChannelException();
static readonly NotYetConnectedException NotYetConnectedException = new NotYetConnectedException();
IMessageSizeEstimatorHandle estimatorHandle;
readonly IChannelUnsafe channelUnsafe;
readonly DefaultChannelPipeline pipeline;
readonly TaskCompletionSource closeFuture = new TaskCompletionSource();
volatile EndPoint localAddress;
volatile EndPoint remoteAddress;
volatile PausableChannelEventLoop eventLoop;
volatile bool registered;
/// <summary> Cache for the string representation of this channel /// </summary>
bool strValActive;
string strVal;
///// <summary>
// /// Creates a new instance.
// ///
// /// @param parent
// /// the parent of this channel. {@code null} if there's no parent.
// /// </summary>
//protected AbstractChannel(IChannel parent)
// : this(DefaultChannelId.NewInstance())
//{
//}
/// <summary>
/// Creates a new instance.
///
//* @param parent
//* the parent of this channel. {@code null} if there's no parent.
/// </summary>
protected AbstractChannel(IChannel parent /*, ChannelId id*/)
{
this.Parent = parent;
//this.Id = id;
this.channelUnsafe = this.NewUnsafe();
this.pipeline = new DefaultChannelPipeline(this);
}
// todo: public ChannelId Id { get; private set; }
public bool IsWritable
{
get
{
ChannelOutboundBuffer buf = this.channelUnsafe.OutboundBuffer;
return buf != null && buf.IsWritable;
}
}
public IChannel Parent { get; private set; }
public IChannelPipeline Pipeline
{
get { return this.pipeline; }
}
public abstract IChannelConfiguration Configuration { get; }
public IByteBufferAllocator Allocator
{
get { return this.Configuration.Allocator; }
}
public IEventLoop EventLoop
{
get
{
IEventLoop eventLoop = this.eventLoop;
if (eventLoop == null)
{
throw new InvalidOperationException("channel not registered to an event loop");
}
return eventLoop;
}
}
public abstract bool Open { get; }
public abstract bool Active { get; }
public abstract bool DisconnectSupported { get; }
public EndPoint LocalAddress
{
get
{
EndPoint address = this.localAddress;
return address ?? this.CacheLocalAddress();
}
}
public EndPoint RemoteAddress
{
get
{
EndPoint address = this.remoteAddress;
return address ?? this.CacheRemoteAddress();
}
}
protected abstract EndPoint LocalAddressInternal { get; }
protected void InvalidateLocalAddress()
{
this.localAddress = null;
}
protected EndPoint CacheLocalAddress()
{
try
{
return this.localAddress = this.LocalAddressInternal;
}
catch (Exception)
{
// Sometimes fails on a closed socket in Windows.
return null;
}
}
protected abstract EndPoint RemoteAddressInternal { get; }
protected void InvalidateRemoteAddress()
{
this.remoteAddress = null;
}
protected EndPoint CacheRemoteAddress()
{
try
{
return this.remoteAddress = this.RemoteAddressInternal;
}
catch (Exception)
{
// Sometimes fails on a closed socket in Windows.
return null;
}
}
/// <summary>
/// Reset the stored remoteAddress
/// </summary>
public bool Registered
{
get { return this.registered; }
}
public Task BindAsync(EndPoint localAddress)
{
return this.pipeline.BindAsync(localAddress);
}
public Task ConnectAsync(EndPoint remoteAddress)
{
return this.pipeline.ConnectAsync(remoteAddress);
}
public Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress)
{
return this.pipeline.ConnectAsync(remoteAddress, localAddress);
}
public Task DisconnectAsync()
{
return this.pipeline.DisconnectAsync();
}
public Task CloseAsync()
{
return this.pipeline.CloseAsync();
}
public Task DeregisterAsync()
{
/// <summary>
/// One problem of channel deregistration is that after a channel has been deregistered
/// there may still be tasks, created from within one of the channel's ChannelHandlers,
/// input the {@link EventLoop}'s task queue. That way, an unfortunate twist of events could lead
/// to tasks still being input the old {@link EventLoop}'s queue even after the channel has been
/// registered with a new {@link EventLoop}. This would lead to the tasks being executed by two
/// different {@link EventLoop}s.
///
/// Our solution to this problem is to always perform the actual deregistration of
/// the channel as a task and to reject any submission of new tasks, from within
/// one of the channel's ChannelHandlers, until the channel is registered with
/// another {@link EventLoop}. That way we can be sure that there are no more tasks regarding
/// that particular channel after it has been deregistered (because the deregistration
/// task is the last one.).
///
/// This only works for one time tasks. To see how we handle periodic/delayed tasks have a look
/// at {@link io.netty.util.concurrent.ScheduledFutureTask#run()}.
///
/// Also see {@link HeadContext#deregister(ChannelHandlerContext, ChannelPromise)}.
/// </summary>
this.eventLoop.RejectNewTasks();
return this.pipeline.DeregisterAsync();
}
public IChannel Flush()
{
this.pipeline.Flush();
return this;
}
public IChannel Read()
{
this.pipeline.Read();
return this;
}
public Task WriteAsync(object msg)
{
return this.pipeline.WriteAsync(msg);
}
public Task WriteAndFlushAsync(object message)
{
return this.pipeline.WriteAndFlushAsync(message);
}
public Task CloseCompletion
{
get { return this.closeFuture.Task; }
}
public IChannelUnsafe Unsafe
{
get { return this.channelUnsafe; }
}
/// <summary>
/// Create a new {@link AbstractUnsafe} instance which will be used for the life-time of the {@link Channel}
/// </summary>
protected abstract IChannelUnsafe NewUnsafe();
// /// <summary>
//* Returns the ID of this channel.
///// </summary>
//public override int GetHashCode()
//{
// return id.hashCode();
//}
/// <summary>
/// Returns {@code true} if and only if the specified object is identical
/// with this channel (i.e: {@code this == o}).
/// </summary>
public override bool Equals(object o)
{
return this == o;
}
//public int CompareTo(IChannel o)
//{
// if (ReferenceEquals(this, o))
// {
// return 0;
// }
// return id().compareTo(o.id());
//}
/// <summary>
/// Returns the {@link String} representation of this channel. The returned
/// string contains the {@linkplain #hashCode()} ID}, {@linkplain #localAddress() local address},
/// and {@linkplain #remoteAddress() remote address} of this channel for
/// easier identification.
/// </summary>
public override string ToString()
{
bool active = this.Active;
if (this.strValActive == active && this.strVal != null)
{
return this.strVal;
}
EndPoint remoteAddr = this.RemoteAddress;
EndPoint localAddr = this.LocalAddress;
if (remoteAddr != null)
{
EndPoint srcAddr;
EndPoint dstAddr;
if (this.Parent == null)
{
srcAddr = localAddr;
dstAddr = remoteAddr;
}
else
{
srcAddr = remoteAddr;
dstAddr = localAddr;
}
StringBuilder buf = new StringBuilder(96)
.Append("[id: 0x")
//.Append(id.asShortText())
.Append(", ")
.Append(srcAddr)
.Append(active ? " => " : " :> ")
.Append(dstAddr)
.Append(']');
this.strVal = buf.ToString();
}
else if (localAddr != null)
{
StringBuilder buf = new StringBuilder(64)
.Append("[id: 0x")
//.Append(id.asShortText())
.Append(", ")
.Append(localAddr)
.Append(']');
this.strVal = buf.ToString();
}
else
{
StringBuilder buf = new StringBuilder(16)
.Append("[id: 0x")
//.Append(id.asShortText())
.Append(']');
this.strVal = buf.ToString();
}
this.strValActive = active;
return this.strVal;
}
internal IMessageSizeEstimatorHandle EstimatorHandle
{
get
{
if (this.estimatorHandle == null)
{
this.estimatorHandle = this.Configuration.MessageSizeEstimator.NewHandle();
}
return this.estimatorHandle;
}
}
/// <summary>
/// {@link Unsafe} implementation which sub-classes must extend and use.
/// </summary>
protected abstract class AbstractUnsafe : IChannelUnsafe
{
protected readonly AbstractChannel channel;
ChannelOutboundBuffer outboundBuffer;
IRecvByteBufAllocatorHandle recvHandle;
bool inFlush0;
/// <summary> true if the channel has never been registered, false otherwise /// </summary>
bool neverRegistered = true;
public IRecvByteBufAllocatorHandle RecvBufAllocHandle
{
get
{
if (this.recvHandle == null)
{
this.recvHandle = this.channel.Configuration.RecvByteBufAllocator.NewHandle();
}
return this.recvHandle;
}
}
//public ChannelHandlerInvoker invoker() {
// // return the unwrapped invoker.
// return ((PausableChannelEventExecutor) eventLoop().asInvoker()).unwrapInvoker();
//}
protected AbstractUnsafe(AbstractChannel channel)
{
this.channel = channel;
this.outboundBuffer = new ChannelOutboundBuffer(channel);
}
public ChannelOutboundBuffer OutboundBuffer
{
get { return this.outboundBuffer; }
}
public Task RegisterAsync(IEventLoop eventLoop)
{
Contract.Requires(eventLoop != null);
if (this.channel.Registered)
{
return TaskEx.FromException(new InvalidOperationException("registered to an event loop already"));
}
if (!this.channel.IsCompatible(eventLoop))
{
return TaskEx.FromException(new InvalidOperationException("incompatible event loop type: " + eventLoop.GetType().Name));
}
// It's necessary to reuse the wrapped eventloop object. Otherwise the user will end up with multiple
// objects that do not share a common state.
if (this.channel.eventLoop == null)
{
this.channel.eventLoop = new PausableChannelEventLoop(this.channel, eventLoop);
}
else
{
this.channel.eventLoop.Unwrapped = eventLoop;
}
var promise = new TaskCompletionSource();
if (eventLoop.InEventLoop)
{
this.Register0(promise);
}
else
{
try
{
eventLoop.Execute(() => this.Register0(promise));
}
catch (Exception ex)
{
ChannelEventSource.Log.Warning(
string.Format("Force-closing a channel whose registration task was not accepted by an event loop: {0}", this.channel),
ex);
this.CloseForcibly();
this.channel.closeFuture.Complete();
Util.SafeSetFailure(promise, ex);
}
}
return promise.Task;
}
void Register0(TaskCompletionSource promise)
{
try
{
// check if the channel is still open as it could be closed input the mean time when the register
// call was outside of the eventLoop
if (!promise.setUncancellable() || !this.EnsureOpen(promise))
{
Util.SafeSetFailure(promise, ClosedChannelException);
return;
}
bool firstRegistration = this.neverRegistered;
this.channel.DoRegister();
this.neverRegistered = false;
this.channel.registered = true;
this.channel.eventLoop.AcceptNewTasks();
Util.SafeSetSuccess(promise);
this.channel.pipeline.FireChannelRegistered();
// Only fire a channelActive if the channel has never been registered. This prevents firing
// multiple channel actives if the channel is deregistered and re-registered.
if (firstRegistration && this.channel.Active)
{
this.channel.pipeline.FireChannelActive();
}
}
catch (Exception t)
{
// Close the channel directly to avoid FD leak.
this.CloseForcibly();
this.channel.closeFuture.Complete();
Util.SafeSetFailure(promise, t);
}
}
public Task BindAsync(EndPoint localAddress)
{
// todo: cancellation support
if ( /*!promise.setUncancellable() || */!this.channel.Open)
{
return this.CreateClosedChannelExceptionTask();
}
//// See: https://github.com/netty/netty/issues/576
//if (bool.TrueString.Equals(this.channel.Configuration.getOption(ChannelOption.SO_BROADCAST)) &&
// localAddress is IPEndPoint &&
// !((IPEndPoint)localAddress).Address.getAddress().isAnyLocalAddress() &&
// !Environment.OSVersion.Platform == PlatformID.Win32NT && !Environment.isRoot())
//{
// // Warn a user about the fact that a non-root user can't receive a
// // broadcast packet on *nix if the socket is bound on non-wildcard address.
// logger.warn(
// "A non-root user can't receive a broadcast packet if the socket " +
// "is not bound to a wildcard address; binding to a non-wildcard " +
// "address (" + localAddress + ") anyway as requested.");
//}
bool wasActive = this.channel.Active;
var promise = new TaskCompletionSource();
try
{
this.channel.DoBind(localAddress);
}
catch (Exception t)
{
Util.SafeSetFailure(promise, t);
this.CloseIfClosed();
return promise.Task;
}
if (!wasActive && this.channel.Active)
{
this.InvokeLater(() => this.channel.pipeline.FireChannelActive());
}
this.SafeSetSuccess(promise);
return promise.Task;
}
public abstract Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress);
void SafeSetFailure(TaskCompletionSource promise, Exception cause)
{
Util.SafeSetFailure(promise, cause);
}
public Task DisconnectAsync()
{
var promise = new TaskCompletionSource();
if (!promise.setUncancellable())
{
return promise.Task;
}
bool wasActive = this.channel.Active;
try
{
this.channel.DoDisconnect();
}
catch (Exception t)
{
this.SafeSetFailure(promise, t);
this.CloseIfClosed();
return promise.Task;
}
if (wasActive && !this.channel.Active)
{
this.InvokeLater(() => this.channel.pipeline.FireChannelInactive());
}
this.SafeSetSuccess(promise);
this.CloseIfClosed(); // doDisconnect() might have closed the channel
return promise.Task;
}
void SafeSetSuccess(TaskCompletionSource promise)
{
Util.SafeSetSuccess(promise);
}
public Task CloseAsync() //CancellationToken cancellationToken)
{
var promise = new TaskCompletionSource();
if (!promise.setUncancellable())
{
return promise.Task;
}
//if (cancellationToken.IsCancellationRequested)
//{
// return TaskEx.Cancelled;
//}
if (this.outboundBuffer == null)
{
// Only needed if no VoidChannelPromise.
if (promise != TaskCompletionSource.Void)
{
// This means close() was called before so we just register a listener and return
return this.channel.closeFuture.Task;
}
return promise.Task;
}
if (this.channel.closeFuture.Task.IsCompleted)
{
// Closed already.
Util.SafeSetSuccess(promise);
return promise.Task;
}
bool wasActive = this.channel.Active;
ChannelOutboundBuffer buffer = this.outboundBuffer;
this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer.
IEventExecutor closeExecutor = null; // todo closeExecutor();
if (closeExecutor != null)
{
closeExecutor.Execute(() =>
{
try
{
// Execute the close.
this.DoClose0(promise);
}
finally
{
// Call invokeLater so closeAndDeregister is executed input the EventLoop again!
this.InvokeLater(() =>
{
// Fail all the queued messages
buffer.FailFlushed(ClosedChannelException,
false);
buffer.Close(ClosedChannelException);
this.FireChannelInactiveAndDeregister(wasActive);
});
}
});
}
else
{
try
{
// Close the channel and fail the queued messages input all cases.
this.DoClose0(promise);
}
finally
{
// Fail all the queued messages.
buffer.FailFlushed(ClosedChannelException, false);
buffer.Close(ClosedChannelException);
}
if (this.inFlush0)
{
this.InvokeLater(() => this.FireChannelInactiveAndDeregister(wasActive));
}
else
{
this.FireChannelInactiveAndDeregister(wasActive);
}
}
return promise.Task;
}
void DoClose0(TaskCompletionSource promise)
{
try
{
this.channel.DoClose();
this.channel.closeFuture.Complete();
this.SafeSetSuccess(promise);
}
catch (Exception t)
{
this.channel.closeFuture.Complete();
this.SafeSetFailure(promise, t);
}
}
void FireChannelInactiveAndDeregister(bool wasActive)
{
if (wasActive && !this.channel.Active)
{
this.InvokeLater(() =>
{
this.channel.pipeline.FireChannelInactive();
this.DeregisterAsync();
});
}
else
{
this.InvokeLater(() => this.DeregisterAsync());
}
}
public void CloseForcibly()
{
try
{
this.channel.DoClose();
}
catch (Exception e)
{
ChannelEventSource.Log.Warning("Failed to close a channel.", e);
}
}
/// <summary>
/// This method must NEVER be called directly, but be executed as an
/// extra task with a clean call stack instead. The reason for this
/// is that this method calls {@link ChannelPipeline#fireChannelUnregistered()}
/// directly, which might lead to an unfortunate nesting of independent inbound/outbound
/// events. See the comments input {@link #invokeLater(Runnable)} for more details.
/// </summary>
public Task DeregisterAsync()
{
//if (!promise.setUncancellable())
//{
// return;
//}
if (!this.channel.registered)
{
return TaskEx.Completed;
}
try
{
this.channel.DoDeregister();
}
catch (Exception t)
{
ChannelEventSource.Log.Warning("Unexpected exception occurred while deregistering a channel.", t);
return TaskEx.FromException(t);
}
finally
{
if (this.channel.registered)
{
this.channel.registered = false;
this.channel.pipeline.FireChannelUnregistered();
}
else
{
// Some transports like local and AIO does not allow the deregistration of
// an open channel. Their doDeregister() calls close(). Consequently,
// close() calls deregister() again - no need to fire channelUnregistered.
}
}
return TaskEx.Completed;
}
public void BeginRead()
{
if (!this.channel.Active)
{
return;
}
try
{
this.channel.DoBeginRead();
}
catch (Exception e)
{
this.InvokeLater(() => this.channel.pipeline.FireExceptionCaught(e));
this.CloseAsync();
}
}
public Task WriteAsync(object msg)
{
ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null)
{
// If the outboundBuffer is null we know the channel was closed and so
// need to fail the future right away. If it is not null the handling of the rest
// will be done input flush0()
// See https://github.com/netty/netty/issues/2362
// release message now to prevent resource-leak
ReferenceCountUtil.Release(msg);
return TaskEx.FromException(ClosedChannelException);
}
int size;
try
{
msg = this.channel.FilterOutboundMessage(msg);
size = this.channel.EstimatorHandle.Size(msg);
if (size < 0)
{
size = 0;
}
}
catch (Exception t)
{
ReferenceCountUtil.Release(msg);
return TaskEx.FromException(t);
}
var promise = new TaskCompletionSource();
outboundBuffer.AddMessage(msg, size, promise);
return promise.Task;
}
public void Flush()
{
ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null)
{
return;
}
outboundBuffer.AddFlush();
this.Flush0();
}
protected virtual void Flush0()
{
if (this.inFlush0)
{
// Avoid re-entrance
return;
}
ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null || outboundBuffer.IsEmpty)
{
return;
}
this.inFlush0 = true;
// Mark all pending write requests as failure if the channel is inactive.
if (!this.channel.Active)
{
try
{
if (this.channel.Open)
{
outboundBuffer.FailFlushed(NotYetConnectedException, true);
}
else
{
// Do not trigger channelWritabilityChanged because the channel is closed already.
outboundBuffer.FailFlushed(ClosedChannelException, false);
}
}
finally
{
this.inFlush0 = false;
}
return;
}
try
{
this.channel.DoWrite(outboundBuffer);
}
catch (Exception t)
{
outboundBuffer.FailFlushed(t, true);
}
finally
{
this.inFlush0 = false;
}
}
protected bool EnsureOpen(TaskCompletionSource promise)
{
if (this.channel.Open)
{
return true;
}
Util.SafeSetFailure(promise, ClosedChannelException);
return false;
}
protected Task CreateClosedChannelExceptionTask()
{
return TaskEx.FromException(ClosedChannelException);
}
protected void CloseIfClosed()
{
if (this.channel.Open)
{
return;
}
this.CloseAsync();
}
void InvokeLater(Action task)
{
try
{
// This method is used by outbound operation implementations to trigger an inbound event later.
// They do not trigger an inbound event immediately because an outbound operation might have been
// triggered by another inbound event handler method. If fired immediately, the call stack
// will look like this for example:
//
// handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection.
// -> handlerA.ctx.close()
// -> channel.unsafe.close()
// -> handlerA.channelInactive() - (2) another inbound handler method called while input (1) yet
//
// which means the execution of two inbound handler methods of the same handler overlap undesirably.
this.channel.EventLoop.Execute(task);
}
catch (RejectedExecutionException e)
{
ChannelEventSource.Log.Warning("Can't invoke task later as EventLoop rejected it", e);
}
}
protected Exception AnnotateConnectException(Exception exception, EndPoint remoteAddress)
{
if (exception is SocketException)
{
return new ConnectException("LogError connecting to " + remoteAddress, exception);
}
return exception;
}
// /// <summary>
//* @return {@link EventLoop} to execute {@link #doClose()} or {@code null} if it should be done input the
//* {@link EventLoop}.
//+
///// </summary>
// protected IEventExecutor closeExecutor()
// {
// return null;
// }
}
/// <summary>
/// Return {@code true} if the given {@link EventLoop} is compatible with this instance.
/// </summary>
protected abstract bool IsCompatible(IEventLoop eventLoop);
/// <summary>
/// Is called after the {@link Channel} is registered with its {@link EventLoop} as part of the register process.
///
/// Sub-classes may override this method
/// </summary>
protected virtual void DoRegister()
{
// NOOP
}
/// <summary>
/// Bind the {@link Channel} to the {@link EndPoint}
/// </summary>
protected abstract void DoBind(EndPoint localAddress);
/// <summary>
/// Disconnect this {@link Channel} from its remote peer
/// </summary>
protected abstract void DoDisconnect();
/// <summary>
/// Close the {@link Channel}
/// </summary>
protected abstract void DoClose();
/// <summary>
/// Deregister the {@link Channel} from its {@link EventLoop}.
///
/// Sub-classes may override this method
/// </summary>
protected virtual void DoDeregister()
{
// NOOP
}
/// <summary>
/// Schedule a read operation.
/// </summary>
protected abstract void DoBeginRead();
/// <summary>
/// Flush the content of the given buffer to the remote peer.
/// </summary>
protected abstract void DoWrite(ChannelOutboundBuffer input);
/// <summary>
/// Invoked when a new message is added to a {@link ChannelOutboundBuffer} of this {@link AbstractChannel}, so that
/// the {@link Channel} implementation converts the message to another. (e.g. heap buffer -> direct buffer)
/// </summary>
protected virtual object FilterOutboundMessage(object msg)
{
return msg;
}
sealed class PausableChannelEventLoop : PausableChannelEventExecutor, IEventLoop
{
volatile bool isAcceptingNewTasks = true;
public volatile IEventLoop Unwrapped;
readonly IChannel channel;
public PausableChannelEventLoop(IChannel channel, IEventLoop unwrapped)
{
this.channel = channel;
this.Unwrapped = unwrapped;
}
public override void RejectNewTasks()
{
this.isAcceptingNewTasks = false;
}
public override void AcceptNewTasks()
{
this.isAcceptingNewTasks = true;
}
public override bool IsAcceptingNewTasks
{
get { return this.isAcceptingNewTasks; }
}
public override IEventExecutor Unwrap()
{
return this.Unwrapped;
}
IEventLoop IEventLoop.Unwrap()
{
return this.Unwrapped;
}
public IChannelHandlerInvoker Invoker
{
get { return this.Unwrapped.Invoker; }
}
public Task RegisterAsync(IChannel c)
{
return this.Unwrapped.RegisterAsync(c);
}
internal override IChannel Channel
{
get { return this.channel; }
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using System;
using System.Collections.Generic;
using System.Threading;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// Special collection that is optimized for tracking unacknowledged packets
/// </summary>
public sealed class UnackedPacketCollection
{
/// <summary>
/// Holds information about a pending acknowledgement
/// </summary>
private struct PendingAck
{
/// <summary>Sequence number of the packet to remove</summary>
public uint SequenceNumber;
/// <summary>Environment.TickCount value when the remove was queued.
/// This is used to update round-trip times for packets</summary>
public int RemoveTime;
/// <summary>Whether or not this acknowledgement was attached to a
/// resent packet. If so, round-trip time will not be calculated</summary>
public bool FromResend;
public PendingAck(uint sequenceNumber, int currentTime, bool fromResend)
{
SequenceNumber = sequenceNumber;
RemoveTime = currentTime;
FromResend = fromResend;
}
}
/// <summary>Holds the actual unacked packet data, sorted by sequence number</summary>
private Dictionary<uint, OutgoingPacket> m_packets = new Dictionary<uint, OutgoingPacket>();
/// <summary>Holds packets that need to be added to the unacknowledged list</summary>
private LocklessQueue<OutgoingPacket> m_pendingAdds = new LocklessQueue<OutgoingPacket>();
/// <summary>Holds information about pending acknowledgements</summary>
private LocklessQueue<PendingAck> m_pendingAcknowledgements = new LocklessQueue<PendingAck>();
/// <summary>Holds information about pending removals</summary>
private LocklessQueue<uint> m_pendingRemoves = new LocklessQueue<uint>();
/// <summary>
/// Add an unacked packet to the collection
/// </summary>
/// <param name="packet">Packet that is awaiting acknowledgement</param>
/// <returns>True if the packet was successfully added, false if the
/// packet already existed in the collection</returns>
/// <remarks>This does not immediately add the ACK to the collection,
/// it only queues it so it can be added in a thread-safe way later</remarks>
public void Add(OutgoingPacket packet)
{
m_pendingAdds.Enqueue(packet);
Interlocked.Add(ref packet.Client.UnackedBytes, packet.Buffer.DataLength);
}
/// <summary>
/// Marks a packet as acknowledged
/// This method is used when an acknowledgement is received from the network for a previously
/// sent packet. Effects of removal this way are to update unacked byte count, adjust RTT
/// and increase throttle to the coresponding client.
/// </summary>
/// <param name="sequenceNumber">Sequence number of the packet to
/// acknowledge</param>
/// <param name="currentTime">Current value of Environment.TickCount</param>
/// <remarks>This does not immediately acknowledge the packet, it only
/// queues the ack so it can be handled in a thread-safe way later</remarks>
public void Acknowledge(uint sequenceNumber, int currentTime, bool fromResend)
{
m_pendingAcknowledgements.Enqueue(new PendingAck(sequenceNumber, currentTime, fromResend));
}
/// <summary>
/// Marks a packet as no longer needing acknowledgement without a received acknowledgement.
/// This method is called when a packet expires and we no longer need an acknowledgement.
/// When some reliable packet types expire, they are handled in a way other than simply
/// resending them. The only effect of removal this way is to update unacked byte count.
/// </summary>
/// <param name="sequenceNumber">Sequence number of the packet to
/// acknowledge</param>
/// <remarks>The does not immediately remove the packet, it only queues the removal
/// so it can be handled in a thread safe way later</remarks>
public void Remove(uint sequenceNumber)
{
m_pendingRemoves.Enqueue(sequenceNumber);
}
/// <summary>
/// Returns a list of all of the packets with a TickCount older than
/// the specified timeout
/// </summary>
/// <remarks>
/// This function is not thread safe, and cannot be called
/// multiple times concurrently
/// </remarks>
/// <param name="timeoutMS">Number of ticks (milliseconds) before a
/// packet is considered expired
/// </param>
/// <returns>
/// A list of all expired packets according to the given
/// expiration timeout
/// </returns>
public List<OutgoingPacket> GetExpiredPackets(int timeoutMS)
{
ProcessQueues();
List<OutgoingPacket> expiredPackets = null;
if (m_packets.Count > 0)
{
int now = Environment.TickCount & Int32.MaxValue;
foreach (OutgoingPacket packet in m_packets.Values)
{
// TickCount of zero means a packet is in the resend queue
// but hasn't actually been sent over the wire yet
if (packet.TickCount == 0)
continue;
if (now - packet.TickCount >= timeoutMS)
{
if (expiredPackets == null)
expiredPackets = new List<OutgoingPacket>();
// The TickCount will be set to the current time when the packet
// is actually sent out again
packet.TickCount = 0;
// As with other network applications, assume that an expired packet is
// an indication of some network problem, slow transmission
packet.Client.FlowThrottle.ExpirePackets(1);
expiredPackets.Add(packet);
}
}
}
//if (expiredPackets != null)
// m_log.DebugFormat("[UNACKED PACKET COLLECTION]: Found {0} expired packets on timeout of {1}", expiredPackets.Count, timeoutMS);
return expiredPackets;
}
private void ProcessQueues()
{
// Process all the pending adds
OutgoingPacket pendingAdd;
while (m_pendingAdds.TryDequeue(out pendingAdd))
if (pendingAdd != null)
m_packets[pendingAdd.SequenceNumber] = pendingAdd;
// Process all the pending removes, including updating statistics and round-trip times
PendingAck pendingAcknowledgement;
while (m_pendingAcknowledgements.TryDequeue(out pendingAcknowledgement))
{
//m_log.DebugFormat("[UNACKED PACKET COLLECTION]: Processing ack {0}", pendingAcknowledgement.SequenceNumber);
OutgoingPacket ackedPacket;
if (m_packets.TryGetValue(pendingAcknowledgement.SequenceNumber, out ackedPacket))
{
if (ackedPacket != null)
{
m_packets.Remove(pendingAcknowledgement.SequenceNumber);
// As with other network applications, assume that an acknowledged packet is an
// indication that the network can handle a little more load, speed up the transmission
ackedPacket.Client.FlowThrottle.AcknowledgePackets(ackedPacket.Buffer.DataLength);
// Update stats
Interlocked.Add(ref ackedPacket.Client.UnackedBytes, -ackedPacket.Buffer.DataLength);
if (!pendingAcknowledgement.FromResend)
{
// Calculate the round-trip time for this packet and its ACK
int rtt = pendingAcknowledgement.RemoveTime - ackedPacket.TickCount;
if (rtt > 0)
ackedPacket.Client.UpdateRoundTrip(rtt);
}
}
else
{
//m_log.WarnFormat("[UNACKED PACKET COLLECTION]: Could not find packet with sequence number {0} to ack", pendingAcknowledgement.SequenceNumber);
}
}
}
uint pendingRemove;
while(m_pendingRemoves.TryDequeue(out pendingRemove))
{
OutgoingPacket removedPacket;
if (m_packets.TryGetValue(pendingRemove, out removedPacket))
{
if (removedPacket != null)
{
m_packets.Remove(pendingRemove);
// Update stats
Interlocked.Add(ref removedPacket.Client.UnackedBytes, -removedPacket.Buffer.DataLength);
}
}
}
}
}
}
| |
using UnityEngine;
namespace UnityStandardAssets.Characters.ThirdPerson
{
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(Animator))]
public class ThirdPersonCharacter : MonoBehaviour
{
[SerializeField] float m_MovingTurnSpeed = 360;
[SerializeField] float m_StationaryTurnSpeed = 180;
[SerializeField] float m_JumpPower = 12f;
[Range(1f, 4f)][SerializeField] float m_GravityMultiplier = 2f;
[SerializeField] float m_RunCycleLegOffset = 0.2f; //specific to the character in sample assets, will need to be modified to work with others
[SerializeField] float m_MoveSpeedMultiplier = 1f;
[SerializeField] float m_AnimSpeedMultiplier = 1f;
[SerializeField] float m_GroundCheckDistance = 0.1f;
Rigidbody m_Rigidbody;
Animator m_Animator;
bool m_IsGrounded;
float m_OrigGroundCheckDistance;
const float k_Half = 0.5f;
float m_TurnAmount;
float m_ForwardAmount;
Vector3 m_GroundNormal;
float m_CapsuleHeight;
Vector3 m_CapsuleCenter;
CapsuleCollider m_Capsule;
bool m_Crouching;
void Start()
{
m_Animator = GetComponent<Animator>();
m_Rigidbody = GetComponent<Rigidbody>();
m_Capsule = GetComponent<CapsuleCollider>();
m_CapsuleHeight = m_Capsule.height;
m_CapsuleCenter = m_Capsule.center;
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
m_OrigGroundCheckDistance = m_GroundCheckDistance;
}
public void Move(Vector3 move, bool crouch, bool jump)
{
// convert the world relative moveInput vector into a local-relative
// turn amount and forward amount required to head in the desired
// direction.
if (move.magnitude > 1f) move.Normalize();
move = transform.InverseTransformDirection(move);
CheckGroundStatus();
move = Vector3.ProjectOnPlane(move, m_GroundNormal);
m_TurnAmount = Mathf.Atan2(move.x, move.z);
m_ForwardAmount = move.z;
ApplyExtraTurnRotation();
// control and velocity handling is different when grounded and airborne:
if (m_IsGrounded)
{
HandleGroundedMovement(crouch, jump);
}
else
{
HandleAirborneMovement();
}
ScaleCapsuleForCrouching(crouch);
PreventStandingInLowHeadroom();
// send input and other state parameters to the animator
UpdateAnimator(move);
}
void ScaleCapsuleForCrouching(bool crouch)
{
if (m_IsGrounded && crouch)
{
if (m_Crouching) return;
m_Capsule.height = m_Capsule.height / 2f;
m_Capsule.center = m_Capsule.center / 2f;
m_Crouching = true;
}
else
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
return;
}
m_Capsule.height = m_CapsuleHeight;
m_Capsule.center = m_CapsuleCenter;
m_Crouching = false;
}
}
void PreventStandingInLowHeadroom()
{
// prevent standing up in crouch-only zones
if (!m_Crouching)
{
Ray crouchRay = new Ray(m_Rigidbody.position + Vector3.up * m_Capsule.radius * k_Half, Vector3.up);
float crouchRayLength = m_CapsuleHeight - m_Capsule.radius * k_Half;
if (Physics.SphereCast(crouchRay, m_Capsule.radius * k_Half, crouchRayLength, ~0, QueryTriggerInteraction.Ignore))
{
m_Crouching = true;
}
}
}
void UpdateAnimator(Vector3 move)
{
// update the animator parameters
m_Animator.SetFloat("Forward", m_ForwardAmount, 0.1f, Time.deltaTime);
m_Animator.SetFloat("Turn", m_TurnAmount, 0.1f, Time.deltaTime);
m_Animator.SetBool("Crouch", m_Crouching);
m_Animator.SetBool("OnGround", m_IsGrounded);
if (!m_IsGrounded)
{
m_Animator.SetFloat("Jump", m_Rigidbody.velocity.y);
}
// calculate which leg is behind, so as to leave that leg trailing in the jump animation
// (This code is reliant on the specific run cycle offset in our animations,
// and assumes one leg passes the other at the normalized clip times of 0.0 and 0.5)
float runCycle =
Mathf.Repeat(
m_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime + m_RunCycleLegOffset, 1);
float jumpLeg = (runCycle < k_Half ? 1 : -1) * m_ForwardAmount;
if (m_IsGrounded)
{
m_Animator.SetFloat("JumpLeg", jumpLeg);
}
// the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector,
// which affects the movement speed because of the root motion.
if (m_IsGrounded && move.magnitude > 0)
{
m_Animator.speed = m_AnimSpeedMultiplier;
}
else
{
// don't use that while airborne
m_Animator.speed = 1;
}
}
void HandleAirborneMovement()
{
// apply extra gravity from multiplier:
Vector3 extraGravityForce = (Physics.gravity * m_GravityMultiplier) - Physics.gravity;
m_Rigidbody.AddForce(extraGravityForce);
m_GroundCheckDistance = m_Rigidbody.velocity.y < 0 ? m_OrigGroundCheckDistance : 0.01f;
}
void HandleGroundedMovement(bool crouch, bool jump)
{
// check whether conditions are right to allow a jump:
if (jump && !crouch && m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Grounded"))
{
// jump!
m_Rigidbody.velocity = new Vector3(m_Rigidbody.velocity.x, m_JumpPower, m_Rigidbody.velocity.z);
m_IsGrounded = false;
m_Animator.applyRootMotion = false;
m_GroundCheckDistance = 0.1f;
}
}
void ApplyExtraTurnRotation()
{
// help the character turn faster (this is in addition to root rotation in the animation)
float turnSpeed = Mathf.Lerp(m_StationaryTurnSpeed, m_MovingTurnSpeed, m_ForwardAmount);
transform.Rotate(0, m_TurnAmount * turnSpeed * Time.deltaTime, 0);
}
public void OnAnimatorMove()
{
// we implement this function to override the default root motion.
// this allows us to modify the positional speed before it's applied.
if (m_IsGrounded && Time.deltaTime > 0)
{
Vector3 v = (m_Animator.deltaPosition * m_MoveSpeedMultiplier) / Time.deltaTime;
// we preserve the existing y part of the current velocity.
v.y = m_Rigidbody.velocity.y;
m_Rigidbody.velocity = v;
}
}
void CheckGroundStatus()
{
RaycastHit hitInfo;
#if UNITY_EDITOR
// helper to visualise the ground check ray in the scene view
Debug.DrawLine(transform.position + (Vector3.up * 0.1f), transform.position + (Vector3.up * 0.1f) + (Vector3.down * m_GroundCheckDistance));
#endif
// 0.1f is a small offset to start the ray from inside the character
// it is also good to note that the transform position in the sample assets is at the base of the character
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, m_GroundCheckDistance))
{
m_GroundNormal = hitInfo.normal;
m_IsGrounded = true;
m_Animator.applyRootMotion = true;
}
else
{
m_IsGrounded = false;
m_GroundNormal = Vector3.up;
m_Animator.applyRootMotion = false;
}
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using Abc.Zebus.Util;
using ProtoBuf;
namespace Abc.Zebus.Serialization.Protobuf
{
internal sealed class ProtoBufferReader
{
private readonly byte[] _guidBuffer = new byte[16];
private readonly byte[] _buffer;
private readonly int _size;
private int _position;
public ProtoBufferReader(byte[] buffer, int length)
{
_buffer = buffer;
_size = length;
}
public int Position => _position;
public int Length => _size;
public void Reset() => _position = 0;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanRead(int length) => _size - _position >= length;
public bool TryReadTag(out uint number, out WireType wireType)
{
if (!TryReadTag(out var tag))
{
number = 0;
wireType = WireType.None;
return false;
}
number = tag >> 3;
wireType = (WireType)(tag & 7);
return true;
}
public bool TryReadTag(out uint value)
{
if (!CanRead(1))
{
value = default;
return false;
}
var tag = _buffer[_position];
if (tag < 128)
{
_position++;
value = tag;
return value != 0;
}
return TryReadRawVariant(out value);
}
public bool TryReadFixed64(out ulong value)
{
return TryReadRawLittleEndian64(out value);
}
public bool TryReadFixed32(out uint value)
{
return TryReadRawLittleEndian32(out value);
}
public bool TryReadBool(out bool value)
{
var success = TryReadRawVariant(out var variant);
value = variant != 0;
return success;
}
public bool TryReadString(out string? s)
{
if (!TryReadLength(out var length) || !CanRead(length))
{
s = default;
return false;
}
if (length == 0)
{
s = "";
return true;
}
var result = ProtoBufferWriter.Utf8Encoding.GetString(_buffer, _position, length);
_position += length;
s = result;
return true;
}
public bool TrySkipString()
{
if (!TryReadLength(out var length) || !CanRead(length))
return false;
_position += length;
return true;
}
public bool TryReadGuid(out Guid value)
{
if (!TryReadLength(out var length) || !CanRead(length) || length != ProtoBufferWriter.GuidSize)
return false;
// Skip tag
ByteUtil.Copy(_buffer, _position + 1, _guidBuffer, 0, 8);
// Skip tag
ByteUtil.Copy(_buffer, _position + 10, _guidBuffer, 8, 8);
_position += ProtoBufferWriter.GuidSize;
value = new Guid(_guidBuffer);
return true;
}
public bool TryReadLength(out int length)
{
var success = TryReadRawVariant(out var variant);
length = (int)variant;
return success;
}
internal bool TryReadRawVariant(out uint value)
{
var available = _size - _position;
if (available <= 0)
{
value = default;
return false;
}
value = _buffer[_position++];
if ((value & 0x80) == 0)
return true;
value &= 0x7F;
if (available == 1)
return false;
uint chunk = _buffer[_position++];
value |= (chunk & 0x7F) << 7;
if ((chunk & 0x80) == 0)
return true;
if (available == 2)
return false;
chunk = _buffer[_position++];
value |= (chunk & 0x7F) << 14;
if ((chunk & 0x80) == 0)
return true;
if (available == 3)
return false;
chunk = _buffer[_position++];
value |= (chunk & 0x7F) << 21;
if ((chunk & 0x80) == 0)
return true;
return false;
}
private bool TryReadRawLittleEndian32(out uint value)
{
if (!CanRead(4))
{
value = default;
return false;
}
uint b1 = _buffer[_position++];
uint b2 = _buffer[_position++];
uint b3 = _buffer[_position++];
uint b4 = _buffer[_position++];
value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
return true;
}
/// <summary>
/// Reads a 64-bit little-endian integer from the stream.
/// </summary>
private bool TryReadRawLittleEndian64(out ulong value)
{
if (!CanRead(8))
{
value = default;
return false;
}
ulong b1 = _buffer[_position++];
ulong b2 = _buffer[_position++];
ulong b3 = _buffer[_position++];
ulong b4 = _buffer[_position++];
ulong b5 = _buffer[_position++];
ulong b6 = _buffer[_position++];
ulong b7 = _buffer[_position++];
ulong b8 = _buffer[_position++];
value = b1 | (b2 << 8) | (b3 << 16) | (b4 << 24) | (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
return true;
}
internal bool TryReadRawBytes(int size, out byte[] value)
{
if (size < 0 || !CanRead(size))
{
value = Array.Empty<byte>();
return false;
}
value = new byte[size];
ByteUtil.Copy(_buffer, _position, value, 0, size);
_position += size;
return true;
}
public string ToDebugString(int byteLength)
{
return _size <= byteLength
? Convert.ToBase64String(_buffer, 0, _size)
: Convert.ToBase64String(_buffer, 0, byteLength) + "...";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Claudy.Input;
namespace Cliffhanger
{
public class LevelTwo : Microsoft.Xna.Framework.GameComponent
{
//Viewport stuff
RenderTarget2D topScreen;
RenderTarget2D bottomScreen;
int bottomOffset;
//Cliff
Texture2D cliffTex;
Rectangle cliffRect;
Vector2 offsetTop;
Vector2 offsetBottom;
//Screen Player stuff
Vector2 p1ScreenPos, p2ScreenPos;
Vector2 p1ScreenVel, p2ScreenVel;
Texture2D test;
Boolean screenSplit;
Color p1, p2;
Rectangle playerBounds;
//Player Stuff
Player player1;
Player player2;
//Platform
List<Platform> platforms;
Platform ground;
//Rock
List<Rock> rocks;
//Vine
List<Vine> vines;
//Rock Machine
RockMachine guitar;
const int FINISH = -3180;
public bool isCompleted;
public int victorPlayerNum;
//Audio Effects
SoundEffect victorySound;
SoundEffect jumpSound;
GraphicsDevice GraphicsDevice;
SpriteFont font;
public LevelTwo(Game game)
: base(game)
{
}
public void Initialize(GraphicsDevice gd)
{
jumpSound = Game.Content.Load<SoundEffect>("Jump");
GraphicsDevice = gd;
topScreen = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height / 2);
bottomScreen = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height / 2);
offsetTop = Vector2.Zero;
offsetBottom = new Vector2(0, -topScreen.Height);
//Player
player1 = new Player(Game, 1, jumpSound);
player1.Initialize();
player1.position = new Vector2(100, 0);
player2 = new Player(Game, 2, jumpSound);
player2.Initialize();
player2.position = new Vector2(400, 0);
//Platform
platforms = new List<Platform>();
ground = new Platform(Game, -20, 400, 2000, 1000);
ground.Initialize();
platforms.Add(ground);
//Screen Representation of players
p1ScreenPos = new Vector2(100, 20);
p2ScreenPos = new Vector2(GraphicsDevice.Viewport.Width - 100, 20);
p1ScreenVel = new Vector2(0, 0);
p2ScreenVel = new Vector2(0, 0);
//changes the screen bounds of where the player is.
playerBounds = new Rectangle(0, 0, 10, 60);
screenSplit = false;
p1 = Color.Red;
p2 = Color.Blue;
//Rock
rocks = new List<Rock>();
//Guitar (Rock Machine)
guitar = new RockMachine(Game, 700, 200);
//Vine
vines = new List<Vine>();
//vines.Add(new Vine(Game, -128, 11, 0)); // (Game, Position Y, Height/32, Lane)
vines.Add(new Vine(Game, 96, 9, 5)); // Ground is some where about 224 .
vines.Add(new Vine(Game, 256, 2, 1));
vines.Add(new Vine(Game, -32, 8, 2));
vines.Add(new Vine(Game, -160, 11, 4));
vines.Add(new Vine(Game, 0, 2, 6));
vines.Add(new Vine(Game, -96, 2, 7));
vines.Add(new Vine(Game, -480, 12, 5));
vines.Add(new Vine(Game, -576, 8, 7));
vines.Add(new Vine(Game, -320, 5, 3));
vines.Add(new Vine(Game, -256, 7, 1));
vines.Add(new Vine(Game, -544, 4, 6));
vines.Add(new Vine(Game, -608, 9, 1));
vines.Add(new Vine(Game, -768, 6, 2));
vines.Add(new Vine(Game, -768, 1, 3));
vines.Add(new Vine(Game, -736, 5, 1));
vines.Add(new Vine(Game, -960, 2, 0));
//Over 1000
vines.Add(new Vine(Game, -1024, 15, 5));
vines.Add(new Vine(Game, -1056, 6, 3));
vines.Add(new Vine(Game, -1120, 4, 4));
vines.Add(new Vine(Game, -1152, 6, 7));
vines.Add(new Vine(Game, -1216, 4, 1));
vines.Add(new Vine(Game, -1248, 2, 7));
vines.Add(new Vine(Game, -1344, 2, 7));
vines.Add(new Vine(Game, -1440, 1, 7));
///
vines.Add(new Vine(Game, -1280, 3, 6));
vines.Add(new Vine(Game, -1344, 3, 5));
vines.Add(new Vine(Game, -1312, 3, 4));
vines.Add(new Vine(Game, -1280, 5, 3));
vines.Add(new Vine(Game, -1344, 4, 2));
vines.Add(new Vine(Game, -1280, 4, 1));
//vines.Add(new Vine(Game, -1248, 7, 0));
//After 1400
vines.Add(new Vine(Game, -1440, 2, 6));
vines.Add(new Vine(Game, -1504, 1, 2));
vines.Add(new Vine(Game, -1536, 2, 5));
vines.Add(new Vine(Game, -1568, 1, 4));
vines.Add(new Vine(Game, -1600, 1, 3));
vines.Add(new Vine(Game, -1664, 1, 4));
vines.Add(new Vine(Game, -1952, 7, 4));
vines.Add(new Vine(Game, -2016, 8, 1));
vines.Add(new Vine(Game, -1824, 6, 2));
//After 2000
vines.Add(new Vine(Game, -2016, 4, 4));
vines.Add(new Vine(Game, -2112, 4, 2));
vines.Add(new Vine(Game, -2176, 3, 3));
vines.Add(new Vine(Game, -2176, 3, 7));
vines.Add(new Vine(Game, -2336, 12, 6));
vines.Add(new Vine(Game, -2464, 4, 7));
vines.Add(new Vine(Game, -2464, 7, 1));
vines.Add(new Vine(Game, -2560, 11, 2));
vines.Add(new Vine(Game, -2560, 3, 6));
vines.Add(new Vine(Game, -2688, 5, 3));
vines.Add(new Vine(Game, -2720, 6, 4));
vines.Add(new Vine(Game, -2784, 5, 5));
vines.Add(new Vine(Game, -2784, 6, 7));
vines.Add(new Vine(Game, -2800, 3, 2));
vines.Add(new Vine(Game, -2848, 3, 6));
vines.Add(new Vine(Game, -2944, 5, 1));
vines.Add(new Vine(Game, -2848, 3, 7));
vines.Add(new Vine(Game, -3008, 4, 2));
vines.Add(new Vine(Game, -3136, 7, 3));
vines.Add(new Vine(Game, -3136, 7, 5));
foreach (Vine vine in vines)
{
vine.Initialize();
}
isCompleted = false;
victorPlayerNum = 0;
base.Initialize();
}
public void LoadContent()
{
cliffTex = Game.Content.Load<Texture2D>("cliff");
cliffRect = new Rectangle(0, GraphicsDevice.Viewport.Height - cliffTex.Height * 2, GraphicsDevice.Viewport.Width * 2, cliffTex.Height * 2);
font = Game.Content.Load<SpriteFont>("Consolas");
test = Game.Content.Load<Texture2D>("blankTex");
victorySound = Game.Content.Load<SoundEffect>("Flashpoint001");
}
public void reset()
{
offsetTop = Vector2.Zero;
offsetBottom = new Vector2(0, -topScreen.Height);
//Player
player1 = new Player(Game, 1, jumpSound);
player1.Initialize();
player1.position = new Vector2(100, 0);
player2 = new Player(Game, 2, jumpSound);
player2.Initialize();
player2.position = new Vector2(400, 0);
//Screen Representation of players
p1ScreenPos = new Vector2(100, 20);
p2ScreenPos = new Vector2(GraphicsDevice.Viewport.Width - 100, 20);
p1ScreenVel = new Vector2(0, 0);
p2ScreenVel = new Vector2(0, 0);
screenSplit = false;
isCompleted = false;
}
public void Update(GameTime gameTime, ClaudyInput input, Rectangle titleSafeRect)
{
ground.Update(gameTime);
#region Platform Collision
foreach (Platform platform in platforms)
{
if (player1.vel.Y >= 0)
{
if (Collision.PlayerPlatformCollision(player1, platform))
{
//state = PlayerState.standing;
player1.canjump = true;
if (!screenSplit)
p1ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetTop.Y;
else
p1ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetBottom.Y + GraphicsDevice.Viewport.Height / 2;
break;
}
else
{
//state = PlayerState.falling;
player1.canjump = false;
}
}
}
foreach (Platform platform in platforms)
{
if (player2.vel.Y >= 0)
{
if (Collision.PlayerPlatformCollision(player2, platform))
{
//state = PlayerState.standing;
player2.canjump = true;
if (!screenSplit)
p2ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetTop.Y;
else
p2ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetBottom.Y + GraphicsDevice.Viewport.Height / 2;
break;
}
else
{
//state = PlayerState.falling;
player2.canjump = false;
}
}
}
#endregion //Platform Collision
foreach (Rock r in rocks)
{
r.Update(gameTime, ground);
}
for (int i = 0; i < rocks.Count; i++)
{
if (!rocks[i].Enabled) // Remove any rocks deemed to be disposed of.
{
rocks.RemoveAt(i);
}
}
#region Rock Machine Collision
if (guitar.IsActive &&
(player1.hitbox.Intersects(guitar.rect) || player2.hitbox.Intersects(guitar.rect)))
{
Random rng = new Random();
for (int i = 0; i < 10; i++)
{
Rock r = new Rock(Game,
(float)rng.Next(1000),
-(float)rng.Next(2500),
Rock.SUGGESTED_UP_R_VELOCITY, 3);
rocks.Add(r);
}
for (int i = 0; i < 10; i++)
{
Rock r = new Rock(Game,
(float)rng.Next(1000),
-(float)rng.Next(2500),
Rock.SUGGESTED_UP_L_VELOCITY, 3);
rocks.Add(r);
}
guitar.Fired(gameTime);
}
guitar.Update(gameTime);
#endregion
#region Vine Collision
foreach (Vine vine in vines)
{
if (Collision.PlayerVineCollision(player1, vine, gameTime) && input.GetAs8DirectionLeftThumbStick(player1.Num).Y > 0)
{
player1.vel.Y = -2f;
player1.vel.X *= .5f;
if (player1.position.Y + player1.hitbox.Height > vine.position.Y && player1.position.Y + player1.hitbox.Height < vine.position.Y + 4)
{
player1.vel.Y = 0;
}
}
if (player1.vel.Y >= 0)
{
if (Collision.PlayerVineCollision(player1, vine, gameTime))
{
//state = PlayerState.standing;
player1.canjump = true;
player1.vel.X *= .5f;
player1.vel.Y = 0;
break;
}
else
{
//state = PlayerState.falling;
//player1.canjump = false;
}
}
}
foreach (Vine vine in vines)
{
if (Collision.PlayerVineCollision(player2, vine, gameTime) && input.GetAs8DirectionLeftThumbStick(player2.Num).Y > 0)
{
player2.vel.Y = -2;
player2.vel.X *= .5f;
if (player2.position.Y + player2.hitbox.Height > vine.position.Y && player2.position.Y + player2.hitbox.Height < vine.position.Y + 4)
{
player2.vel.Y = 0;
}
}
if (player2.vel.Y >= 0)
{
if (Collision.PlayerVineCollision(player2, vine, gameTime))
{
//state = PlayerState.standing;
player2.canjump = true;
player2.vel.X *= .5f;
player2.vel.Y = 0;
break;
}
else
{
//state = PlayerState.falling;
//player1.canjump = false;
}
}
}
#endregion //Vine Collision
//Player updates
player1.Update(gameTime, titleSafeRect);
player2.Update(gameTime, titleSafeRect);
#region Throw Rocks (requires knowledge of player & of the rock list)
//PLAYER 1
if (input.GamepadByID[player1.Num].Triggers.Left > 0.5f &&
input.PreviousGamepadByID[player1.Num].Triggers.Left <= 0.5f)
{
Rock r = new Rock(Game,
player1.hitbox.X, player1.hitbox.Y,
Rock.SUGGESTED_SIDE_L_VELOCITY,
player1.Num);
r.Initialize();
rocks.Add(r);
}
if (input.GamepadByID[player1.Num].Triggers.Right > 0.5f &&
input.PreviousGamepadByID[player1.Num].Triggers.Right <= 0.5f)
{
Rock r = new Rock(Game,
player1.hitbox.X + player1.hitbox.Width, player1.hitbox.Y,
Rock.SUGGESTED_SIDE_R_VELOCITY,
player1.Num);
r.Initialize();
rocks.Add(r);
}
if (input.isFirstPress(Buttons.RightShoulder, player1.Num))
{
Rock r = new Rock(Game,
player1.hitbox.X, player1.hitbox.Y,
Rock.SUGGESTED_UP_R_VELOCITY,
player1.Num);
r.Initialize();
rocks.Add(r);
}
if (input.isFirstPress(Buttons.LeftShoulder, player1.Num))
{
Rock r = new Rock(Game,
player1.hitbox.X + player1.hitbox.Width, player1.hitbox.Y,
Rock.SUGGESTED_UP_L_VELOCITY,
player1.Num);
r.Initialize();
rocks.Add(r);
}
//PLAYER 2
if (input.GamepadByID[player2.Num].Triggers.Left > 0.5f &&
input.PreviousGamepadByID[player2.Num].Triggers.Left <= 0.5f)
{
Rock r = new Rock(Game,
player2.hitbox.X, player2.hitbox.Y,
Rock.SUGGESTED_SIDE_L_VELOCITY,
player2.Num);
r.Initialize();
rocks.Add(r);
}
if (input.GamepadByID[player2.Num].Triggers.Right > 0.5f &&
input.PreviousGamepadByID[player2.Num].Triggers.Right <= 0.5f)
{
Rock r = new Rock(Game,
player2.hitbox.X + player2.hitbox.Width, player2.hitbox.Y,
Rock.SUGGESTED_SIDE_R_VELOCITY,
player2.Num);
r.Initialize();
rocks.Add(r);
}
if (input.isFirstPress(Buttons.RightShoulder, player2.Num))
{
Rock r = new Rock(Game,
player2.hitbox.X, player2.hitbox.Y,
Rock.SUGGESTED_UP_R_VELOCITY,
player2.Num);
r.Initialize();
rocks.Add(r);
}
if (input.isFirstPress(Buttons.LeftShoulder, player2.Num))
{
Rock r = new Rock(Game,
player2.hitbox.X + player2.hitbox.Width, player2.hitbox.Y,
Rock.SUGGESTED_UP_L_VELOCITY,
player2.Num);
r.Initialize();
rocks.Add(r);
}
#endregion
p1ScreenVel.Y = -player1.vel.Y;
p2ScreenVel.Y = -player2.vel.Y;
p1ScreenPos.Y -= p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
p2ScreenPos.Y -= p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
#region splitScreen Movement
if (p1ScreenPos.Y < titleSafeRect.Y + 20)
{
p1ScreenPos.Y = titleSafeRect.Y + 20;
offsetTop.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
if (p2ScreenPos.Y > titleSafeRect.Height - playerBounds.Height - 5)
{
screenSplit = true;
}
if (!screenSplit)
{
p2ScreenPos.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
offsetBottom.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
}
}
if (p2ScreenPos.Y < titleSafeRect.Y + 20)
{
p2ScreenPos.Y = titleSafeRect.Y + 20;
offsetTop.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
if (p1ScreenPos.Y > titleSafeRect.Height - playerBounds.Height - 5 && !screenSplit)
{
screenSplit = true;
}
if (!screenSplit)
{
p1ScreenPos.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
offsetBottom.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
}
}
else if (p2ScreenPos.Y > titleSafeRect.Height - playerBounds.Height)
{
offsetBottom.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
p2ScreenPos.Y = titleSafeRect.Height - playerBounds.Height;
if (p1ScreenPos.Y < titleSafeRect.Y && !screenSplit)
{
screenSplit = true;
}
if (!screenSplit)
{
p1ScreenPos.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
offsetTop.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
}
}
if (p1ScreenPos.Y > titleSafeRect.Height - playerBounds.Height)
{
offsetBottom.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
p1ScreenPos.Y = titleSafeRect.Height - playerBounds.Height;
if (p2ScreenPos.Y < titleSafeRect.Y && !screenSplit)
{
screenSplit = true;
}
if (!screenSplit)
{
p2ScreenPos.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
offsetTop.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
}
}
if (screenSplit)
{
if (p1ScreenPos.Y > GraphicsDevice.Viewport.Height / 2 - playerBounds.Height && p1ScreenPos.Y < GraphicsDevice.Viewport.Height / 2)
{
p1ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 - playerBounds.Height;
offsetTop.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2)
screenSplit = false;
}
if (p2ScreenPos.Y > GraphicsDevice.Viewport.Height / 2 - playerBounds.Height && p2ScreenPos.Y < GraphicsDevice.Viewport.Height / 2)
{
p2ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 - playerBounds.Height;
offsetTop.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2)
screenSplit = false;
}
if (p2ScreenPos.Y < GraphicsDevice.Viewport.Height / 2 + playerBounds.Height && p2ScreenPos.Y > GraphicsDevice.Viewport.Height / 2)
{
p2ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 + playerBounds.Height;
offsetBottom.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2)
screenSplit = false;
}
if (p1ScreenPos.Y < GraphicsDevice.Viewport.Height / 2 + playerBounds.Height && p1ScreenPos.Y > GraphicsDevice.Viewport.Height / 2)
{
p1ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 + playerBounds.Height;
offsetBottom.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f;
if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2)
screenSplit = false;
}
}
if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2)
{
screenSplit = false;
offsetBottom.Y = offsetTop.Y - GraphicsDevice.Viewport.Height / 2;
}
#endregion
#region Rock Collisions
foreach (Rock r in rocks)
{
if (Collision.PlayerRockCollision(player1, r))
{
continue;
}
else
{
Collision.PlayerRockCollision(player2, r);
}
}
#endregion // Rock Collisions
if (player1.position.Y <= FINISH || player2.position.Y <= FINISH)
{
victorySound.Play();
isCompleted = true;
if (player1.position.Y < player2.position.Y)
victorPlayerNum = 1;
else if (player2.position.Y < player1.position.Y)
victorPlayerNum = 2;
}
base.Update(gameTime);
}
public void Draw(SpriteBatch spriteBatch)
{
//Draw stuff in the top renderTarget
GraphicsDevice.SetRenderTarget(topScreen);
GraphicsDevice.Clear(Color.Gray);
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null); // TODO: Change to LinearWrap before submitting to Dr. Birmingham.
#region Top Viewport
{
spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, cliffRect.Y + (int)offsetTop.Y, cliffRect.Width, cliffRect.Height), Color.White);
//Vines
foreach (Vine vine in vines)
{
vine.Draw(spriteBatch, offsetTop);
}
spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, -3160 + (int)offsetTop.Y, cliffRect.Width, 3), Color.LawnGreen);
guitar.Draw(spriteBatch, offsetTop);
player1.Draw(spriteBatch, offsetTop);
player2.Draw(spriteBatch, offsetTop);
ground.Draw(spriteBatch, offsetTop);
foreach (Rock r in rocks)
{
r.Draw(spriteBatch, offsetTop);
}
}
#endregion //Top Viewport
spriteBatch.End();
//Draw stuff in the bottom renderTarget; Use an offset
GraphicsDevice.SetRenderTarget(bottomScreen);
GraphicsDevice.Clear(Color.Gray);
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);
bottomOffset = GraphicsDevice.Viewport.Height;
#region Bottom Viewport
{
spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, cliffRect.Y + (int)offsetBottom.Y, cliffRect.Width, cliffRect.Height), Color.White);
//Vines
foreach (Vine vine in vines)
{
vine.Draw(spriteBatch, offsetBottom);
}
spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, -3160 + (int)offsetBottom.Y, cliffRect.Width, 3), Color.LawnGreen);
guitar.Draw(spriteBatch, offsetBottom);
player1.Draw(spriteBatch, offsetBottom);
player2.Draw(spriteBatch, offsetBottom);
ground.Draw(spriteBatch, offsetBottom);
foreach (Rock r in rocks)
{
r.Draw(spriteBatch, offsetBottom);
}
}
#endregion //Bottom Viewport
spriteBatch.End();
//Draw the renderTargets
GraphicsDevice.SetRenderTarget(null);
spriteBatch.Begin();
spriteBatch.Draw(topScreen, new Vector2(0, 0), Color.White);
spriteBatch.Draw(bottomScreen, new Vector2(0, GraphicsDevice.Viewport.Height / 2), Color.White);
//Debugging draw statements
//spriteBatch.Draw(test, new Rectangle((int)p1ScreenPos.X, (int)p1ScreenPos.Y, playerBounds.Width, playerBounds.Height), p1);
//spriteBatch.Draw(test, new Rectangle((int)p2ScreenPos.X, (int)p2ScreenPos.Y, playerBounds.Width, playerBounds.Height), p2);
//spriteBatch.DrawString(font, "bool: " + player1.canjump.ToString(), new Vector2(0, 0), Color.Black);
//spriteBatch.DrawString(font, "bool: " + player1.vel.ToString(), new Vector2(0, 50), Color.Orange);
//spriteBatch.DrawString(font, player1.position.Y.ToString(), new Vector2(0f, 200f), Color.Yellow);
spriteBatch.End();
}
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="CustomerFeedServiceClient"/> instances.</summary>
public sealed partial class CustomerFeedServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CustomerFeedServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CustomerFeedServiceSettings"/>.</returns>
public static CustomerFeedServiceSettings GetDefault() => new CustomerFeedServiceSettings();
/// <summary>Constructs a new <see cref="CustomerFeedServiceSettings"/> object with default settings.</summary>
public CustomerFeedServiceSettings()
{
}
private CustomerFeedServiceSettings(CustomerFeedServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCustomerFeedSettings = existing.GetCustomerFeedSettings;
MutateCustomerFeedsSettings = existing.MutateCustomerFeedsSettings;
OnCopy(existing);
}
partial void OnCopy(CustomerFeedServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerFeedServiceClient.GetCustomerFeed</c> and <c>CustomerFeedServiceClient.GetCustomerFeedAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetCustomerFeedSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CustomerFeedServiceClient.MutateCustomerFeeds</c> and
/// <c>CustomerFeedServiceClient.MutateCustomerFeedsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateCustomerFeedsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="CustomerFeedServiceSettings"/> object.</returns>
public CustomerFeedServiceSettings Clone() => new CustomerFeedServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CustomerFeedServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CustomerFeedServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerFeedServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CustomerFeedServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CustomerFeedServiceClientBuilder()
{
UseJwtAccessWithScopes = CustomerFeedServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CustomerFeedServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerFeedServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CustomerFeedServiceClient Build()
{
CustomerFeedServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CustomerFeedServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CustomerFeedServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CustomerFeedServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CustomerFeedServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CustomerFeedServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CustomerFeedServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CustomerFeedServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CustomerFeedServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerFeedServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>CustomerFeedService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage customer feeds.
/// </remarks>
public abstract partial class CustomerFeedServiceClient
{
/// <summary>
/// The default endpoint for the CustomerFeedService service, which is a host of "googleads.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default CustomerFeedService scopes.</summary>
/// <remarks>
/// The default CustomerFeedService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="CustomerFeedServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="CustomerFeedServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CustomerFeedServiceClient"/>.</returns>
public static stt::Task<CustomerFeedServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CustomerFeedServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CustomerFeedServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use
/// <see cref="CustomerFeedServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CustomerFeedServiceClient"/>.</returns>
public static CustomerFeedServiceClient Create() => new CustomerFeedServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CustomerFeedServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="CustomerFeedServiceSettings"/>.</param>
/// <returns>The created <see cref="CustomerFeedServiceClient"/>.</returns>
internal static CustomerFeedServiceClient Create(grpccore::CallInvoker callInvoker, CustomerFeedServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CustomerFeedService.CustomerFeedServiceClient grpcClient = new CustomerFeedService.CustomerFeedServiceClient(callInvoker);
return new CustomerFeedServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC CustomerFeedService client</summary>
public virtual CustomerFeedService.CustomerFeedServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerFeed GetCustomerFeed(GetCustomerFeedRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerFeed> GetCustomerFeedAsync(GetCustomerFeedRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerFeed> GetCustomerFeedAsync(GetCustomerFeedRequest request, st::CancellationToken cancellationToken) =>
GetCustomerFeedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer feed to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerFeed GetCustomerFeed(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerFeed(new GetCustomerFeedRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer feed to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerFeed> GetCustomerFeedAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerFeedAsync(new GetCustomerFeedRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer feed to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerFeed> GetCustomerFeedAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCustomerFeedAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer feed to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CustomerFeed GetCustomerFeed(gagvr::CustomerFeedName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerFeed(new GetCustomerFeedRequest
{
ResourceNameAsCustomerFeedName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer feed to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerFeed> GetCustomerFeedAsync(gagvr::CustomerFeedName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCustomerFeedAsync(new GetCustomerFeedRequest
{
ResourceNameAsCustomerFeedName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the customer feed to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CustomerFeed> GetCustomerFeedAsync(gagvr::CustomerFeedName resourceName, st::CancellationToken cancellationToken) =>
GetCustomerFeedAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerFeedsResponse MutateCustomerFeeds(MutateCustomerFeedsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerFeedsResponse> MutateCustomerFeedsAsync(MutateCustomerFeedsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerFeedsResponse> MutateCustomerFeedsAsync(MutateCustomerFeedsRequest request, st::CancellationToken cancellationToken) =>
MutateCustomerFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose customer feeds are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual customer feeds.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCustomerFeedsResponse MutateCustomerFeeds(string customerId, scg::IEnumerable<CustomerFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerFeeds(new MutateCustomerFeedsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose customer feeds are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual customer feeds.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerFeedsResponse> MutateCustomerFeedsAsync(string customerId, scg::IEnumerable<CustomerFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCustomerFeedsAsync(new MutateCustomerFeedsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose customer feeds are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual customer feeds.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCustomerFeedsResponse> MutateCustomerFeedsAsync(string customerId, scg::IEnumerable<CustomerFeedOperation> operations, st::CancellationToken cancellationToken) =>
MutateCustomerFeedsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CustomerFeedService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage customer feeds.
/// </remarks>
public sealed partial class CustomerFeedServiceClientImpl : CustomerFeedServiceClient
{
private readonly gaxgrpc::ApiCall<GetCustomerFeedRequest, gagvr::CustomerFeed> _callGetCustomerFeed;
private readonly gaxgrpc::ApiCall<MutateCustomerFeedsRequest, MutateCustomerFeedsResponse> _callMutateCustomerFeeds;
/// <summary>
/// Constructs a client wrapper for the CustomerFeedService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="CustomerFeedServiceSettings"/> used within this client.</param>
public CustomerFeedServiceClientImpl(CustomerFeedService.CustomerFeedServiceClient grpcClient, CustomerFeedServiceSettings settings)
{
GrpcClient = grpcClient;
CustomerFeedServiceSettings effectiveSettings = settings ?? CustomerFeedServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCustomerFeed = clientHelper.BuildApiCall<GetCustomerFeedRequest, gagvr::CustomerFeed>(grpcClient.GetCustomerFeedAsync, grpcClient.GetCustomerFeed, effectiveSettings.GetCustomerFeedSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCustomerFeed);
Modify_GetCustomerFeedApiCall(ref _callGetCustomerFeed);
_callMutateCustomerFeeds = clientHelper.BuildApiCall<MutateCustomerFeedsRequest, MutateCustomerFeedsResponse>(grpcClient.MutateCustomerFeedsAsync, grpcClient.MutateCustomerFeeds, effectiveSettings.MutateCustomerFeedsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCustomerFeeds);
Modify_MutateCustomerFeedsApiCall(ref _callMutateCustomerFeeds);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetCustomerFeedApiCall(ref gaxgrpc::ApiCall<GetCustomerFeedRequest, gagvr::CustomerFeed> call);
partial void Modify_MutateCustomerFeedsApiCall(ref gaxgrpc::ApiCall<MutateCustomerFeedsRequest, MutateCustomerFeedsResponse> call);
partial void OnConstruction(CustomerFeedService.CustomerFeedServiceClient grpcClient, CustomerFeedServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CustomerFeedService client</summary>
public override CustomerFeedService.CustomerFeedServiceClient GrpcClient { get; }
partial void Modify_GetCustomerFeedRequest(ref GetCustomerFeedRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCustomerFeedsRequest(ref MutateCustomerFeedsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CustomerFeed GetCustomerFeed(GetCustomerFeedRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerFeedRequest(ref request, ref callSettings);
return _callGetCustomerFeed.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested customer feed in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CustomerFeed> GetCustomerFeedAsync(GetCustomerFeedRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCustomerFeedRequest(ref request, ref callSettings);
return _callGetCustomerFeed.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateCustomerFeedsResponse MutateCustomerFeeds(MutateCustomerFeedsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerFeedsRequest(ref request, ref callSettings);
return _callMutateCustomerFeeds.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes customer feeds. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [CustomerFeedError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [FunctionParsingError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NotEmptyError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateCustomerFeedsResponse> MutateCustomerFeedsAsync(MutateCustomerFeedsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCustomerFeedsRequest(ref request, ref callSettings);
return _callMutateCustomerFeeds.Async(request, callSettings);
}
}
}
| |
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace Nop.Core.Html
{
/// <summary>
/// Represents a HTML helper
/// </summary>
public partial class HtmlHelper
{
#region Fields
private readonly static Regex paragraphStartRegex = new Regex("<p>", RegexOptions.IgnoreCase);
private readonly static Regex paragraphEndRegex = new Regex("</p>", RegexOptions.IgnoreCase);
//private static Regex ampRegex = new Regex("&(?!(?:#[0-9]{2,4};|[a-z0-9]+;))", RegexOptions.Compiled | RegexOptions.IgnoreCase);
#endregion
#region Utilities
private static string EnsureOnlyAllowedHtml(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
const string allowedTags = "br,hr,b,i,u,a,div,ol,ul,li,blockquote,img,span,p,em,strong,font,pre,h1,h2,h3,h4,h5,h6,address,cite";
var m = Regex.Matches(text, "<.*?>", RegexOptions.IgnoreCase);
for (int i = m.Count - 1; i >= 0; i--)
{
string tag = text.Substring(m[i].Index + 1, m[i].Length - 1).Trim().ToLower();
if (!IsValidTag(tag, allowedTags))
{
text = text.Remove(m[i].Index, m[i].Length);
}
}
return text;
}
private static bool IsValidTag(string tag, string tags)
{
string[] allowedTags = tags.Split(',');
if (tag.IndexOf("javascript") >= 0) return false;
if (tag.IndexOf("vbscript") >= 0) return false;
if (tag.IndexOf("onclick") >= 0) return false;
var endchars = new [] { ' ', '>', '/', '\t' };
int pos = tag.IndexOfAny(endchars, 1);
if (pos > 0) tag = tag.Substring(0, pos);
if (tag[0] == '/') tag = tag.Substring(1);
foreach (string aTag in allowedTags)
{
if (tag == aTag) return true;
}
return false;
}
#endregion
#region Methods
/// <summary>
/// Formats the text
/// </summary>
/// <param name="text">Text</param>
/// <param name="stripTags">A value indicating whether to strip tags</param>
/// <param name="convertPlainTextToHtml">A value indicating whether HTML is allowed</param>
/// <param name="allowHtml">A value indicating whether HTML is allowed</param>
/// <param name="allowBBCode">A value indicating whether BBCode is allowed</param>
/// <param name="resolveLinks">A value indicating whether to resolve links</param>
/// <param name="addNoFollowTag">A value indicating whether to add "noFollow" tag</param>
/// <returns>Formatted text</returns>
public static string FormatText(string text, bool stripTags,
bool convertPlainTextToHtml, bool allowHtml,
bool allowBBCode, bool resolveLinks, bool addNoFollowTag)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
try
{
if (stripTags)
{
text = StripTags(text);
}
text = allowHtml ? EnsureOnlyAllowedHtml(text) : HttpUtility.HtmlEncode(text);
if (convertPlainTextToHtml)
{
text = ConvertPlainTextToHtml(text);
}
if (allowBBCode)
{
text = BBCodeHelper.FormatText(text, true, true, true, true, true, true, true);
}
if (resolveLinks)
{
text = ResolveLinksHelper.FormatText(text);
}
if (addNoFollowTag)
{
//add noFollow tag. not implemented
}
}
catch (Exception exc)
{
text = string.Format("Text cannot be formatted. Error: {0}", exc.Message);
}
return text;
}
/// <summary>
/// Strips tags
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string StripTags(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, @"(>)(\r|\n)*(<)", "><");
text = Regex.Replace(text, "(<[^>]*>)([^<]*)", "$2");
text = Regex.Replace(text, "(&#x?[0-9]{2,4};|"|&| |<|>|€|©|®|‰|‡|†|‹|›|„|”|“|‚|’|‘|—|–|‏|‎|‍|‌| | | |˜|ˆ|Ÿ|š|Š)", "@");
return text;
}
/// <summary>
/// replace anchor text (remove a tag from the following url <a href="http://example.com">Name</a> and output only the string "Name")
/// </summary>
/// <param name="text">Text</param>
/// <returns>Text</returns>
public static string ReplaceAnchorTags(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, @"<a\b[^>]+>([^<]*(?:(?!</a)<[^<]*)*)</a>", "$1", RegexOptions.IgnoreCase);
return text;
}
/// <summary>
/// Converts plain text to HTML
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string ConvertPlainTextToHtml(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = text.Replace("\r\n", "<br />");
text = text.Replace("\r", "<br />");
text = text.Replace("\n", "<br />");
text = text.Replace("\t", " ");
text = text.Replace(" ", " ");
return text;
}
/// <summary>
/// Converts HTML to plain text
/// </summary>
/// <param name="text">Text</param>
/// <param name="decode">A value indicating whether to decode text</param>
/// <param name="replaceAnchorTags">A value indicating whether to replace anchor text (remove a tag from the following url <a href="http://example.com">Name</a> and output only the string "Name")</param>
/// <returns>Formatted text</returns>
public static string ConvertHtmlToPlainText(string text,
bool decode = false, bool replaceAnchorTags = false)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
if (decode)
text = HttpUtility.HtmlDecode(text);
text = text.Replace("<br>", "\n");
text = text.Replace("<br >", "\n");
text = text.Replace("<br />", "\n");
text = text.Replace(" ", "\t");
text = text.Replace(" ", " ");
if (replaceAnchorTags)
text = ReplaceAnchorTags(text);
return text;
}
/// <summary>
/// Converts text to paragraph
/// </summary>
/// <param name="text">Text</param>
/// <returns>Formatted text</returns>
public static string ConvertPlainTextToParagraph(string text)
{
if (String.IsNullOrEmpty(text))
return string.Empty;
text = paragraphStartRegex.Replace(text, string.Empty);
text = paragraphEndRegex.Replace(text, "\n");
text = text.Replace("\r\n", "\n").Replace("\r", "\n");
text = text + "\n\n";
text = text.Replace("\n\n", "\n");
var strArray = text.Split(new [] { '\n' });
var builder = new StringBuilder();
foreach (string str in strArray)
{
if ((str != null) && (str.Trim().Length > 0))
{
builder.AppendFormat("<p>{0}</p>\n", str);
}
}
return builder.ToString();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Sandbox.Areas.HelpPage.SampleGeneration
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
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 Microsoft.Rest.Azure;
using Models;
/// <summary>
/// LocalNetworkGatewaysOperations operations.
/// </summary>
internal partial class LocalNetworkGatewaysOperations : IServiceOperations<NetworkManagementClient>, ILocalNetworkGatewaysOperations
{
/// <summary>
/// Initializes a new instance of the LocalNetworkGatewaysOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LocalNetworkGatewaysOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local network
/// gateway in the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Local Network Gateway
/// operation through Network resource provider.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<LocalNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<LocalNetworkGateway> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(
resourceGroupName, localNetworkGatewayName, parameters, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local network
/// gateway in the specified resource group through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Begin Create or update Local Network Gateway
/// operation through Network resource provider.
/// </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<AzureOperationResponse<LocalNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (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(parameters != null)
{
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// 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 != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LocalNetworkGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_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>
/// The Get LocalNetworkGateway operation retrieves information about the
/// specified local network gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </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<AzureOperationResponse<LocalNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LocalNetworkGateway>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<LocalNetworkGateway>(_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>
/// The Delete LocalNetworkGateway operation deletes the specified local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(
resourceGroupName, localNetworkGatewayName, customHeaders, cancellationToken);
return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken);
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specified local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// The name of the local network gateway.
/// </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<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string localNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "localNetworkGatewayName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways/{localNetworkGatewayName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{localNetworkGatewayName}", Uri.EscapeDataString(localNetworkGatewayName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
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 != 204 && (int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// The List LocalNetworkGateways operation retrieves all the local network
/// gateways stored.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </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<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/localNetworkGateways").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_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>
/// The List LocalNetworkGateways operation retrieves all the local network
/// gateways stored.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </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<AzureOperationResponse<IPage<LocalNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LocalNetworkGateway>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<LocalNetworkGateway>>(_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;
}
}
}
| |
/*****************************************************************************
* Spine Extensions by Mitch Thompson and John Dy
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using UnityEngine;
using Spine;
namespace Spine.Unity {
public static class SkeletonExtensions {
const float ByteToFloat = 1f / 255f;
#region Colors
public static Color GetColor (this Skeleton s) { return new Color(s.r, s.g, s.b, s.a); }
public static Color GetColor (this RegionAttachment a) { return new Color(a.r, a.g, a.b, a.a); }
public static Color GetColor (this MeshAttachment a) { return new Color(a.r, a.g, a.b, a.a); }
public static Color GetColor (this WeightedMeshAttachment a) { return new Color(a.r, a.g, a.b, a.a); }
public static void SetColor (this Skeleton skeleton, Color color) {
skeleton.A = color.a;
skeleton.R = color.r;
skeleton.G = color.g;
skeleton.B = color.b;
}
public static void SetColor (this Skeleton skeleton, Color32 color) {
skeleton.A = color.a * ByteToFloat;
skeleton.R = color.r * ByteToFloat;
skeleton.G = color.g * ByteToFloat;
skeleton.B = color.b * ByteToFloat;
}
public static void SetColor (this Slot slot, Color color) {
slot.A = color.a;
slot.R = color.r;
slot.G = color.g;
slot.B = color.b;
}
public static void SetColor (this Slot slot, Color32 color) {
slot.A = color.a * ByteToFloat;
slot.R = color.r * ByteToFloat;
slot.G = color.g * ByteToFloat;
slot.B = color.b * ByteToFloat;
}
public static void SetColor (this RegionAttachment attachment, Color color) {
attachment.A = color.a;
attachment.R = color.r;
attachment.G = color.g;
attachment.B = color.b;
}
public static void SetColor (this RegionAttachment attachment, Color32 color) {
attachment.A = color.a * ByteToFloat;
attachment.R = color.r * ByteToFloat;
attachment.G = color.g * ByteToFloat;
attachment.B = color.b * ByteToFloat;
}
public static void SetColor (this MeshAttachment attachment, Color color) {
attachment.A = color.a;
attachment.R = color.r;
attachment.G = color.g;
attachment.B = color.b;
}
public static void SetColor (this MeshAttachment attachment, Color32 color) {
attachment.A = color.a * ByteToFloat;
attachment.R = color.r * ByteToFloat;
attachment.G = color.g * ByteToFloat;
attachment.B = color.b * ByteToFloat;
}
public static void SetColor (this WeightedMeshAttachment attachment, Color color) {
attachment.A = color.a;
attachment.R = color.r;
attachment.G = color.g;
attachment.B = color.b;
}
public static void SetColor (this WeightedMeshAttachment attachment, Color32 color) {
attachment.A = color.a * ByteToFloat;
attachment.R = color.r * ByteToFloat;
attachment.G = color.g * ByteToFloat;
attachment.B = color.b * ByteToFloat;
}
#endregion
#region Bone Position
public static void SetPosition (this Bone bone, Vector2 position) {
bone.X = position.x;
bone.Y = position.y;
}
public static void SetPosition (this Bone bone, Vector3 position) {
bone.X = position.x;
bone.Y = position.y;
}
public static Vector2 GetSkeletonSpacePosition (this Bone bone) {
return new Vector2(bone.worldX, bone.worldY);
}
public static Vector3 GetWorldPosition (this Bone bone, UnityEngine.Transform parentTransform) {
return parentTransform.TransformPoint(new Vector3(bone.worldX, bone.worldY));
}
#endregion
#region Posing
/// <summary>
/// Shortcut for posing a skeleton at a specific time. Time is in seconds. (frameNumber / 30f) will give you seconds.
/// If you need to do this often, you should get the Animation object yourself using skeleton.data.FindAnimation. and call Apply on that.</summary>
/// <param name = "skeleton">The skeleton to pose.</param>
/// <param name="animationName">The name of the animation to use.</param>
/// <param name = "time">The time of the pose within the animation.</param>
/// <param name = "loop">Wraps the time around if it is longer than the duration of the animation.</param>
public static void PoseWithAnimation (this Skeleton skeleton, string animationName, float time, bool loop) {
// Fail loud when skeleton.data is null.
Spine.Animation animation = skeleton.data.FindAnimation(animationName);
if (animation == null) return;
animation.Apply(skeleton, 0, time, loop, null);
}
/// <summary>Resets the DrawOrder to the Setup Pose's draw order</summary>
public static void SetDrawOrderToSetupPose (this Skeleton skeleton) {
var slotsItems = skeleton.slots.Items;
int n = skeleton.slots.Count;
var drawOrder = skeleton.drawOrder;
drawOrder.Clear(false);
drawOrder.GrowIfNeeded(n);
System.Array.Copy(slotsItems, drawOrder.Items, n);
}
/// <summary>Resets the color of a slot to Setup Pose value.</summary>
public static void SetColorToSetupPose (this Slot slot) {
slot.r = slot.data.r;
slot.g = slot.data.g;
slot.b = slot.data.b;
slot.a = slot.data.a;
}
/// <summary>Sets a slot's attachment to setup pose. If you have the slotIndex, Skeleton.SetSlotAttachmentToSetupPose is faster.</summary>
public static void SetAttachmentToSetupPose (this Slot slot) {
var slotData = slot.data;
slot.Attachment = slot.bone.skeleton.GetAttachment(slotData.name, slotData.attachmentName);
}
/// <summary>Resets the attachment of slot at a given slotIndex to setup pose. This is faster than Slot.SetAttachmentToSetupPose.</summary>
public static void SetSlotAttachmentToSetupPose (this Skeleton skeleton, int slotIndex) {
var slot = skeleton.slots.Items[slotIndex];
var attachment = skeleton.GetAttachment(slotIndex, slot.data.attachmentName);
slot.Attachment = attachment;
}
/// <summary>Resets Skeleton parts to Setup Pose according to a Spine.Animation's keyed items.</summary>
public static void SetKeyedItemsToSetupPose (this Animation animation, Skeleton skeleton) {
var timelinesItems = animation.timelines.Items;
for (int i = 0, n = timelinesItems.Length; i < n; i++)
timelinesItems[i].SetToSetupPose(skeleton);
}
public static void SetToSetupPose (this Timeline timeline, Skeleton skeleton) {
if (timeline != null) {
// sorted according to assumed likelihood here
// Bone
if (timeline is RotateTimeline) {
var bone = skeleton.bones.Items[((RotateTimeline)timeline).boneIndex];
bone.rotation = bone.data.rotation;
} else if (timeline is TranslateTimeline) {
var bone = skeleton.bones.Items[((TranslateTimeline)timeline).boneIndex];
bone.x = bone.data.x;
bone.y = bone.data.y;
} else if (timeline is ScaleTimeline) {
var bone = skeleton.bones.Items[((ScaleTimeline)timeline).boneIndex];
bone.scaleX = bone.data.scaleX;
bone.scaleY = bone.data.scaleY;
// Attachment
} else if (timeline is FfdTimeline) {
var slot = skeleton.slots.Items[((FfdTimeline)timeline).slotIndex];
slot.attachmentVerticesCount = 0;
// Slot
} else if (timeline is AttachmentTimeline) {
skeleton.SetSlotAttachmentToSetupPose(((AttachmentTimeline)timeline).slotIndex);
} else if (timeline is ColorTimeline) {
skeleton.slots.Items[((ColorTimeline)timeline).slotIndex].SetColorToSetupPose();
// Constraint
} else if (timeline is IkConstraintTimeline) {
var ikTimeline = (IkConstraintTimeline)timeline;
var ik = skeleton.ikConstraints.Items[ikTimeline.ikConstraintIndex];
var data = ik.data;
ik.bendDirection = data.bendDirection;
ik.mix = data.mix;
// Skeleton
} else if (timeline is DrawOrderTimeline) {
skeleton.SetDrawOrderToSetupPose();
}
}
}
#endregion
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Web
{
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web.Configuration;
public class WebServiceHost : ServiceHost
{
static readonly Type WebHttpBindingType = typeof(WebHttpBinding);
static readonly string WebHttpEndpointKind = "webHttpEndpoint";
public WebServiceHost()
: base()
{
}
public WebServiceHost(object singletonInstance, params Uri[] baseAddresses)
: base(singletonInstance, baseAddresses)
{
}
public WebServiceHost(Type serviceType, params Uri[] baseAddresses) :
base(serviceType, baseAddresses)
{
}
// This method adds automatic endpoints at the base addresses, 1 per site binding (http or https). It only configures
// the security on the binding. It does not add any behaviors.
// If there are no base addresses, or if endpoints have been configured explicitly, it does not add any
// automatic endpoints.
// If it adds automatic endpoints, it validates that the service implements a single contract
internal static void AddAutomaticWebHttpBindingEndpoints(ServiceHost host, IDictionary<string, ContractDescription> implementedContracts, string multipleContractsErrorMessage, string noContractErrorMessage, string standardEndpointKind)
{
bool enableAutoEndpointCompat = AppSettings.EnableAutomaticEndpointsCompatibility;
// We do not add an automatic endpoint if an explicit endpoint has been configured unless
// the user has specifically opted into compat mode. See CSDMain bugs 176157 & 262728 for history
if (host.Description.Endpoints != null
&& host.Description.Endpoints.Count > 0
&& !enableAutoEndpointCompat)
{
return;
}
AuthenticationSchemes supportedSchemes = AuthenticationSchemes.None;
if (host.BaseAddresses.Count > 0)
{
supportedSchemes = AspNetEnvironment.Current.GetAuthenticationSchemes(host.BaseAddresses[0]);
if (AspNetEnvironment.Current.IsSimpleApplicationHost)
{
// Cassini always reports the auth scheme as anonymous or Ntlm. Map this to Ntlm, except when forms auth
// is requested
if (supportedSchemes == (AuthenticationSchemes.Anonymous | AuthenticationSchemes.Ntlm))
{
if (AspNetEnvironment.Current.IsWindowsAuthenticationConfigured())
{
supportedSchemes = AuthenticationSchemes.Ntlm;
}
else
{
supportedSchemes = AuthenticationSchemes.Anonymous;
}
}
}
}
Type contractType = null;
// add an endpoint with the contract at each base address
foreach (Uri baseAddress in host.BaseAddresses)
{
string uriScheme = baseAddress.Scheme;
// HTTP and HTTPs are only supported schemes
if (Object.ReferenceEquals(uriScheme, Uri.UriSchemeHttp) || Object.ReferenceEquals(uriScheme, Uri.UriSchemeHttps))
{
// bypass adding the automatic endpoint if there's already one at the base address
bool isExplicitEndpointConfigured = false;
foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
{
if (endpoint.Address != null && EndpointAddress.UriEquals(endpoint.Address.Uri, baseAddress, true, false))
{
isExplicitEndpointConfigured = true;
break;
}
}
if (isExplicitEndpointConfigured)
{
continue;
}
if (contractType == null)
{
if (implementedContracts.Count > 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(multipleContractsErrorMessage));
}
else if (implementedContracts.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(noContractErrorMessage));
}
foreach (ContractDescription contract in implementedContracts.Values)
{
contractType = contract.ContractType;
break;
}
}
// Get the default web endpoint
ConfigLoader configLoader = new ConfigLoader(host.GetContractResolver(implementedContracts));
ServiceEndpointElement serviceEndpointElement = new ServiceEndpointElement();
serviceEndpointElement.Contract = contractType.FullName;
// Check for a protocol mapping
ProtocolMappingItem protocolMappingItem = ConfigLoader.LookupProtocolMapping(baseAddress.Scheme);
if (protocolMappingItem != null &&
string.Equals(protocolMappingItem.Binding, WebHttpBinding.WebHttpBindingConfigurationStrings.WebHttpBindingCollectionElementName, StringComparison.Ordinal))
{
serviceEndpointElement.BindingConfiguration = protocolMappingItem.BindingConfiguration;
}
serviceEndpointElement.Kind = standardEndpointKind;
// LookupEndpoint will not set the Endpoint address and listenUri
// because omitSettingEndpointAddress is set to true.
// We will set them after setting the binding security
ServiceEndpoint automaticEndpoint = configLoader.LookupEndpoint(serviceEndpointElement, null, host, host.Description, true /*omitSettingEndpointAddress*/);
WebHttpBinding binding = automaticEndpoint.Binding as WebHttpBinding;
bool automaticallyConfigureSecurity = !binding.Security.IsModeSet;
if (automaticallyConfigureSecurity)
{
if (Object.ReferenceEquals(uriScheme, Uri.UriSchemeHttps))
{
binding.Security.Mode = WebHttpSecurityMode.Transport;
}
else if (supportedSchemes != AuthenticationSchemes.None && supportedSchemes != AuthenticationSchemes.Anonymous)
{
binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
}
else
{
binding.Security.Mode = WebHttpSecurityMode.None;
}
}
if (automaticallyConfigureSecurity && AspNetEnvironment.Enabled)
{
SetBindingCredentialBasedOnHostedEnvironment(automaticEndpoint, supportedSchemes);
}
// Setting the Endpoint address and listenUri now that we've set the binding security
ConfigLoader.ConfigureEndpointAddress(serviceEndpointElement, host, automaticEndpoint);
ConfigLoader.ConfigureEndpointListenUri(serviceEndpointElement, host, automaticEndpoint);
host.AddServiceEndpoint(automaticEndpoint);
}
}
}
internal static void SetRawContentTypeMapperIfNecessary(ServiceEndpoint endpoint, bool isDispatch)
{
Binding binding = endpoint.Binding;
ContractDescription contract = endpoint.Contract;
if (binding == null)
{
return;
}
CustomBinding customBinding = new CustomBinding(binding);
BindingElementCollection bec = customBinding.Elements;
WebMessageEncodingBindingElement encodingElement = bec.Find<WebMessageEncodingBindingElement>();
if (encodingElement == null || encodingElement.ContentTypeMapper != null)
{
return;
}
bool areAllOperationsRawMapperCompatible = true;
int numStreamOperations = 0;
foreach (OperationDescription operation in contract.Operations)
{
bool isCompatible = (isDispatch) ? IsRawContentMapperCompatibleDispatchOperation(operation, ref numStreamOperations) : IsRawContentMapperCompatibleClientOperation(operation, ref numStreamOperations);
if (!isCompatible)
{
areAllOperationsRawMapperCompatible = false;
break;
}
}
if (areAllOperationsRawMapperCompatible && numStreamOperations > 0)
{
encodingElement.ContentTypeMapper = RawContentTypeMapper.Instance;
endpoint.Binding = customBinding;
}
}
protected override void OnOpening()
{
if (this.Description == null)
{
return;
}
// disable other things that listen for GET at base address and may conflict with auto-endpoints
ServiceDebugBehavior sdb = this.Description.Behaviors.Find<ServiceDebugBehavior>();
if (sdb != null)
{
sdb.HttpHelpPageEnabled = false;
sdb.HttpsHelpPageEnabled = false;
}
ServiceMetadataBehavior smb = this.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb != null)
{
smb.HttpGetEnabled = false;
smb.HttpsGetEnabled = false;
}
AddAutomaticWebHttpBindingEndpoints(this, this.ImplementedContracts, SR2.GetString(SR2.HttpTransferServiceHostMultipleContracts, this.Description.Name), SR2.GetString(SR2.HttpTransferServiceHostNoContract, this.Description.Name), WebHttpEndpointKind);
// for both user-defined and automatic endpoints, ensure they have the right behavior and content type mapper added
foreach (ServiceEndpoint serviceEndpoint in this.Description.Endpoints)
{
if (serviceEndpoint.Binding != null && serviceEndpoint.Binding.CreateBindingElements().Find<WebMessageEncodingBindingElement>() != null)
{
SetRawContentTypeMapperIfNecessary(serviceEndpoint, true);
if (serviceEndpoint.Behaviors.Find<WebHttpBehavior>() == null)
{
ConfigLoader.LoadDefaultEndpointBehaviors(serviceEndpoint);
if (serviceEndpoint.Behaviors.Find<WebHttpBehavior>() == null)
{
serviceEndpoint.Behaviors.Add(new WebHttpBehavior());
}
}
}
}
base.OnOpening();
}
static bool IsRawContentMapperCompatibleClientOperation(OperationDescription operation, ref int numStreamOperations)
{
// An operation is raw encoder compatible on the client side iff the response is a Stream or void
// The request is driven by the format property on the message and not by the content type
if (operation.Messages.Count > 1 & !IsResponseStreamOrVoid(operation, ref numStreamOperations))
{
return false;
}
return true;
}
static bool IsRawContentMapperCompatibleDispatchOperation(OperationDescription operation, ref int numStreamOperations)
{
// An operation is raw encoder compatible on the dispatch side iff the request body is a Stream or void
// The response is driven by the format property on the message and not by the content type
UriTemplateDispatchFormatter throwAway = new UriTemplateDispatchFormatter(operation, null, new QueryStringConverter(), operation.DeclaringContract.Name, new Uri("http://localhost"));
int numUriVariables = throwAway.pathMapping.Count + throwAway.queryMapping.Count;
bool isRequestCompatible = false;
if (numUriVariables > 0)
{
// we need the local variable tmp because ref parameters are not allowed to be passed into
// anonymous methods by the compiler.
int tmp = 0;
WebHttpBehavior.HideRequestUriTemplateParameters(operation, throwAway, delegate()
{
isRequestCompatible = IsRequestStreamOrVoid(operation, ref tmp);
});
numStreamOperations += tmp;
}
else
{
isRequestCompatible = IsRequestStreamOrVoid(operation, ref numStreamOperations);
}
return isRequestCompatible;
}
static bool IsRequestStreamOrVoid(OperationDescription operation, ref int numStreamOperations)
{
MessageDescription message = operation.Messages[0];
if (WebHttpBehavior.IsTypedMessage(message) || WebHttpBehavior.IsUntypedMessage(message))
{
return false;
}
if (message.Body.Parts.Count == 0)
{
return true;
}
else if (message.Body.Parts.Count == 1)
{
if (IsStreamPart(message.Body.Parts[0].Type))
{
++numStreamOperations;
return true;
}
else if (IsVoidPart(message.Body.Parts[0].Type))
{
return true;
}
}
return false;
}
static bool IsResponseStreamOrVoid(OperationDescription operation, ref int numStreamOperations)
{
if (operation.Messages.Count <= 1)
{
return true;
}
MessageDescription message = operation.Messages[1];
if (WebHttpBehavior.IsTypedMessage(message) || WebHttpBehavior.IsUntypedMessage(message))
{
return false;
}
if (message.Body.Parts.Count == 0)
{
if (message.Body.ReturnValue == null || IsVoidPart(message.Body.ReturnValue.Type))
{
return true;
}
else if (IsStreamPart(message.Body.ReturnValue.Type))
{
++numStreamOperations;
return true;
}
}
return false;
}
static bool IsStreamPart(Type type)
{
return (type == typeof(Stream));
}
static bool IsVoidPart(Type type)
{
return (type == null || type == typeof(void));
}
// For automatic endpoints, in the hosted case we configure a credential type based on the vdir settings.
// For IIS, in IntegratedWindowsAuth mode we pick Negotiate.
static void SetBindingCredentialBasedOnHostedEnvironment(ServiceEndpoint serviceEndpoint, AuthenticationSchemes supportedSchemes)
{
WebHttpBinding whb = serviceEndpoint.Binding as WebHttpBinding;
Fx.Assert(whb != null, "Automatic endpoint must be WebHttpBinding");
switch (supportedSchemes)
{
case AuthenticationSchemes.Digest:
whb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest;
break;
case AuthenticationSchemes.IntegratedWindowsAuthentication:
// fall through to Negotiate
case AuthenticationSchemes.Negotiate:
whb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
break;
case AuthenticationSchemes.Ntlm:
whb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
break;
case AuthenticationSchemes.Basic:
whb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
break;
case AuthenticationSchemes.Anonymous:
whb.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
break;
default:
whb.Security.Transport.ClientCredentialType = HttpClientCredentialType.InheritedFromHost;
break;
}
}
}
}
| |
using System;
using System.Collections;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Web.UI;
using Rainbow.Framework.Web.UI.WebControls;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Tasks Module - Edit page part
/// Writen by: ?
/// Moved into Rainbow by Jakob Hansen, hansen3000@hotmail.com
/// </summary>
public partial class TasksEdit : AddEditItemPage
{
#region Declarations
/// <summary>
///
/// </summary>
protected IHtmlEditor DesktopText;
#endregion
/// <summary>
/// The Page_Load event on this Page is used to obtain the ModuleID
/// and ItemID of the task to edit.
/// It then uses the Rainbow.TasksDB() data component
/// to populate the page's edit controls with the task details.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Page_Load(object sender, EventArgs e)
{
// If the page is being requested the first time, determine if an
// task itemID value is specified, and if so populate page
// contents with the task details
//Chris Farrell, chris@cftechconsulting.com, 5/28/04
//Added support for Rainbow WYSIWYG editors.
//Editor placeholder setup
HtmlEditorDataType h = new HtmlEditorDataType();
h.Value = moduleSettings["Editor"].ToString();
DesktopText =
h.GetEditor(DescriptionField, ModuleID, bool.Parse(moduleSettings["ShowUpload"].ToString()),
portalSettings);
DesktopText.Width = new Unit(moduleSettings["Width"].ToString());
DesktopText.Height = new Unit(moduleSettings["Height"].ToString());
//end Chris Farrell changes, 5/28/04
//Set right popup url
StartField.xPopupURL = Path.ApplicationRoot + "/DesktopModules/DateTextBox/popupcalendar.aspx";
StartField.xImageURL = Path.ApplicationRoot + "/DesktopModules/DateTextBox/calendar.jpg";
DueField.xPopupURL = Path.ApplicationRoot + "/DesktopModules/DateTextBox/popupcalendar.aspx";
DueField.xImageURL = Path.ApplicationRoot + "/DesktopModules/DateTextBox/calendar.jpg";
if (Page.IsPostBack == false)
{
StartField.Text = DateTime.Now.ToShortDateString();
DueField.Text = DateTime.Now.ToShortDateString();
AddListItem("TASK_STATE_0", "Not Started", StatusField);
AddListItem("TASK_STATE_1", "In Progress", StatusField);
AddListItem("TASK_STATE_2", "Complete", StatusField);
StatusField.SelectedIndex = 0;
AddListItem("TASK_PRIORITY_0", "High", PriorityField);
AddListItem("TASK_PRIORITY_1", "Normal", PriorityField);
AddListItem("TASK_PRIORITY_2", "Low", PriorityField);
PriorityField.SelectedIndex = 1;
if (ItemID != 0)
{
// Obtain a single row of Task information
TasksDB Tasks = new TasksDB();
SqlDataReader dr = Tasks.GetSingleTask(ItemID);
try
{
// Read first row from database
if (dr.Read())
{
TitleField.Text = (string) dr["Title"];
StartField.Text = ((DateTime) dr["StartDate"]).ToShortDateString();
DueField.Text = ((DateTime) dr["DueDate"]).ToShortDateString();
CreatedBy.Text = (string) dr["CreatedByUser"];
ModifiedBy.Text = (string) dr["ModifiedByUser"];
PercentCompleteField.Text = ((Int32) dr["PercentComplete"]).ToString();
AssignedField.Text = (string) dr["AssignedTo"];
CreatedDate.Text = ((DateTime) dr["CreatedDate"]).ToString();
ModifiedDate.Text = ((DateTime) dr["ModifiedDate"]).ToString();
StatusField.SelectedIndex = Convert.ToInt16((string) dr["Status"]);
PriorityField.SelectedIndex = Convert.ToInt16((string) dr["Priority"]);
// 15/7/2004 added localization by Mario Endara mario@softworks.com.uy
if (CreatedBy.Text == "unknown")
{
CreatedBy.Text = General.GetString("UNKNOWN", "unknown");
}
// 15/7/2004 added localization by Mario Endara mario@softworks.com.uy
if (ModifiedBy.Text == "unknown")
{
ModifiedBy.Text = General.GetString("UNKNOWN", "unknown");
}
//Chris Farrell, chris@cftechconsulting.com, 5/28/04
//DescriptionField.Text = (string) dr["Description"];
DesktopText.Text = (string) dr["Description"];
}
}
finally
{
dr.Close();
}
}
else //default for new
{
AssignedField.Text = moduleSettings["TASKS_DEFAULT_ASSIGNEE"].ToString();
}
}
}
/// <summary>
/// Set the module guids with free access to this page
/// </summary>
protected override ArrayList AllowedModules
{
get
{
ArrayList al = new ArrayList();
al.Add("2502DB18-B580-4F90-8CB4-C15E6E531012");
return al;
}
}
/// <summary>
/// The OnUpdate event handler on this Page is used to either
/// create or update an task. It uses the Rainbow.TasksDB()
/// data component to encapsulate all data functionality.
/// Note: This procedure is automaticall called on Update
/// </summary>
/// <param name="e"></param>
protected override void OnUpdate(EventArgs e)
{
// Calling base we check if the user has rights on updating
base.OnUpdate(e);
// Only Update if the Entered Data is Valid
if (Page.IsValid == true)
{
// Create an instance of the Task DB component
TasksDB tasks = new TasksDB();
if (ItemID == 0)
{
// Add the task within the Tasks table
//by Manu
//First get linked task modules
string[] linkedModules = moduleSettings["TASKS_LINKED_MODULES"].ToString().Split(';');
for (int i = 0; i < linkedModules.Length; i++)
{
int linkedModuleID = int.Parse(linkedModules[i]);
//If not module is null or current
if (linkedModuleID != 0 && linkedModuleID != ModuleID)
{
//Add to linked
//Get default assignee from module setting
Hashtable linkedModuleSettings = ModuleSettings.GetModuleSettings(linkedModuleID, this);
string linkedModuleAssignee = linkedModuleSettings["TASKS_DEFAULT_ASSIGNEE"].ToString();
tasks.AddTask(linkedModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email,
TitleField.Text, DateTime.Parse(StartField.Text), DesktopText.Text,
StatusField.SelectedItem.Value, PriorityField.SelectedItem.Value,
linkedModuleAssignee, DateTime.Parse(DueField.Text),
Int16.Parse(PercentCompleteField.Text));
}
}
//Add to current
tasks.AddTask(ModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email, TitleField.Text,
DateTime.Parse(StartField.Text), DesktopText.Text, StatusField.SelectedItem.Value,
PriorityField.SelectedItem.Value, AssignedField.Text, DateTime.Parse(DueField.Text),
Int16.Parse(PercentCompleteField.Text));
}
else
{
// Update the task within the Tasks table
tasks.UpdateTask(ModuleID, ItemID, PortalSettings.CurrentUser.Identity.Email, TitleField.Text,
DateTime.Parse(StartField.Text), DesktopText.Text, StatusField.SelectedItem.Value,
PriorityField.SelectedItem.Value, AssignedField.Text, DateTime.Parse(DueField.Text),
Int16.Parse(PercentCompleteField.Text));
}
// Redirect back to the portal home page
RedirectBackToReferringPage();
}
}
/// <summary>
/// The OnDelete event handler on this Page is used to delete
/// an task. It uses the Rainbow.TasksDB() data component to
/// encapsulate all data functionality.
/// Note:This procedure is automaticall called on Update
/// </summary>
/// <param name="e"></param>
protected override void OnDelete(EventArgs e)
{
// Calling base we check if the user has rights on deleting
base.OnUpdate(e);
// Only attempt to delete the item if it is an existing item
// (new items will have "ItemID" of 0)
if (ItemID != 0)
{
TasksDB tasks = new TasksDB();
tasks.DeleteTask(ItemID);
}
// Redirect back to the portal home page
RedirectBackToReferringPage();
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="translation"></param>
/// <param name="sender"></param>
protected void AddListItem(string key, string translation, DropDownList sender)
{
ListItem Item = new ListItem();
Item.Value = key.Substring(key.Length - 1, 1);
Item.Text = General.GetString(key, translation, sender);
sender.Items.Add(Item);
}
#region Web Form Designer generated code
/// <summary>
/// Raises OnInitEvent
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
//Translate! Jakob Hansen says: TBD!!
//RequiredTitle.ErrorMessage = Esperantus.General.GetString("TASKS_VALID_TITLE");
//PercentValidator.ErrorMessage = Esperantus.General.GetString("TASKS_INVALID_PERCENT");
//VerifyStartDate.ErrorMessage = Esperantus.General.GetString("TASKS_INVALID_STARTDATE");
//VerifyDueDate.ErrorMessage = Esperantus.General.GetString("TASKS_INVALID_DUEDATE");
InitializeComponent();
// Jes1111
if (!((Page) this.Page).IsCssFileRegistered("Mod_Tasks"))
((Page) this.Page).RegisterCssFile("Mod_Tasks");
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new EventHandler(this.Page_Load);
}
#endregion
}
}
| |
/*
* ToolkitBrushBase.cs - Implementation of the
* "System.Drawing.Toolkit.ToolkitBrushBase" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
* Copyright (C) 2003 Neil Cawse.
*
* 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.Drawing.Toolkit
{
using System.Drawing.Drawing2D;
[NonStandardExtra]
public abstract class ToolkitBrushBase : IToolkitBrush
{
private Color color;
public ToolkitBrushBase(Color color)
{
this.color = color;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected abstract void Dispose(bool disposing);
~ToolkitBrushBase()
{
Dispose(false);
}
public abstract void Select(IToolkitGraphics graphics);
public Color Color
{
get
{
return color;
}
}
// Get the bitmap bits corresponding to a particular hatch style.
protected static byte[] GetBits(HatchStyle style)
{
// Get the raw bits for the hatch bitmap.
byte[] bits;
switch(style)
{
case HatchStyle.BackwardDiagonal:
bits = BackwardDiagonal_bits; break;
case HatchStyle.DarkDownwardDiagonal:
bits = DarkDownwardDiagonal_bits; break;
case HatchStyle.DarkHorizontal:
bits = DarkHorizontal_bits; break;
case HatchStyle.DarkUpwardDiagonal:
bits = DarkUpwardDiagonal_bits; break;
case HatchStyle.DarkVertical:
bits = DarkVertical_bits; break;
case HatchStyle.DashedDownwardDiagonal:
bits = DashedDownwardDiagonal_bits; break;
case HatchStyle.DashedHorizontal:
bits = DashedHorizontal_bits; break;
case HatchStyle.DashedUpwardDiagonal:
bits = DashedUpwardDiagonal_bits; break;
case HatchStyle.DashedVertical:
bits = DashedVertical_bits; break;
case HatchStyle.DiagonalBrick:
bits = DiagonalBrick_bits; break;
case HatchStyle.DiagonalCross:
bits = DiagonalCross_bits; break;
case HatchStyle.Divot:
bits = Divot_bits; break;
case HatchStyle.DottedDiamond:
bits = DottedDiamond_bits; break;
case HatchStyle.DottedGrid:
bits = DottedGrid_bits; break;
case HatchStyle.ForwardDiagonal:
bits = ForwardDiagonal_bits; break;
case HatchStyle.Horizontal:
bits = Horizontal_bits; break;
case HatchStyle.HorizontalBrick:
bits = HorizontalBrick_bits; break;
case HatchStyle.LargeCheckerBoard:
bits = LargeCheckerBoard_bits; break;
case HatchStyle.LargeConfetti:
bits = LargeConfetti_bits; break;
case HatchStyle.LargeGrid:
bits = LargeGrid_bits; break;
case HatchStyle.LightDownwardDiagonal:
bits = LightDownwardDiagonal_bits; break;
case HatchStyle.LightHorizontal:
bits = LightHorizontal_bits; break;
case HatchStyle.LightUpwardDiagonal:
bits = LightUpwardDiagonal_bits; break;
case HatchStyle.LightVertical:
bits = LightVertical_bits; break;
case HatchStyle.NarrowHorizontal:
bits = NarrowHorizontal_bits; break;
case HatchStyle.NarrowVertical:
bits = NarrowVertical_bits; break;
case HatchStyle.OutlinedDiamond:
bits = OutlinedDiamond_bits; break;
case HatchStyle.Percent05:
bits = Percent05_bits; break;
case HatchStyle.Percent10:
bits = Percent10_bits; break;
case HatchStyle.Percent20:
bits = Percent20_bits; break;
case HatchStyle.Percent25:
bits = Percent25_bits; break;
case HatchStyle.Percent30:
bits = Percent30_bits; break;
case HatchStyle.Percent40:
bits = Percent40_bits; break;
case HatchStyle.Percent50:
bits = Percent50_bits; break;
case HatchStyle.Percent60:
bits = Percent60_bits; break;
case HatchStyle.Percent70:
bits = Percent70_bits; break;
case HatchStyle.Percent75:
bits = Percent75_bits; break;
case HatchStyle.Percent80:
bits = Percent80_bits; break;
case HatchStyle.Percent90:
bits = Percent90_bits; break;
case HatchStyle.Plaid:
bits = Plaid_bits; break;
case HatchStyle.Shingle:
bits = Shingle_bits; break;
case HatchStyle.SmallCheckerBoard:
bits = SmallCheckerBoard_bits; break;
case HatchStyle.SmallConfetti:
bits = SmallConfetti_bits; break;
case HatchStyle.SmallGrid:
bits = SmallGrid_bits; break;
case HatchStyle.SolidDiamond:
bits = SolidDiamond_bits; break;
case HatchStyle.Sphere:
bits = Sphere_bits; break;
case HatchStyle.Trellis:
bits = Trellis_bits; break;
case HatchStyle.Vertical:
bits = Vertical_bits; break;
case HatchStyle.Wave:
bits = Wave_bits; break;
case HatchStyle.Weave:
bits = Weave_bits; break;
case HatchStyle.WideDownwardDiagonal:
bits = WideDownwardDiagonal_bits; break;
case HatchStyle.WideUpwardDiagonal:
bits = WideUpwardDiagonal_bits; break;
case HatchStyle.ZigZag:
bits = ZigZag_bits; break;
default: return null;
}
return bits;
}
// Bitmap data for all of the hatch styles.
private static readonly byte[] BackwardDiagonal_bits = {
0x80,0x80,0x40,0x40,0x20,0x20,0x10,0x10,0x08,0x08,0x04,0x04,
0x02,0x02,0x01,0x01,0x80,0x80,0x40,0x40,0x20,0x20,0x10,0x10,
0x08,0x08,0x04,0x04,0x02,0x02,0x01,0x01};
private static readonly byte[] DarkDownwardDiagonal_bits = {
0x33,0x33,0x66,0x66,0xcc,0xcc,0x99,0x99,0x33,0x33,0x66,0x66,
0xcc,0xcc,0x99,0x99,0x33,0x33,0x66,0x66,0xcc,0xcc,0x99,0x99,
0x33,0x33,0x66,0x66,0xcc,0xcc,0x99,0x99};
private static readonly byte[] DarkHorizontal_bits = {
0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,
0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,
0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00};
private static readonly byte[] DarkUpwardDiagonal_bits = {
0xcc,0xcc,0x66,0x66,0x33,0x33,0x99,0x99,0xcc,0xcc,0x66,0x66,
0x33,0x33,0x99,0x99,0xcc,0xcc,0x66,0x66,0x33,0x33,0x99,0x99,
0xcc,0xcc,0x66,0x66,0x33,0x33,0x99,0x99};
private static readonly byte[] DarkVertical_bits = {
0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,
0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,0x33,
0x33,0x33,0x33,0x33,0x33,0x33, 0x33,0x33};
private static readonly byte[] DashedDownwardDiagonal_bits = {
0x00,0x00,0x00,0x00,0x11,0x11,0x22,0x22,0x44,0x44,0x88,0x88,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x11,0x11,0x22,0x22,
0x44,0x44,0x88,0x88,0x00,0x00,0x00,0x00};
private static readonly byte[] DashedHorizontal_bits = {
0x0f,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0xf0,0xf0,0x00,0x00,
0x00,0x00,0x00,0x00,0x0f,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,
0xf0,0xf0,0x00,0x00,0x00,0x00,0x00,0x00};
private static readonly byte[] DashedUpwardDiagonal_bits = {
0x00,0x00,0x00,0x00,0x88,0x88,0x44,0x44,0x22,0x22,0x11,0x11,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x88,0x88,0x44,0x44,
0x22,0x22,0x11,0x11,0x00,0x00,0x00,0x00};
private static readonly byte[] DashedVertical_bits = {
0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x10,0x10,0x10,0x10,
0x10,0x10,0x10,0x10,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10};
private static readonly byte[] DiagonalBrick_bits = {
0x80,0x80,0x40,0x40,0x20,0x20,0x10,0x10,0x18,0x18,0x24,0x24,
0x42,0x42,0x81,0x81,0x80,0x80,0x40,0x40,0x20,0x20,0x10,0x10,
0x18,0x18,0x24,0x24,0x42,0x42,0x81,0x81};
private static readonly byte[] DiagonalCross_bits = {
0x81,0x81,0x42,0x42,0x24,0x24,0x18,0x18,0x18,0x18,0x24,0x24,
0x42,0x42,0x81,0x81,0x81,0x81,0x42,0x42,0x24,0x24,0x18,0x18,
0x18,0x18,0x24,0x24,0x42,0x42,0x81,0x81};
private static readonly byte[] Divot_bits = {
0x00,0x00,0x08,0x08,0x10,0x10,0x08,0x08,0x00,0x00,0x01,0x01,
0x80,0x80,0x01,0x01,0x00,0x00,0x08,0x08,0x10,0x10,0x08,0x08,
0x00,0x00,0x01,0x01,0x80,0x80,0x01,0x01};
private static readonly byte[] DottedDiamond_bits = {
0x01,0x01,0x00,0x00,0x44,0x44,0x00,0x00,0x10,0x10,0x00,0x00,
0x44,0x44,0x00,0x00,0x01,0x01,0x00,0x00,0x44,0x44,0x00,0x00,
0x10,0x10,0x00,0x00,0x44,0x44,0x00,0x00};
private static readonly byte[] DottedGrid_bits = {
0x55,0x55,0x00,0x00,0x01,0x01,0x00,0x00,0x01,0x01,0x00,0x00,
0x01,0x01,0x00,0x00,0x55,0x55,0x00,0x00,0x01,0x01,0x00,0x00,
0x01,0x01,0x00,0x00,0x01,0x01,0x00,0x00};
private static readonly byte[] ForwardDiagonal_bits = {
0x01,0x01,0x02,0x02,0x04,0x04,0x08,0x08,0x10,0x10,0x20,0x20,
0x40,0x40,0x80,0x80,0x01,0x01,0x02,0x02,0x04,0x04,0x08,0x08,
0x10,0x10,0x20,0x20,0x40,0x40,0x80,0x80};
private static readonly byte[] Horizontal_bits = {
0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
private static readonly byte[] HorizontalBrick_bits = {
0xff,0xff,0x01,0x01,0x01,0x01,0x01,0x01,0xff,0xff,0x10,0x10,
0x10,0x10,0x10,0x10,0xff,0xff,0x01,0x01,0x01,0x01,0x01,0x01,
0xff,0xff,0x10,0x10,0x10,0x10,0x10,0x10};
private static readonly byte[] LargeCheckerBoard_bits = {
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0xf0,0xf0,0xf0,0xf0,
0xf0,0xf0,0xf0,0xf0,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,
0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0};
private static readonly byte[] LargeConfetti_bits = {
0x8d,0x8d,0x0c,0x0c,0xc0,0xc0,0xd8,0xd8,0x1b,0x1b,0x03,0x03,
0x30,0x30,0xb1,0xb1,0x8d,0x8d,0x0c,0x0c,0xc0,0xc0,0xd8,0xd8,
0x1b,0x1b,0x03,0x03,0x30,0x30,0xb1,0xb1};
private static readonly byte[] LargeGrid_bits = {
0xff,0xff,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,0xff,0xff,0x01,0x01,0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01};
private static readonly byte[] LightDownwardDiagonal_bits = {
0x11,0x11,0x22,0x22,0x44,0x44,0x88,0x88,0x11,0x11,0x22,0x22,
0x44,0x44,0x88,0x88,0x11,0x11,0x22,0x22,0x44,0x44,0x88,0x88,
0x11,0x11,0x22,0x22,0x44,0x44,0x88,0x88};
private static readonly byte[] LightHorizontal_bits = {
0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x00,0x00,
0x00,0x00,0x00,0x00,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,
0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00};
private static readonly byte[] LightUpwardDiagonal_bits = {
0x88,0x88,0x44,0x44,0x22,0x22,0x11,0x11,0x88,0x88,0x44,0x44,
0x22,0x22,0x11,0x11,0x88,0x88,0x44,0x44,0x22,0x22,0x11,0x11,
0x88,0x88,0x44,0x44,0x22,0x22,0x11,0x11};
private static readonly byte[] LightVertical_bits = {
0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,
0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,
0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11};
private static readonly byte[] NarrowHorizontal_bits = {
0xff,0xff,0x00,0x00,0xff,0xff,0x00,0x00,0xff,0xff,0x00,0x00,
0xff,0xff,0x00,0x00,0xff,0xff,0x00,0x00,0xff,0xff,0x00,0x00,
0xff,0xff,0x00,0x00,0xff,0xff,0x00,0x00};
private static readonly byte[] NarrowVertical_bits = {
0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,
0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,
0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa};
private static readonly byte[] OutlinedDiamond_bits = {
0x41,0x41,0x22,0x22,0x14,0x14,0x08,0x08,0x14,0x14,0x22,0x22,
0x41,0x41,0x80,0x80,0x41,0x41,0x22,0x22,0x14,0x14,0x08,0x08,
0x14,0x14,0x22,0x22,0x41,0x41,0x80,0x80};
private static readonly byte[] Percent05_bits = {
0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x10,0x00,0x00,
0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
0x10,0x10,0x00,0x00,0x00,0x00,0x00,0x00};
private static readonly byte[] Percent10_bits = {
0x01,0x01,0x00,0x00,0x10,0x10,0x00,0x00,0x01,0x01,0x00,0x00,
0x10,0x10,0x00,0x00,0x01,0x01,0x00,0x00,0x10,0x10,0x00,0x00,
0x01,0x01,0x00,0x00,0x10,0x10,0x00,0x00};
private static readonly byte[] Percent20_bits = {
0x11,0x11,0x00,0x00,0x44,0x44,0x00,0x00,0x11,0x11,0x00,0x00,
0x44,0x44,0x00,0x00,0x11,0x11,0x00,0x00,0x44,0x44,0x00,0x00,
0x11,0x11,0x00,0x00,0x44,0x44,0x00,0x00};
private static readonly byte[] Percent25_bits = {
0x11,0x11,0x44,0x44,0x11,0x11,0x44,0x44,0x11,0x11,0x44,0x44,
0x11,0x11,0x44,0x44,0x11,0x11,0x44,0x44,0x11,0x11,0x44,0x44,
0x11,0x11,0x44,0x44,0x11,0x11,0x44,0x44};
private static readonly byte[] Percent30_bits = {
0x55,0x55,0x22,0x22,0x55,0x55,0x88,0x88,0x55,0x55,0x22,0x22,
0x55,0x55,0x88,0x88,0x55,0x55,0x22,0x22,0x55,0x55,0x88,0x88,
0x55,0x55,0x22,0x22,0x55,0x55,0x88,0x88};
private static readonly byte[] Percent40_bits = {
0x55,0x55,0xaa,0xaa,0x55,0x55,0x8a,0x8a,0x55,0x55,0xaa,0xaa,
0x55,0x55,0xa8,0xa8,0x55,0x55,0xaa,0xaa,0x55,0x55,0x8a,0x8a,
0x55,0x55,0xaa,0xaa,0x55,0x55,0xa8,0xa8};
private static readonly byte[] Percent50_bits = {
0x55,0x55,0xaa,0xaa,0x55,0x55,0xaa,0xaa,0x55,0x55,0xaa,0xaa,
0x55,0x55,0xaa,0xaa,0x55,0x55,0xaa,0xaa,0x55,0x55,0xaa,0xaa,
0x55,0x55,0xaa,0xaa,0x55,0x55,0xaa,0xaa};
private static readonly byte[] Percent60_bits = {
0x77,0x77,0xaa,0xaa,0xdd,0xdd,0xaa,0xaa,0x77,0x77,0xaa,0xaa,
0xdd,0xdd,0xaa,0xaa,0x77,0x77,0xaa,0xaa,0xdd,0xdd,0xaa,0xaa,
0x77,0x77,0xaa,0xaa,0xdd,0xdd,0xaa,0xaa};
private static readonly byte[] Percent70_bits = {
0xee,0xee,0xbb,0xbb,0xee,0xee,0xbb,0xbb,0xee,0xee,0xbb,0xbb,
0xee,0xee,0xbb,0xbb,0xee,0xee,0xbb,0xbb,0xee,0xee,0xbb,0xbb,
0xee,0xee,0xbb,0xbb,0xee,0xee,0xbb,0xbb};
private static readonly byte[] Percent75_bits = {
0xee,0xee,0xff,0xff,0xbb,0xbb,0xff,0xff,0xee,0xee,0xff,0xff,
0xbb,0xbb,0xff,0xff,0xee,0xee,0xff,0xff,0xbb,0xbb,0xff,0xff,
0xee,0xee,0xff,0xff,0xbb,0xbb,0xff,0xff};
private static readonly byte[] Percent80_bits = {
0xf7,0xf7,0xff,0xff,0x7f,0x7f,0xff,0xff,0xf7,0xf7,0xff,0xff,
0x7f,0x7f,0xff,0xff,0xf7,0xf7,0xff,0xff,0x7f,0x7f,0xff,0xff,
0xf7,0xf7,0xff,0xff,0x7f,0x7f,0xff,0xff};
private static readonly byte[] Percent90_bits = {
0xff,0xff,0xff,0xff,0xff,0xff,0xef,0xef,0xff,0xff,0xff,0xff,
0xff,0xff,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xef,0xef,
0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe};
private static readonly byte[] Plaid_bits = {
0x55,0x55,0xaa,0xaa,0x55,0x55,0xaa,0xaa,0x0f,0x0f,0x0f,0x0f,
0x0f,0x0f,0x0f,0x0f,0x55,0x55,0xaa,0xaa,0x55,0x55,0xaa,0xaa,
0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f,0x0f};
private static readonly byte[] Shingle_bits = {
0xc0,0xc0,0x21,0x21,0x12,0x12,0x0c,0x0c,0x30,0x30,0x40,0x40,
0x80,0x80,0x80,0x80,0xc0,0xc0,0x21,0x21,0x12,0x12,0x0c,0x0c,
0x30,0x30,0x40,0x40,0x80,0x80,0x80,0x80};
private static readonly byte[] SmallCheckerBoard_bits = {
0x99,0x99,0x66,0x66,0x66,0x66,0x99,0x99,0x99,0x99,0x66,0x66,
0x66,0x66,0x99,0x99,0x99,0x99,0x66,0x66,0x66,0x66,0x99,0x99,
0x99,0x99,0x66,0x66,0x66,0x66,0x99,0x99};
private static readonly byte[] SmallConfetti_bits = {
0x01,0x01,0x10,0x10,0x02,0x02,0x40,0x40,0x08,0x08,0x80,0x80,
0x04,0x04,0x20,0x20,0x01,0x01,0x10,0x10,0x02,0x02,0x40,0x40,
0x08,0x08,0x80,0x80,0x04,0x04,0x20,0x20};
private static readonly byte[] SmallGrid_bits = {
0xff,0xff,0x11,0x11,0x11,0x11,0x11,0x11,0xff,0xff,0x11,0x11,
0x11,0x11,0x11,0x11,0xff,0xff,0x11,0x11,0x11,0x11,0x11,0x11,
0xff,0xff,0x11,0x11,0x11,0x11,0x11,0x11};
private static readonly byte[] SolidDiamond_bits = {
0x08,0x08,0x1c,0x1c,0x3e,0x3e,0x7f,0x7f,0x3e,0x3e,0x1c,0x1c,
0x08,0x08,0x00,0x00,0x08,0x08,0x1c,0x1c,0x3e,0x3e,0x7f,0x7f,
0x3e,0x3e,0x1c,0x1c,0x08,0x08,0x00,0x00};
private static readonly byte[] Sphere_bits = {
0xee,0xee,0x91,0x91,0xf1,0xf1,0xf1,0xf1,0xee,0xee,0x19,0x19,
0x1f,0x1f,0x1f,0x1f,0xee,0xee,0x91,0x91,0xf1,0xf1,0xf1,0xf1,
0xee,0xee,0x19,0x19,0x1f,0x1f,0x1f,0x1f};
private static readonly byte[] Trellis_bits = {
0xff,0xff,0x66,0x66,0xff,0xff,0x99,0x99,0xff,0xff,0x66,0x66,
0xff,0xff,0x99,0x99,0xff,0xff,0x66,0x66,0xff,0xff,0x99,0x99,
0xff,0xff,0x66,0x66,0xff,0xff,0x99,0x99};
private static readonly byte[] Vertical_bits = {
0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01};
private static readonly byte[] Wave_bits = {
0x00,0x00,0x18,0x18,0xa4,0xa4,0x03,0x03,0x00,0x00,0x18,0x18,
0xa4,0xa4,0x03,0x03,0x00,0x00,0x18,0x18,0xa4,0xa4,0x03,0x03,
0x00,0x00,0x18,0x18,0xa4,0xa4,0x03,0x03};
private static readonly byte[] Weave_bits = {
0x11,0x11,0x2a,0x2a,0x44,0x44,0xa2,0xa2,0x11,0x11,0x28,0x28,
0x44,0x44,0x8a,0x8a,0x11,0x11,0x2a,0x2a,0x44,0x44,0xa2,0xa2,
0x11,0x11,0x28,0x28,0x44,0x44,0x8a,0x8a};
private static readonly byte[] WideDownwardDiagonal_bits = {
0x83,0x83,0x07,0x07,0x0e,0x0e,0x1c,0x1c,0x38,0x38,0x70,0x70,
0xe0,0xe0,0xc1,0xc1,0x83,0x83,0x07,0x07,0x0e,0x0e,0x1c,0x1c,
0x38,0x38,0x70,0x70,0xe0,0xe0,0xc1,0xc1};
private static readonly byte[] WideUpwardDiagonal_bits = {
0xc1,0xc1,0xe0,0xe0,0x70,0x70,0x38,0x38,0x1c,0x1c,0x0e,0x0e,
0x07,0x07,0x83,0x83,0xc1,0xc1,0xe0,0xe0,0x70,0x70,0x38,0x38,
0x1c,0x1c,0x0e,0x0e,0x07,0x07,0x83,0x83};
private static readonly byte[] ZigZag_bits = {
0x81,0x81,0x42,0x42,0x24,0x24,0x18,0x18,0x81,0x81,0x42,0x42,
0x24,0x24,0x18,0x18,0x81,0x81,0x42,0x42,0x24,0x24,0x18,0x18,
0x81,0x81,0x42,0x42,0x24,0x24,0x18,0x18};
}; // class ToolkitBrushBase
}; // namespace System.Drawing.Toolkit
| |
// 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.IO;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public abstract class WebRequest : MarshalByRefObject, ISerializable
{
internal class WebRequestPrefixElement
{
public readonly string Prefix;
public readonly IWebRequestCreate Creator;
public WebRequestPrefixElement(string prefix, IWebRequestCreate creator)
{
Prefix = prefix;
Creator = creator;
}
}
private static List<WebRequestPrefixElement> s_prefixList;
private static object s_internalSyncObject = new object();
internal const int DefaultTimeoutMilliseconds = 100 * 1000;
protected WebRequest() { }
protected WebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
// Create a WebRequest.
//
// This is the main creation routine. We take a Uri object, look
// up the Uri in the prefix match table, and invoke the appropriate
// handler to create the object. We also have a parameter that
// tells us whether or not to use the whole Uri or just the
// scheme portion of it.
//
// Input:
// requestUri - Uri object for request.
// useUriBase - True if we're only to look at the scheme portion of the Uri.
//
// Returns:
// Newly created WebRequest.
private static WebRequest Create(Uri requestUri, bool useUriBase)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, requestUri);
string LookupUri;
WebRequestPrefixElement Current = null;
bool Found = false;
if (!useUriBase)
{
LookupUri = requestUri.AbsoluteUri;
}
else
{
// schemes are registered as <schemeName>":", so add the separator
// to the string returned from the Uri object
LookupUri = requestUri.Scheme + ':';
}
int LookupLength = LookupUri.Length;
// Copy the prefix list so that if it is updated it will
// not affect us on this thread.
List<WebRequestPrefixElement> prefixList = PrefixList;
// Look for the longest matching prefix.
// Walk down the list of prefixes. The prefixes are kept longest
// first. When we find a prefix that is shorter or the same size
// as this Uri, we'll do a compare to see if they match. If they
// do we'll break out of the loop and call the creator.
for (int i = 0; i < prefixList.Count; i++)
{
Current = prefixList[i];
// See if this prefix is short enough.
if (LookupLength >= Current.Prefix.Length)
{
// It is. See if these match.
if (string.Compare(Current.Prefix,
0,
LookupUri,
0,
Current.Prefix.Length,
StringComparison.OrdinalIgnoreCase) == 0)
{
// These match. Remember that we found it and break
// out.
Found = true;
break;
}
}
}
WebRequest webRequest = null;
if (Found)
{
// We found a match, so just call the creator and return what it does.
webRequest = Current.Creator.Create(requestUri);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, webRequest);
return webRequest;
}
// Otherwise no match, throw an exception.
if (NetEventSource.IsEnabled) NetEventSource.Exit(null);
throw new NotSupportedException(SR.net_unknown_prefix);
}
// Create - Create a WebRequest.
//
// An overloaded utility version of the real Create that takes a
// string instead of an Uri object.
//
// Input:
// RequestString - Uri string to create.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException(nameof(requestUriString));
}
return Create(new Uri(requestUriString), false);
}
// Create - Create a WebRequest.
//
// Another overloaded version of the Create function that doesn't
// take the UseUriBase parameter.
//
// Input:
// requestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
return Create(requestUri, false);
}
// CreateDefault - Create a default WebRequest.
//
// This is the creation routine that creates a default WebRequest.
// We take a Uri object and pass it to the base create routine,
// setting the useUriBase parameter to true.
//
// Input:
// RequestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
public static WebRequest CreateDefault(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
return Create(requestUri, true);
}
public static HttpWebRequest CreateHttp(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException(nameof(requestUriString));
}
return CreateHttp(new Uri(requestUriString));
}
public static HttpWebRequest CreateHttp(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
if ((requestUri.Scheme != "http") && (requestUri.Scheme != "https"))
{
throw new NotSupportedException(SR.net_unknown_prefix);
}
return (HttpWebRequest)CreateDefault(requestUri);
}
// RegisterPrefix - Register an Uri prefix for creating WebRequests.
//
// This function registers a prefix for creating WebRequests. When an
// user wants to create a WebRequest, we scan a table looking for a
// longest prefix match for the Uri they're passing. We then invoke
// the sub creator for that prefix. This function puts entries in
// that table.
//
// We don't allow duplicate entries, so if there is a dup this call
// will fail.
//
// Input:
// Prefix - Represents Uri prefix being registered.
// Creator - Interface for sub creator.
//
// Returns:
// True if the registration worked, false otherwise.
public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
{
bool Error = false;
int i;
WebRequestPrefixElement Current;
if (prefix == null)
{
throw new ArgumentNullException(nameof(prefix));
}
if (creator == null)
{
throw new ArgumentNullException(nameof(creator));
}
// Lock this object, then walk down PrefixList looking for a place to
// to insert this prefix.
lock (s_internalSyncObject)
{
// Clone the object and update the clone, thus
// allowing other threads to still read from the original.
List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>(PrefixList);
// As AbsoluteUri is used later for Create, account for formating changes
// like Unicode escaping, default ports, etc.
Uri tempUri;
if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri))
{
string cookedUri = tempUri.AbsoluteUri;
// Special case for when a partial host matching is requested, drop the added trailing slash
// IE: http://host could match host or host.domain
if (!prefix.EndsWith("/", StringComparison.Ordinal)
&& tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped)
.Equals("/"))
{
cookedUri = cookedUri.Substring(0, cookedUri.Length - 1);
}
prefix = cookedUri;
}
i = 0;
// The prefix list is sorted with longest entries at the front. We
// walk down the list until we find a prefix shorter than this
// one, then we insert in front of it. Along the way we check
// equal length prefixes to make sure this isn't a dupe.
while (i < prefixList.Count)
{
Current = prefixList[i];
// See if the new one is longer than the one we're looking at.
if (prefix.Length > Current.Prefix.Length)
{
// It is. Break out of the loop here.
break;
}
// If these are of equal length, compare them.
if (prefix.Length == Current.Prefix.Length)
{
// They're the same length.
if (string.Equals(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase))
{
// ...and the strings are identical. This is an error.
Error = true;
break;
}
}
i++;
}
// When we get here either i contains the index to insert at or
// we've had an error, in which case Error is true.
if (!Error)
{
// No error, so insert.
prefixList.Insert(i, new WebRequestPrefixElement(prefix, creator));
// Assign the clone to the static object. Other threads using it
// will have copied the original object already.
PrefixList = prefixList;
}
}
return !Error;
}
internal class HttpRequestCreator : IWebRequestCreate
{
// Create - Create an HttpWebRequest.
//
// This is our method to create an HttpWebRequest. We register
// for HTTP and HTTPS Uris, and this method is called when a request
// needs to be created for one of those.
//
//
// Input:
// uri - Uri for request being created.
//
// Returns:
// The newly created HttpWebRequest.
public WebRequest Create(Uri Uri)
{
return new HttpWebRequest(Uri);
}
}
// PrefixList - Returns And Initialize our prefix list.
//
//
// This is the method that initializes the prefix list. We create
// an List for the PrefixList, then each of the request creators,
// and then we register them with the associated prefixes.
//
// Returns:
// true
internal static List<WebRequestPrefixElement> PrefixList
{
get
{
// GetConfig() might use us, so we have a circular dependency issue
// that causes us to nest here. We grab the lock only if we haven't
// initialized.
return LazyInitializer.EnsureInitialized(ref s_prefixList, ref s_internalSyncObject, () =>
{
var httpRequestCreator = new HttpRequestCreator();
var ftpRequestCreator = new FtpWebRequestCreator();
var fileRequestCreator = new FileWebRequestCreator();
const int Count = 4;
var prefixList = new List<WebRequestPrefixElement>(Count)
{
new WebRequestPrefixElement("http:", httpRequestCreator),
new WebRequestPrefixElement("https:", httpRequestCreator),
new WebRequestPrefixElement("ftp:", ftpRequestCreator),
new WebRequestPrefixElement("file:", fileRequestCreator),
};
Debug.Assert(prefixList.Count == Count, $"Expected {Count}, got {prefixList.Count}");
return prefixList;
});
}
set
{
Volatile.Write(ref s_prefixList, value);
}
}
public static RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public virtual RequestCachePolicy CachePolicy { get; set; }
public AuthenticationLevel AuthenticationLevel { get; set; } = AuthenticationLevel.MutualAuthRequested;
public TokenImpersonationLevel ImpersonationLevel { get; set; } = TokenImpersonationLevel.Delegation;
public virtual string ConnectionGroupName
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual string Method
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual Uri RequestUri
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual WebHeaderCollection Headers
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual long ContentLength
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual string ContentType
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual ICredentials Credentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual int Timeout
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual bool UseDefaultCredentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual Stream GetRequestStream()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual WebResponse GetResponse()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual WebResponse EndGetResponse(IAsyncResult asyncResult)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual Stream EndGetRequestStream(IAsyncResult asyncResult)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual Task<Stream> GetRequestStreamAsync()
{
// Offload to a different thread to avoid blocking the caller during request submission.
// We use Task.Run rather than Task.Factory.StartNew even though StartNew would let us pass 'this'
// as a state argument to avoid the closure to capture 'this' and the associated delegate.
// This is because the task needs to call FromAsync and marshal the inner Task out, and
// Task.Run's implementation of this is sufficiently more efficient than what we can do with
// Unwrap() that it's worth it to just rely on Task.Run and accept the closure/delegate.
return Task.Run(() =>
Task<Stream>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetRequestStream(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetRequestStream(iar),
this));
}
public virtual Task<WebResponse> GetResponseAsync()
{
// See comment in GetRequestStreamAsync(). Same logic applies here.
return Task.Run(() =>
Task<WebResponse>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetResponse(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetResponse(iar),
this));
}
public virtual void Abort()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
private static IWebProxy s_DefaultWebProxy;
private static bool s_DefaultWebProxyInitialized;
public static IWebProxy GetSystemWebProxy() => HttpClient.DefaultProxy;
public static IWebProxy DefaultWebProxy
{
get
{
return LazyInitializer.EnsureInitialized(ref s_DefaultWebProxy, ref s_DefaultWebProxyInitialized, ref s_internalSyncObject, () => GetSystemWebProxy());
}
set
{
lock (s_internalSyncObject)
{
s_DefaultWebProxy = value;
s_DefaultWebProxyInitialized = true;
}
}
}
public virtual bool PreAuthenticate
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual IWebProxy Proxy
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal class AttributeNamedParameterCompletionProvider : CommonCompletionProvider
{
private const string EqualsString = "=";
private const string SpaceEqualsString = " =";
private const string ColonString = ":";
private static readonly CompletionItemRules _spaceItemFilterRule = CompletionItemRules.Default.WithFilterCharacterRule(
CharacterSetModificationRule.Create(CharacterSetModificationKind.Remove, ' '));
internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options);
}
public override async Task ProvideCompletionsAsync(CompletionContext context)
{
var document = context.Document;
var position = context.Position;
var cancellationToken = context.CancellationToken;
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (syntaxTree.IsInNonUserCode(position, cancellationToken))
{
return;
}
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken))
{
return;
}
var attributeArgumentList = token.Parent as AttributeArgumentListSyntax;
var attributeSyntax = token.Parent.Parent as AttributeSyntax;
if (attributeSyntax == null || attributeArgumentList == null)
{
return;
}
if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token))
{
context.IsExclusive = true;
}
// We actually want to collect two sets of named parameters to present the user. The
// normal named parameters that come from the attribute constructors. These will be
// presented like "foo:". And also the named parameters that come from the writable
// fields/properties in the attribute. These will be presented like "bar =".
var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position);
var workspace = document.Project.Solution.Workspace;
var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false);
var nameColonItems = await GetNameColonItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false);
var nameEqualsItems = await GetNameEqualsItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false);
context.AddItems(nameEqualsItems);
// If we're after a name= parameter, then we only want to show name= parameters.
// Otherwise, show name: parameters too.
if (!IsAfterNameEqualsArgument(token))
{
context.AddItems(nameColonItems);
}
}
private bool IsAfterNameColonArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
private bool IsAfterNameEqualsArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameEquals != null)
{
return true;
}
}
}
}
return false;
}
private async Task<ImmutableArray<CompletionItem>> GetNameEqualsItemsAsync(
CompletionContext context, SemanticModel semanticModel,
SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters)
{
var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, context.Position, attributeSyntax, context.CancellationToken);
var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name));
var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false);
var q = from p in attributeNamedParameters
where !existingNamedParameters.Contains(p.Name)
select SymbolCompletionItem.CreateWithSymbolId(
displayText: p.Name.ToIdentifierToken().ToString() + SpaceEqualsString,
insertionText: null,
symbol: p,
contextPosition: token.SpanStart,
sortText: p.Name,
rules: _spaceItemFilterRule);
return q.ToImmutableArray();
}
private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync(
CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters)
{
var parameterLists = GetParameterLists(semanticModel, context.Position, attributeSyntax, context.CancellationToken);
parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters));
var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false);
return from pl in parameterLists
from p in pl
where !existingNamedParameters.Contains(p.Name)
select SymbolCompletionItem.CreateWithSymbolId(
displayText: p.Name.ToIdentifierToken().ToString() + ColonString,
insertionText: null,
symbol: p,
contextPosition: token.SpanStart,
sortText: p.Name,
rules: CompletionItemRules.Default);
}
protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
=> SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken);
private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters)
{
return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty();
}
private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position)
{
var existingArguments1 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameColon != null)
.Select(a => a.NameColon.Name.Identifier.ValueText);
var existingArguments2 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameEquals != null)
.Select(a => a.NameEquals.Name.Identifier.ValueText);
return existingArguments1.Concat(existingArguments2).ToSet();
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
if (within != null && attributeType != null)
{
return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
}
return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>();
}
private IEnumerable<ISymbol> GetAttributeNamedParameters(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within);
}
protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken)
{
return Task.FromResult(GetTextChange(selectedItem, ch));
}
private TextChange? GetTextChange(CompletionItem selectedItem, char? ch)
{
var displayText = selectedItem.DisplayText;
if (ch != null)
{
// If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The
// typed space character will be passed through to the editor, and they can then type the '='.
if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - SpaceEqualsString.Length));
}
// If the user types '=', do not complete the '=' at the end of the named parameter because the typed '='
// will be passed through to the editor.
if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - EqualsString.Length));
}
// If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':'
// will be passed through to the editor.
if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal))
{
return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - ColonString.Length));
}
}
return new TextChange(selectedItem.Span, displayText);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.ProvideCorrectArgumentsToFormattingMethodsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.ProvideCorrectArgumentsToFormattingMethodsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class ProvideCorrectArgumentsToFormattingMethodsTests
{
#region Diagnostic Tests
[Fact]
public async Task CA2241CSharpStringAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
void Method()
{
var a = String.Format("""", 1);
var b = String.Format(""{0}"", 1, 2);
var c = String.Format(""{0} {1}"", 1, 2, 3);
var d = String.Format(""{0} {1} {2}"", 1, 2, 3, 4);
var e = string.Format(""{0} {0}"", 1, 2);
IFormatProvider p = null;
var f = String.Format(p, """", 1);
var g = String.Format(p, ""{0}"", 1, 2);
var h = String.Format(p, ""{0} {1}"", 1, 2, 3);
var i = String.Format(p, ""{0} {1} {2}"", 1, 2, 3, 4);
}
}
",
GetCSharpResultAt(8, 17),
GetCSharpResultAt(9, 17),
GetCSharpResultAt(10, 17),
GetCSharpResultAt(11, 17),
GetCSharpResultAt(12, 17),
GetCSharpResultAt(15, 17),
GetCSharpResultAt(16, 17),
GetCSharpResultAt(17, 17),
GetCSharpResultAt(18, 17));
}
[Fact]
public async Task CA2241CSharpConsoleWriteAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
void Method()
{
Console.Write("""", 1);
Console.Write(""{0}"", 1, 2);
Console.Write(""{0} {1}"", 1, 2, 3);
Console.Write(""{0} {1} {2}"", 1, 2, 3, 4);
Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5);
}
}
",
GetCSharpResultAt(8, 9),
GetCSharpResultAt(9, 9),
GetCSharpResultAt(10, 9),
GetCSharpResultAt(11, 9),
GetCSharpResultAt(12, 9));
}
[Fact]
public async Task CA2241CSharpConsoleWriteLineAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
void Method()
{
Console.WriteLine("""", 1);
Console.WriteLine(""{0}"", 1, 2);
Console.WriteLine(""{0} {1}"", 1, 2, 3);
Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4);
Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5);
}
}
",
GetCSharpResultAt(8, 9),
GetCSharpResultAt(9, 9),
GetCSharpResultAt(10, 9),
GetCSharpResultAt(11, 9),
GetCSharpResultAt(12, 9));
}
[Fact]
public async Task CA2241CSharpPassingAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
void Method()
{
var a = String.Format(""{0}"", 1);
var b = String.Format(""{0} {1}"", 1, 2);
var c = String.Format(""{0} {1} {2}"", 1, 2, 3);
var d = String.Format(""{0} {1} {2} {3}"", 1, 2, 3, 4);
var e = String.Format(""{0} {1} {2} {0}"", 1, 2, 3);
Console.Write(""{0}"", 1);
Console.Write(""{0} {1}"", 1, 2);
Console.Write(""{0} {1} {2}"", 1, 2, 3);
Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4);
Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5);
Console.Write(""{0} {1} {2} {3} {0}"", 1, 2, 3, 4);
Console.WriteLine(""{0}"", 1);
Console.WriteLine(""{0} {1}"", 1, 2);
Console.WriteLine(""{0} {1} {2}"", 1, 2, 3);
Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4);
Console.WriteLine(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5);
Console.WriteLine(""{0} {1} {2} {3} {0}"", 1, 2, 3, 4);
}
}
");
}
[Fact]
public async Task CA2241CSharpExplicitObjectArraySupportedAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
void Method()
{
var s = String.Format(""{0} {1} {2} {3}"", new object[] {1, 2});
Console.Write(""{0} {1} {2} {3}"", new object[] {1, 2, 3, 4, 5});
Console.WriteLine(""{0} {1} {2} {3}"", new object[] {1, 2, 3, 4, 5});
}
}
",
GetCSharpResultAt(8, 17),
GetCSharpResultAt(9, 9),
GetCSharpResultAt(10, 9));
}
[Fact]
public async Task CA2241CSharpVarArgsNotSupportedAsync()
{
// currently not supported due to "https://github.com/dotnet/roslyn/issues/7346"
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default,
TestCode = @"
using System;
public class C
{
void Method()
{
Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, __arglist(5));
Console.WriteLine(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, __arglist(5));
}
}
",
}.RunAsync();
}
[Fact]
public async Task CA2241VBStringAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C
Sub Method()
Dim a = String.Format("""", 1)
Dim b = String.Format(""{0}"", 1, 2)
Dim c = String.Format(""{0} {1}"", 1, 2, 3)
Dim d = String.Format(""{0} {1} {2}"", 1, 2, 3, 4)
Dim p as IFormatProvider = Nothing
Dim e = String.Format(p, """", 1)
Dim f = String.Format(p, ""{0}"", 1, 2)
Dim g = String.Format(p, ""{0} {1}"", 1, 2, 3)
Dim h = String.Format(p, ""{0} {1} {2}"", 1, 2, 3, 4)
End Sub
End Class
",
GetBasicResultAt(6, 17),
GetBasicResultAt(7, 17),
GetBasicResultAt(8, 17),
GetBasicResultAt(9, 17),
GetBasicResultAt(12, 17),
GetBasicResultAt(13, 17),
GetBasicResultAt(14, 17),
GetBasicResultAt(15, 17));
}
[Fact]
public async Task CA2241VBConsoleWriteAsync()
{
// this works in VB
// Dim s = Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4)
// since VB bind it to __arglist version where we skip analysis
// due to a bug - https://github.com/dotnet/roslyn/issues/7346
// we might skip it only in C# since VB doesn't support __arglist
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C
Sub Method()
Console.Write("""", 1)
Console.Write(""{0}"", 1, 2)
Console.Write(""{0} {1}"", 1, 2, 3)
Console.Write(""{0} {1} {2}"", 1, 2, 3, 4)
Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5)
End Sub
End Class
",
GetBasicResultAt(6, 9),
GetBasicResultAt(7, 9),
GetBasicResultAt(8, 9),
#if NETCOREAPP
GetBasicResultAt(9, 9),
#endif
GetBasicResultAt(10, 9));
}
[Fact]
public async Task CA2241VBConsoleWriteLineAsync()
{
// this works in VB
// Dim s = Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4)
// since VB bind it to __arglist version where we skip analysis
// due to a bug - https://github.com/dotnet/roslyn/issues/7346
// we might skip it only in C# since VB doesn't support __arglist
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C
Sub Method()
Console.WriteLine("""", 1)
Console.WriteLine(""{0}"", 1, 2)
Console.WriteLine(""{0} {1}"", 1, 2, 3)
Console.WriteLine(""{0} {1} {2}"", 1, 2, 3, 4)
Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4, 5)
End Sub
End Class
",
GetBasicResultAt(6, 9),
GetBasicResultAt(7, 9),
GetBasicResultAt(8, 9),
#if NETCOREAPP
GetBasicResultAt(9, 9),
#endif
GetBasicResultAt(10, 9));
}
[Fact]
public async Task CA2241VBPassingAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C
Sub Method()
Dim a = String.Format(""{0}"", 1)
Dim b = String.Format(""{0} {1}"", 1, 2)
Dim c = String.Format(""{0} {1} {2}"", 1, 2, 3)
Dim d = String.Format(""{0} {1} {2} {3}"", 1, 2, 3, 4)
Console.Write(""{0}"", 1)
Console.Write(""{0} {1}"", 1, 2)
Console.Write(""{0} {1} {2}"", 1, 2, 3)
Console.Write(""{0} {1} {2} {3}"", 1, 2, 3, 4)
Console.Write(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5)
Console.WriteLine(""{0}"", 1)
Console.WriteLine(""{0} {1}"", 1, 2)
Console.WriteLine(""{0} {1} {2}"", 1, 2, 3)
Console.WriteLine(""{0} {1} {2} {3}"", 1, 2, 3, 4)
Console.WriteLine(""{0} {1} {2} {3} {4}"", 1, 2, 3, 4, 5)
End Sub
End Class
");
}
[Fact]
public async Task CA2241VBExplicitObjectArraySupportedAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class C
Sub Method()
Dim s = String.Format(""{0} {1} {2} {3}"", New Object() {1, 2})
Console.Write(""{0} {1} {2} {3}"", New Object() {1, 2, 3, 4, 5})
Console.WriteLine(""{0} {1} {2} {3}"", New Object() {1, 2, 3, 4, 5})
End Sub
End Class
",
GetBasicResultAt(6, 17),
GetBasicResultAt(7, 9),
GetBasicResultAt(8, 9));
}
[Fact]
public async Task CA2241CSharpFormatStringParserAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class C
{
void Method()
{
var a = String.Format(""{0,-4 :xd}"", 1);
var b = String.Format(""{0 , 5 : d} {1}"", 1, 2);
var c = String.Format(""{0:d} {1} {2}"", 1, 2, 3);
var d = String.Format(""{0, 5} {1} {2} {3}"", 1, 2, 3, 4);
Console.Write(""{0,1}"", 1);
Console.Write(""{0: x} {1}"", 1, 2);
Console.Write(""{{escape}}{0} {1} {2}"", 1, 2, 3);
Console.Write(""{0: {{escape}} x} {1} {2} {3}"", 1, 2, 3, 4);
Console.Write(""{0 , -10 : {{escape}} y} {1} {2} {3} {4}"", 1, 2, 3, 4, 5);
}
}
");
}
[Theory]
[WorkItem(2799, "https://github.com/dotnet/roslyn-analyzers/issues/2799")]
// No configuration - validate no diagnostics in default configuration
[InlineData(null)]
// Configured but disabled
[InlineData(false)]
// Configured and enabled
[InlineData(true)]
public async Task EditorConfigConfiguration_HeuristicAdditionalStringFormattingMethodsAsync(bool? editorConfig)
{
string editorConfigText = editorConfig == null ? string.Empty :
"dotnet_code_quality.try_determine_additional_string_formatting_methods_automatically = " + editorConfig.Value;
var csharpTest = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
class Test
{
public static string MyFormat(string format, params object[] args) => format;
void M1(string param)
{
var a = MyFormat("""", 1);
}
}"
},
AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true
[*]
{editorConfigText}
") }
}
};
if (editorConfig == true)
{
csharpTest.ExpectedDiagnostics.Add(
// Test0.cs(8,17): warning CA2241: Provide correct arguments to formatting methods
GetCSharpResultAt(8, 17));
}
await csharpTest.RunAsync();
var basicTest = new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Class Test
Public Shared Function MyFormat(format As String, ParamArray args As Object()) As String
Return format
End Function
Private Sub M1(ByVal param As String)
Dim a = MyFormat("""", 1)
End Sub
End Class"
},
AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true
[*]
{editorConfigText}
") }
}
};
if (editorConfig == true)
{
basicTest.ExpectedDiagnostics.Add(
// Test0.vb(8,17): warning CA2241: Provide correct arguments to formatting methods
GetBasicResultAt(8, 17));
}
await basicTest.RunAsync();
}
[Theory]
[WorkItem(2799, "https://github.com/dotnet/roslyn-analyzers/issues/2799")]
// No configuration - validate no diagnostics in default configuration
[InlineData("")]
// Match by method name
[InlineData("dotnet_code_quality.additional_string_formatting_methods = MyFormat")]
// Setting only for Rule ID
[InlineData("dotnet_code_quality." + ProvideCorrectArgumentsToFormattingMethodsAnalyzer.RuleId + ".additional_string_formatting_methods = MyFormat")]
// Match by documentation ID without "M:" prefix
[InlineData("dotnet_code_quality.additional_string_formatting_methods = Test.MyFormat(System.String,System.Object[])~System.String")]
// Match by documentation ID with "M:" prefix
[InlineData("dotnet_code_quality.additional_string_formatting_methods = M:Test.MyFormat(System.String,System.Object[])~System.String")]
public async Task EditorConfigConfiguration_AdditionalStringFormattingMethodsAsync(string editorConfigText)
{
var csharpTest = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
class Test
{
public static string MyFormat(string format, params object[] args) => format;
void M1(string param)
{
var a = MyFormat("""", 1);
}
}"
},
AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true
[*]
{editorConfigText}
") }
}
};
if (editorConfigText.Length > 0)
{
csharpTest.ExpectedDiagnostics.Add(
// Test0.cs(8,17): warning CA2241: Provide correct arguments to formatting methods
GetCSharpResultAt(8, 17));
}
await csharpTest.RunAsync();
var basicTest = new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Class Test
Public Shared Function MyFormat(format As String, ParamArray args As Object()) As String
Return format
End Function
Private Sub M1(ByVal param As String)
Dim a = MyFormat("""", 1)
End Sub
End Class"
},
AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true
[*]
{editorConfigText}
") }
}
};
if (editorConfigText.Length > 0)
{
basicTest.ExpectedDiagnostics.Add(
// Test0.vb(8,17): warning CA2241: Provide correct arguments to formatting methods
GetBasicResultAt(8, 17));
}
await basicTest.RunAsync();
}
#endregion
private static DiagnosticResult GetCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column);
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult GetBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
| |
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.SceneManagement;
using createMaterials;
using ChangeTheColor;
[RequireComponent(typeof(MeshCollider))]
//Attach this script to the camera
//set guiskin
//In Project Settings add Identify and ClearLabel to Input with I and L respectively
public class IdentifyItem : MonoBehaviour
{
//public Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// RaycastHit hit;
// Use this for initialization
public Rect WindowRect = new Rect (60, 20, 420, 30);
public float RotationDegrees = 5;
public float distanceFrom = 65.0f;
public float speed = 1;
//private RaycastHit hit;
public GUISkin guiSkin;
public bool doWindow0 = false;
public GameObject DaisPrefab;
public float X_MouseSensitivity = 5f;
public float Y_MouseSensitivity = 5f;
public int moveLayer = 27;
private bool labelOn = false;
private GameObject go;
private Vector3 screenPoint;
private Vector3 offset;
private Vector3 scanPos;
private Ray ray = new Ray ();
private bool isPrinted = false;
//GameObject read = Document_IO.readFile("NewObjectPosition.txt");
public Color newColor = Color.green;
//used to change element colors
//ChangeTheColor.ChangeColor newcolor= new ChangeColor();
void Awake ()
{
labelOn = false;
ChangeTheColor.extractColorFromString.readColorFile ("changedColour.txt");
}
void Update ()
{
IdentifyObject ();
if (Input.GetButtonUp ("ClearLabel")) {
ClickedObject = "";
labelOn = !labelOn;
}
if (Input.GetMouseButtonDown (0) && Input.GetKey (KeyCode.LeftShift))
Rotate (RotationDegrees);
if (Input.GetMouseButtonDown (0) && Input.GetKey (KeyCode.RightShift))
Rotate (-RotationDegrees);
if (Input.GetKey (KeyCode.Z)) {
MoveObject (-1, 1);
}
if (Input.GetKey (KeyCode.X)) {
MoveObject (1, 1);
}
if (Input.GetKey (KeyCode.C)) {
MoveObject (-1, 0);
}
if (Input.GetKey (KeyCode.V)) {
MoveObject (1, 0);
}
///
///Write the current GO from Ray to the file
if (Input.GetKey (KeyCode.T)) {
if (!isPrinted)
writeGOtoFILE ("NewObjectPosition.txt", true);
}
}
void writeGOtoFILE (string Filename, bool newline)
{
string tmp = "";
switch (Filename) {
case "NewObjectPosition.txt":
Vector3 lines = go.transform.parent.localPosition;
tmp = go.transform.parent.name + ",";
tmp = tmp + lines.ToString () + ",";
tmp = tmp + go.transform.parent.localRotation;
break;
case "changedColour.txt":
//string str = hit.collider.gameObject.name;
//tmp = go.transform.parent.name + ",";
//tmp = tmp + str.ToString () + ",";
;break;
}
if (!isPrinted) {
Document_IO.writeFile (Filename, tmp, newline);
//isPrinted = true;
}
}
void writeGOtoFILE (string Filename, string content, bool newline)
{
string tmp = "";
switch (Filename) {
case "NewObjectPosition.txt":
Vector3 lines = go.transform.parent.localPosition;
tmp = go.transform.parent.name + ",";
tmp = tmp + lines.ToString () + ",";
tmp = tmp + go.transform.parent.localRotation;
break;
case "changedColour.txt":
//string str = hit.collider.gameObject.name;
//tmp = go.transform.parent.name + ",";
//tmp = tmp + str.ToString () + ",";
tmp=content;
;break;
}
if (!isPrinted) {
Document_IO.writeFile (Filename, tmp,newline);
//isPrinted = true;
}
}
void OnGUI ()
{
GUI.skin = guiSkin;
if (labelOn && ClickedObject.Length > 0)
GUI.Label (new Rect (Input.mousePosition.x, (Screen.height - Input.mousePosition.y + 20), 200, 80), ClickedObject);
//Debug.Log (ClickedObject);
// if (GUI.Button (new Rect (20, 20, 100, 20), "Re-position moved Objects")) {
// Document_IO.readFile("NewObjectPosition.txt");
//
// }
}
private string ClickedObject { get; set; }
void MoveObject (int direction, int button)
{
//go has been destroyed, used middle click to to turn on
if (go == null)
return;
float moveForward = speed * Time.deltaTime * direction;
float moveLeft = speed * Time.deltaTime * direction;
Transform parent;
parent = go.transform.parent;
if (button == 0)
parent.Translate (Vector3.up * moveForward);
else if (button == 1)
parent.Translate (Vector3.left * moveLeft);
isPrinted = false;
}
void IdentifyObject ()
{
RaycastHit hit = new RaycastHit ();
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float tiltAroundX = Input.GetAxis ("Vertical");
float tiltAroundZ = Input.GetAxis ("Horizontal");
//Returns true during the frame the user touches the object
if (Input.GetButtonUp ("Identify"))
{
if (Physics.Raycast (ray, out hit)) {
float lockPos = 0f;
//show name of hit item
//Debug.Log (hit.collider.gameObject.name);
///identify the object
///
string tmpName = hit.collider.gameObject.name;
Renderer rend =hit.collider.gameObject.GetComponent(typeof (Renderer)) as Renderer;
//GameObject CP = GameObject.Find("ColorPickerPrefab");;
//GameObject Pic = Instantiate ( CP, hit.point, Quaternion.LookRotation (hit.normal)) as GameObject;
string colr = rend.material.color.ToString();
writeGOtoFILE ("changedColour.txt",hit.transform.ToString() + " old color= " + colr.ToString(), true);
Material nMaterial = new Material(Shader.Find("Standard"));
//try this class to get color from colorpicker
nMaterial.color = ChangeTheColor.UtilityClass.ChangeColor ;
GetComponent<Renderer>().material = nMaterial;
rend.sharedMaterial = nMaterial;
isPrinted = false;
writeGOtoFILE ("changedColour.txt",hit.transform.ToString() + " new color = " + nMaterial.color.ToString(), true);
//TODO: save a new material to a different name
//createMaterials.CreateMaterials.CreateMaterial(nMaterial);
//revised name
string[] newname = tmpName.Split('[');
ClickedObject = newname[0]; //hit.collider.gameObject.name;
///check for object layer
if (hit.collider.gameObject.layer == moveLayer) {
///get the prefab and attach to object
///get the right transform location and rotation;
///check if item already has Dais prefab, if so Destroy
if (hit.collider.transform.childCount > 0) {
foreach (Transform child in hit.collider.transform) {
if (child.name == "Dais")
Destroy (child.gameObject);
return;
}
}
go = Instantiate (DaisPrefab, hit.point, Quaternion.LookRotation (hit.normal)) as GameObject;
Vector3 colGO = new Vector3 (hit.collider.gameObject.transform.position.x, hit.collider.gameObject.transform.position.y, hit.collider.gameObject.transform.position.z);
go.transform.position = colGO;
//go.transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x,lockPos,lockPos);
//Quaternion target = Quaternion.Euler (tiltAroundX, 0, tiltAroundZ);
go.transform.rotation = Quaternion.Euler (tiltAroundX, lockPos, tiltAroundZ);
go.name = "Dais";
go.transform.parent = hit.collider.transform;
// go.AddComponent("RotateObject");
// go.transform.parent.gameObject.AddComponent("RotateObject");
return;
}
}
}
return;
}
public void Rotate (float amount)
{
go.transform.parent.Rotate (0, 0, amount);
isPrinted = false;
}
public static void relocateObject(string[] newPosition)
{
float x, y ,z;
x = Convert.ToSingle(newPosition[1]);
y = Convert.ToSingle(newPosition[2]);
z = Convert.ToSingle(newPosition[3]);
GameObject go = GameObject.Find(newPosition[0]);
Vector3 newPos = new Vector3(x,y,z);
go.transform.position = newPos;
}
void resetScene()
{
Scene currScene = SceneManager.GetActiveScene();
string sceneName = currScene.name;
SceneManager.LoadSceneAsync(sceneName);
Debug.Log("Scene Reset");
}
}
| |
using System;
using System.Collections.Generic;
using Midori.Runtime;
namespace Broom
{
public class ListEntry<T>
{
private T _element;
private ListEntry<T> _tail;
public T Element
{
get { return _element; }
}
public ListEntry<T> Tail
{
get { return _tail; }
}
public ListEntry(Region region, T element)
{
_element = element;
_tail = null;
}
public void Extend(ListEntry<T> tail)
{
_tail = tail;
}
}
public class RegionList<T>
{
private int _count;
private Region _region;
private ListEntry<T> _head;
public RegionList(Region region)
{
_region = region;
_count = 0;
}
public int IndexOf(T item)
{
throw new NotImplementedException();
}
public void Insert(int index, T item)
{
throw new NotImplementedException();
}
public T RemoveAtAndGet(int index)
{
if (index > this.Count)
{
throw new InvalidOperationException("Insufficient elements");
}
ListEntry<T> current = _head;
if (index == 0)
{
_head = _head.Tail;
_count--;
return current.Element;
}
ListEntry<T> previous = null;
for (int count = 0; count < index; count++)
{
previous = current;
current = current.Tail;
}
var deleted = current;
previous.Extend(current.Tail);
_count--;
return deleted.Element;
}
public void RemoveAt(int index)
{
if (index > this.Count)
{
throw new InvalidOperationException("Insufficient elements");
}
ListEntry<T> current = _head;
ListEntry<T> previous = null;
for (int count = 0; count < index; count++)
{
previous = current;
current = current.Tail;
}
previous.Extend(current.Tail);
_count--;
}
public T this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void Add(T item)
{
var listEntry = new ListEntry<T>(_region, item);
listEntry.Extend(_head);
_head = listEntry;
_count++;
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(T item)
{
throw new NotImplementedException();
}
public void CopyTo(T[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { return _count; }
}
public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
/*
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
*/
}
public class Item
{
public int ItemId;
public int Category;
public Item(Region region, int itemId, int category)
{
this.ItemId = itemId;
this.Category = category;
}
public Item Clone(Region region)
{
var newItem = new Item(region, this.ItemId, this.Category);
return newItem;
}
};
public class ItemList
{
private RegionList<Item> _items;
public RegionList<Item> Items
{
get { return _items; }
}
private Region _region;
public Region Region
{
get { return _region; }
}
public ItemList(Region region)
{
_region = region;
_items = new RegionList<Item>(region);
for(int i = 0; i < 2000000/64; i++)
{
_items.Add(new Item(region, 0, 0));
}
}
}
public class ListActor
{
private static int BUFFER_SIZE = 100;
private RegionList<ItemList> _list;
private int _recvCount;
public ListActor(Region parentRegion)
{
var actorRegion = RegionAllocator.AllocateRegion(parentRegion, 100000);
_list = new RegionList<ItemList>(actorRegion);
_recvCount = 0;
}
public void OnRecv(ItemList list)
{
_recvCount++;
Console.WriteLine("Receiving message {0}", _recvCount);
_list.Add(list);
if (_recvCount % BUFFER_SIZE == 0)
{
Console.WriteLine("Freeing regions");
try
{
for(int count = 0; count < BUFFER_SIZE; count++)
{
var itemList = _list.RemoveAtAndGet(0);
RegionAllocator.FreeRegion(itemList.Region);
}
}
catch (Exception)
{
}
}
}
}
public class Program
{
public static void Main(string[] args)
{
var parentRegion = RegionAllocator.AllocateRegion(320000);
var actor = new ListActor(parentRegion);
Console.WriteLine("Allocated parent region");
for(int count = 0; count < 10000; count++)
{
var messageRegion = RegionAllocator.AllocateRegion(parentRegion, 2000000);
var itemList = new ItemList(messageRegion);
actor.OnRecv(itemList);
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
namespace FileSystemTest
{
public class Combine : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region helper methods
private bool TestCombine(string arg1, string arg2, string expected)
{
string path = Path.Combine(arg1, arg2);
Log.Comment("Arg1: '" + arg1 + "'");
Log.Comment("Arg2: '" + arg2 + "'");
Log.Comment("Expected: '" + expected + "'");
if (path != expected)
{
Log.Exception("Got: '" + path + "'");
return false;
}
return true;
}
# endregion helper methods
#region Test Cases
[TestMethod]
public MFTestResults NullArguments()
{
MFTestResults result = MFTestResults.Pass;
try
{
Log.Comment("null 1st param");
string path = Path.Combine(null, "");
Log.Exception("Expected Argument exception, but got path: " + path);
}
catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); }
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
try
{
Log.Comment("null 2nd param");
string path = Path.Combine("", null);
Log.Exception("Expected Argument exception, but got path: " + path);
}
catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); }
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults Root()
{
MFTestResults result = MFTestResults.Pass;
try
{
string root = "\\";
/// Expected output "\\" or root, See remarks section in MSDN Path.Combine
/// http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx?PHPSESSID=ca9tbhkv7klmem4g3b2ru2q4d4
if (!TestCombine(root, root, root))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults SameRoot()
{
MFTestResults result = MFTestResults.Pass;
try
{
string root = "\\nand1";
if (!TestCombine(root, root, root))
{
return MFTestResults.Fail;
}
if (!TestCombine(root + "\\dir", root + "\\dir", root + "\\dir"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults EmptyArgs()
{
MFTestResults result = MFTestResults.Pass;
try
{
string croot = "\\sd1";
if (!TestCombine(croot, "", croot))
{
return MFTestResults.Fail;
}
if (!TestCombine("", croot, croot))
{
return MFTestResults.Fail;
}
if (!TestCombine("", "", ""))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults TwoUnique()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestCombine("Hello", "World", "Hello\\World"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults TwoUniqueWithRoot()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestCombine("\\sd1\\Hello\\", "World", "\\sd1\\Hello\\World"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults SecondBeginWithSlash()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestCombine("\\sd1\\Hello", "\\World", "\\World"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults UNCName()
{
MFTestResults result = MFTestResults.Pass;
try
{
string unc = @"\\\\radt\VbSsDb\VbTests\shadow\FXBCL\test\auto\System_IO\Path\";
if (!TestCombine(unc, "World", unc + "World"))
{
return MFTestResults.Fail;
}
if (!TestCombine("\\", unc, unc))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults MultipleSubDirs()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestCombine("\\MyDir\\Hello\\", "World\\You\\Are\\My\\Creation", "\\MyDir\\Hello\\World\\You\\Are\\My\\Creation"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults FirstRootedSecondNot()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestCombine("\\sd1\\MyDirectory\\Sample", "Test", "\\sd1\\MyDirectory\\Sample\\Test"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults CombineDot()
{
MFTestResults result = MFTestResults.Pass;
try
{
if (!TestCombine("\\sd1\\Directory", ".\\SubDir", "\\sd1\\Directory\\.\\SubDir"))
{
return MFTestResults.Fail;
}
if (!TestCombine("\\sd1\\Directory\\..", "SubDir", "\\sd1\\Directory\\..\\SubDir"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults WhiteSpace()
{
MFTestResults result = MFTestResults.Pass;
try
{
//white space inside
if (!TestCombine("\\sd1\\Directory Name", "Sub Dir", "\\sd1\\Directory Name\\Sub Dir"))
{
return MFTestResults.Fail;
}
//white space end of arg1
/// Since path2 is rooted, it is also the expected result. See MSDN remarks section:
/// http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx?PHPSESSID=ca9tbhkv7klmem4g3b2ru2q4d4
if (!TestCombine("\\sd1\\Directory Name\\ ", "\\Sub Dir", "\\Sub Dir"))
{
return MFTestResults.Fail;
}
//white space start of arg2
if (!TestCombine("\\sd1\\Directory Name", " \\Sub Dir", "\\sd1\\Directory Name\\ \\Sub Dir"))
{
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults ForwardSlashes()
{
MFTestResults result = MFTestResults.Pass;
try
{
/// Forward slash is illegal for us, an exception should be thrown.
TestCombine("//sd1//Directory Name//", "Sub//Dir", "//sd1//Directory Name//Sub//Dir");
return MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Exception: " + ex.Message);
result = MFTestResults.Pass;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( NullArguments, "NullArguments" ),
new MFTestMethod( Root, "Root" ),
new MFTestMethod( SameRoot, "SameRoot" ),
new MFTestMethod( EmptyArgs, "EmptyArgs" ),
new MFTestMethod( TwoUnique, "TwoUnique" ),
new MFTestMethod( TwoUniqueWithRoot, "TwoUniqueWithRoot" ),
new MFTestMethod( SecondBeginWithSlash, "SecondBeginWithSlash" ),
new MFTestMethod( UNCName, "UNCName" ),
new MFTestMethod( MultipleSubDirs, "MultipleSubDirs" ),
new MFTestMethod( FirstRootedSecondNot, "FirstRootedSecondNot" ),
new MFTestMethod( CombineDot, "CombineDot" ),
new MFTestMethod( WhiteSpace, "WhiteSpace" ),
new MFTestMethod( ForwardSlashes, "ForwardSlashes" ),
};
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="VolumetricHashTree.cs" company="Google">
//
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// A binary tree datastructure that uses a hashkey based on the 3D coordinates.
/// Space surrounding the origin is divided into 1 meter cubes. The hashkey is a
/// reversible index into that volume. allows quick indexing, and ray marching
/// through space. Supports a 1000m x 1000m x 1000m volume centered at the origin.
/// </summary>
public class VolumetricHashTree
{
/// <summary>
/// Left subtree.
/// </summary>
private VolumetricHashTree m_leftHashTree = null;
/// <summary>
/// Right subtree.
/// </summary>
private VolumetricHashTree m_rightHashTree = null;
/// <summary>
/// Pointer to the root node of the tree.
/// </summary>
private VolumetricHashTree m_rootHashTree = null;
/// <summary>
/// Prefab that will be instantiated for each tree node.
/// </summary>
private GameObject m_meshPrefab = null;
/// <summary>
/// Dynamic Meshing class that will handle the data processing.
/// </summary>
private DynamicMeshCube m_dynamicMeshCube = null;
/// <summary>
/// Unpacked spatial volume index of the position of this tree node.
/// </summary>
private int[] m_volumeIndex = new int[3];
/// <summary>
/// HashKey of the position of this tree node.
/// </summary>
private int m_hashKey = 0;
/// <summary>
/// Maximum dimension of 3D the hashkey space.
/// </summary>
private int m_maximumVolumeIndexDimension = 1000; // supports +/- 500m from origin along each axis
/// <summary>
/// Epsilon tolerance for boundary insertions.
/// </summary>
private float m_epsilon = 0.01f;
/// <summary>
/// Create a new tree node with a specified parent and hashkey.
/// </summary>
/// <param name="parent">The parent tree node.</param>
/// <param name="hashkey">The spatial hashkey for this tree node.</param>
public VolumetricHashTree(VolumetricHashTree parent, int hashkey)
{
if (parent == null)
{
m_rootHashTree = this;
}
else
{
m_rootHashTree = parent;
}
m_hashKey = hashkey;
}
/// <summary>
/// Gets the DynamicMeshCube that contains the mesh data.
/// </summary>
/// <value>The dynamic mesh cube.</value>
public DynamicMeshCube DynamicMeshCube
{
get { return m_dynamicMeshCube; }
}
/// <summary>
/// Enumeration function for iterating through the entire tree structure.
/// </summary>
/// <returns>The enumerable.</returns>
public IEnumerable<VolumetricHashTree> GetEnumerable()
{
if (m_leftHashTree != null)
{
foreach (VolumetricHashTree n in m_leftHashTree.GetEnumerable())
{
yield return n;
}
}
yield return this;
if (m_rightHashTree != null)
{
foreach (VolumetricHashTree n in m_rightHashTree.GetEnumerable())
{
yield return n;
}
}
}
/// <summary>
/// Computes the spatial hashkey given a 3D point.
/// </summary>
/// <returns>The hashkey value for the point.</returns>
/// <param name="p">Point for hashing into the key space.</param>
public int GetHashKey(Vector3 p)
{
return Mathf.FloorToInt(p.x) + (int)(m_maximumVolumeIndexDimension * Mathf.Floor(p.y)) + (int)(m_maximumVolumeIndexDimension * m_maximumVolumeIndexDimension * Mathf.Floor(p.z));
}
/// <summary>
/// Computes the new spatial hashkey given an integer offset in the 3D volume.
/// </summary>
/// <returns>The hashkey value for the new position.</returns>
/// <param name="startKey">Start key.</param>
/// <param name="xOffset">X offset.</param>
/// <param name="yOffset">Y offset.</param>
/// <param name="zOffset">Z offset.</param>
public int OffsetHashKey(int startKey, int xOffset, int yOffset, int zOffset)
{
return startKey + xOffset + (m_maximumVolumeIndexDimension * yOffset) + (m_maximumVolumeIndexDimension * m_maximumVolumeIndexDimension * zOffset);
}
/// <summary>
/// Insert 3D point into the hash storage. Creates a new meshing cube at the location if needed.
/// </summary>
/// <returns>The value of the voxel that received the insertion.</returns>
/// <param name="p">The 3D point.</param>
/// <param name="obs">Observation vector from the camera to the point.</param>
/// <param name="weight">Weight of the observation.</param>
/// <param name="prefab">Unity Prefab to be instantiated at this node location if needed.</param>
/// <param name="parent">Unity transform of the parent object for the prefab created at this node location.</param>
/// <param name="voxelResolution">Resolution of the voxels for this meshing cube.</param>
public float InsertPoint(Vector3 p, Vector3 obs, float weight, GameObject prefab, Transform parent, int voxelResolution)
{
int hashKey = GetHashKey(p);
return InsertPoint(hashKey, p, obs, weight, prefab, parent, voxelResolution);
}
/// <summary>
/// Raycast through the volume to quickly determine the list of voxels intersected.
/// </summary>
/// <returns>List of populated voxels the ray intersects.</returns>
/// <param name="start">Start point of the ray.</param>
/// <param name="stop">Stop point of the ray.</param>
public List<Voxel> RaycastVoxelHitlist(Vector3 start, Vector3 stop)
{
Vector3 dir = (stop - start).normalized;
List<int> volumeHitKeys = new List<int>();
volumeHitKeys.Add(GetHashKey(start));
// x crosses
if (dir.x > 0)
{
for (float x = Mathf.Ceil(start.x) + m_epsilon; x < stop.x; x += 1)
{
float scale = (x - start.x) / dir.x;
volumeHitKeys.Add(GetHashKey(start + (scale * dir)));
}
}
else
{
for (float x = Mathf.Floor(start.x) - m_epsilon; x > stop.x; x -= 1)
{
float scale = (x - start.x) / dir.x;
volumeHitKeys.Add(GetHashKey(start + (scale * dir)));
}
}
// y crosses
if (dir.y > 0)
{
for (float y = Mathf.Ceil(start.y) + m_epsilon; y < stop.y; y += 1)
{
float scale = (y - start.y) / dir.y;
volumeHitKeys.Add(GetHashKey(start + (scale * dir)));
}
}
else
{
for (float y = Mathf.Floor(start.y) - m_epsilon; y > stop.y; y -= 1)
{
float scale = (y - start.y) / dir.y;
volumeHitKeys.Add(GetHashKey(start + (scale * dir)));
}
}
// z crosses
if (dir.z > 0)
{
for (float z = Mathf.Ceil(start.z) + m_epsilon; z < stop.z; z += 1)
{
float scale = (z - start.z) / dir.z;
volumeHitKeys.Add(GetHashKey(start + (scale * dir)));
}
}
else
{
for (float z = Mathf.Floor(start.z) - m_epsilon; z > stop.z; z -= 1)
{
float scale = (z - start.z) / dir.z;
volumeHitKeys.Add(GetHashKey(start + (scale * dir)));
}
}
List<Voxel> voxelHits = new List<Voxel>();
foreach (int volumeKey in volumeHitKeys)
{
VolumetricHashTree result = Query(volumeKey);
if (result == null)
{
continue;
}
if (result.m_meshPrefab == null)
{
continue;
}
List<Voxel> voxels = result.m_dynamicMeshCube.RayCastVoxelHitlist(start, stop, dir);
foreach (Voxel v in voxels)
{
voxelHits.Add(v);
}
}
return voxelHits;
}
/// <summary>
/// Query for the existence of a node at a hashKey location.
/// </summary>
/// <param name="hashKey">Hash key.</param>
/// <returns>The node if it exists, null if it does not.</returns>
public VolumetricHashTree Query(int hashKey)
{
if (hashKey == m_hashKey)
{
return this;
}
if (hashKey < m_hashKey)
{
if (m_leftHashTree != null)
{
return m_leftHashTree.Query(hashKey);
}
}
else
{
if (m_rightHashTree != null)
{
return m_rightHashTree.Query(hashKey);
}
}
return null;
}
/// <summary>
/// Clears the contents of this tree node and its subtrees.
/// </summary>
public void Clear()
{
if (m_leftHashTree != null)
{
m_leftHashTree.Clear();
m_leftHashTree = null;
}
if (m_rightHashTree != null)
{
m_rightHashTree.Clear();
m_rightHashTree = null;
}
if (m_dynamicMeshCube != null)
{
m_dynamicMeshCube.Clear();
}
if (m_meshPrefab != null)
{
GameObject.DestroyImmediate(m_meshPrefab);
m_meshPrefab = null;
}
}
/// <summary>
/// Calculates statistics about this tree node and its subtrees.
/// </summary>
/// <param name="vertCount">Vertex counter.</param>
/// <param name="triangleCount">Triangle counter.</param>
/// <param name="nodeCount">Tree node counter.</param>
public void ComputeStats(ref int vertCount, ref int triangleCount, ref int nodeCount)
{
if (m_leftHashTree != null)
{
m_leftHashTree.ComputeStats(ref vertCount, ref triangleCount, ref nodeCount);
}
if (m_meshPrefab != null)
{
vertCount += m_dynamicMeshCube.Vertices.Count;
triangleCount += m_dynamicMeshCube.Triangles.Count;
}
nodeCount++;
if (m_rightHashTree != null)
{
m_rightHashTree.ComputeStats(ref vertCount, ref triangleCount, ref nodeCount);
}
}
/// <summary>
/// Debug Draw will draw debug lines outlining the populated volumes.
/// </summary>
public void DebugDraw()
{
if (m_leftHashTree != null)
{
m_leftHashTree.DebugDraw();
}
if (m_dynamicMeshCube != null)
{
m_dynamicMeshCube.DebugDrawNormals();
}
if (m_rightHashTree != null)
{
m_rightHashTree.DebugDraw();
}
}
/// <summary>
/// Instantiate the Unity Prefab that will exist at this node location.
/// </summary>
/// <param name="hashkey">The spatial hashkey for this tree node.</param>
/// <param name="prefab">The Unity Prefab object.</param>
/// <param name="parent">The Unity transform of the GameObject parent of the prefab.</param>
/// <param name="voxelResolution">The voxel resolution of the meshing cube.</param>
private void InstantiatePrefab(int hashkey, GameObject prefab, Transform parent, int voxelResolution)
{
int x, y, z;
ReverseHashKey(hashkey, out x, out y, out z);
m_meshPrefab = (GameObject)GameObject.Instantiate(prefab);
m_meshPrefab.transform.position = new Vector3(x, y, z);
m_meshPrefab.transform.parent = parent;
m_dynamicMeshCube = m_meshPrefab.GetComponent<DynamicMeshCube>();
if (m_meshPrefab == null)
{
Debug.LogError("Game Object does not have the dynamic mesh component");
}
m_dynamicMeshCube.SetProperties(voxelResolution);
m_dynamicMeshCube.Key = hashkey;
}
/// <summary>
/// Computes the x, y, z integer coordinates that coorespond to a given hashkey.
/// </summary>
/// <param name="hashKey">The key to reverse.</param>
/// <param name="x">The output x position.</param>
/// <param name="y">The output y position.</param>
/// <param name="z">The output z position.</param>
private void ReverseHashKey(int hashKey, out int x, out int y, out int z)
{
int flipLimit = m_maximumVolumeIndexDimension / 2;
int temp = hashKey;
x = temp % m_maximumVolumeIndexDimension;
if (x > flipLimit)
{
// x is negative, but opposite sign of y
x = x - m_maximumVolumeIndexDimension;
}
if (x < -flipLimit)
{
// x is positive, but opposite sign of y
x = m_maximumVolumeIndexDimension + x;
}
temp -= x;
temp /= m_maximumVolumeIndexDimension;
y = temp % m_maximumVolumeIndexDimension;
if (y > flipLimit)
{
// y is negative, but opposite sign of z
y = y - m_maximumVolumeIndexDimension;
}
if (y < -flipLimit)
{
// y is positive, but opposite sign of z
y = m_maximumVolumeIndexDimension + y;
}
temp -= y;
z = temp / m_maximumVolumeIndexDimension;
}
/// <summary>
/// Insert 3D point into the hash storage. Creates a new meshing cube at the location if needed.
/// </summary>
/// <returns>The value of the voxel that received the insertion.</returns>
/// <param name="hashkey">Hashkey index of the target node.</param>
/// <param name="p">The 3D point.</param>
/// <param name="obs">Observation vector from the camera to the point.</param>
/// <param name="weight">Weight of the observation.</param>
/// <param name="prefab">Unity Prefab to be instantiated at this node location if needed.</param>
/// <param name="parent">Unity transform of the parent object for the prefab created at this node location.</param>
/// <param name="voxelResolution">Resolution of the voxels for this meshing cube.</param>
private float InsertPoint(int hashkey, Vector3 p, Vector3 obs, float weight, GameObject prefab, Transform parent, int voxelResolution)
{
if (m_hashKey == hashkey)
{
if (m_meshPrefab == null)
{
InstantiatePrefab(hashkey, prefab, parent, voxelResolution);
}
if (m_meshPrefab == null)
{
m_dynamicMeshCube = m_meshPrefab.GetComponent<DynamicMeshCube>();
}
if (m_meshPrefab == null)
{
Debug.Log("Error: cannot find DynamicMeshVolume");
return 0;
}
if (m_dynamicMeshCube.IsRegenerating)
{
return 0;
}
// adjust weight of mutiple voxels along observation ray
float result = m_dynamicMeshCube.InsertPoint(p, obs, weight, ref m_volumeIndex);
Vector3 closerPoint = p - (obs * m_dynamicMeshCube.VoxelSize);
Vector3 furtherPoint = p + (obs * m_dynamicMeshCube.VoxelSize);
// voxel was inside the surface, back out one, and insert in the next closest voxel
if (result > 0)
{
m_dynamicMeshCube.InsertPoint(closerPoint, p, obs, weight);
}
else
{
m_dynamicMeshCube.InsertPoint(furtherPoint, p, obs, weight);
}
if (m_volumeIndex[0] == 0)
{
int neighborHashKey = hashkey - 1;
result = m_rootHashTree.InsertPoint(neighborHashKey, p, obs, weight, prefab, parent, voxelResolution);
}
if (m_volumeIndex[1] == 0)
{
int neighborHashKey = hashkey - m_maximumVolumeIndexDimension;
result = m_rootHashTree.InsertPoint(neighborHashKey, p, obs, weight, prefab, parent, voxelResolution);
}
if (m_volumeIndex[2] == 0)
{
int neighborHashKey = hashkey - (m_maximumVolumeIndexDimension * m_maximumVolumeIndexDimension);
result = m_rootHashTree.InsertPoint(neighborHashKey, p, obs, weight, prefab, parent, voxelResolution);
}
return result;
}
if (hashkey < m_hashKey)
{
if (m_leftHashTree == null)
{
m_leftHashTree = new VolumetricHashTree(m_rootHashTree, hashkey);
}
return m_leftHashTree.InsertPoint(hashkey, p, obs, weight, prefab, parent, voxelResolution);
}
else
{
if (m_rightHashTree == null)
{
m_rightHashTree = new VolumetricHashTree(m_rootHashTree, hashkey);
}
return m_rightHashTree.InsertPoint(hashkey, p, obs, weight, prefab, parent, voxelResolution);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using DatenMeister.Core.EMOF.Implementation;
using DatenMeister.Core.EMOF.Interface.Reflection;
using DatenMeister.Core.Functions.Queries;
using DatenMeister.Core.Helper;
using StundenMeister.Model;
namespace StundenMeister.Logic
{
public class TimeRecordingLogic
{
private bool hibernationActive => _stundenMeisterPlugin.Configuration.HibernationDetectionActive;
private TimeSpan hibernationTime => _stundenMeisterPlugin.Configuration.HibernationDetectionTime;
private readonly StundenMeisterPlugin _stundenMeisterPlugin;
public TimeRecordingLogic(StundenMeisterPlugin stundenMeisterPlugin)
{
_stundenMeisterPlugin = stundenMeisterPlugin;
}
/// <summary>
/// Performs the initialization.
/// 1), it is looked, whether one time recording is still active and if yes, this time recording
/// is set within the <c>StundenMeisterData</c> instance.
/// 2) If there are multiple activations of the time recordings, only the last one is kept active
/// </summary>
public void Initialize()
{
var list = _stundenMeisterPlugin.Data.Extent.elements()
.WhenMetaClassIs(
_stundenMeisterPlugin.Data.ClassTimeRecording)
.WhenPropertyHasValue(
nameof(TimeRecording.isActive), true)
.OfType<IElement>()
.ToList();
IElement theActiveOne = null;
if (list.Count > 1)
{
// Find the one with the highest starting date and deactivate the rest
var highest = DateTime.MinValue;
foreach (var item in list)
{
var date = item.getOrDefault<DateTime>(nameof(TimeRecording.startDate));
if (date > highest)
{
theActiveOne = item;
highest = date;
}
}
// Now, deactivate everything, which is not the active one
foreach (var item in list)
{
if (item == theActiveOne)
{
continue;
}
item.set(nameof(TimeRecording.isActive), false);
}
}
else
{
theActiveOne = list.FirstOrDefault();
}
if (theActiveOne != null)
{
_stundenMeisterPlugin.Data.CurrentTimeRecording = theActiveOne;
}
}
public IEnumerable<TimeRecordingSet> GetTimeRecordingSets()
{
var now = DateTime.Now;
var startDay = FindStartOfDay(now);
var endDay = FindEndOfDay(now);
var startWeek = FindStartOfWeek(now);
var endWeek = FindEndOfWeek(now);
var startMonth = FindStartOfMonth(now);
var endMonth = FindEndOfMonth(now);
var total = new TimeRecordingSet {Title = "Total"};
var list = new List<TimeRecordingSet>();
TimeRecordingSet costCenterSet = null;
foreach (var recording in _stundenMeisterPlugin.Data.Extent
.elements()
.WhenMetaClassIs(_stundenMeisterPlugin.Data.ClassTimeRecording)
.OfType<IElement>())
{
// Checks, if cost center is in given list
var costCenter = recording.getOrDefault<IElement>(nameof(TimeRecording.costCenter));
if (costCenter != null)
{
costCenterSet = list.FirstOrDefault(x=>x.CostCenter?.equals(costCenter) == true);
if (costCenterSet == null)
{
costCenterSet = new TimeRecordingSet
{
Title = costCenter.getOrDefault<string>(nameof(CostCenter.id)),
CostCenter = costCenter
};
list.Add(costCenterSet);
}
}
var recordingStartDate = recording.getOrDefault<DateTime>(nameof(TimeRecording.startDate));
if (recordingStartDate >= startDay && recordingStartDate < endDay)
{
total.Day = total.Day.Add(GetTimeSpanOfRecording(recording));
if (costCenterSet != null)
{
costCenterSet.Day = costCenterSet.Day.Add(GetTimeSpanOfRecording(recording));
}
}
if (recordingStartDate >= startWeek && recordingStartDate < endWeek)
{
total.Week = total.Week.Add(GetTimeSpanOfRecording(recording));
if (costCenterSet != null)
{
costCenterSet.Week = costCenterSet.Week.Add(GetTimeSpanOfRecording(recording));
}
}
if (recordingStartDate >= startMonth && recordingStartDate < endMonth)
{
total.Month = total.Month.Add(GetTimeSpanOfRecording(recording));
if (costCenterSet != null)
{
costCenterSet.Month = costCenterSet.Month.Add(GetTimeSpanOfRecording(recording));
}
}
}
foreach (var center in list.OrderBy(x => x.Title))
{
yield return center;
}
yield return total;
}
/// <summary>
/// Creates a new element containing the time recordings
/// </summary>
/// <returns>The element being created</returns>
public IElement CreateAndAddNewTimeRecoding()
{
var factory = new MofFactory(StundenMeisterData.TheOne.Extent);
var createdItem = factory.create(StundenMeisterData.TheOne.ClassTimeRecording);
StundenMeisterData.TheOne.Extent.elements().add(createdItem);
_stundenMeisterPlugin.Data.CurrentTimeRecording = createdItem;
return createdItem;
}
/// <summary>
/// Starts a new recording of timing.
/// Ends the current one and creates a new time record
/// </summary>
/// <param name="costCenter">Cost center whose timing will be started</param>
public void StartNewRecording(IElement costCenter)
{
EndRecording();
var logic = new TimeRecordingLogic(StundenMeisterPlugin.Get());
var currentTimeRecording = logic.CreateAndAddNewTimeRecoding();
currentTimeRecording.set(nameof(TimeRecording.startDate), DateTime.UtcNow);
currentTimeRecording.set(nameof(TimeRecording.endDate), DateTime.UtcNow);
currentTimeRecording.set(nameof(TimeRecording.isActive), true);
currentTimeRecording.set(nameof(TimeRecording.costCenter), costCenter);
}
/// <summary>
/// Ends the current active recording
/// </summary>
public void EndRecording()
{
var currentTimeRecording = _stundenMeisterPlugin.Data.CurrentTimeRecording;
if (currentTimeRecording != null)
{
currentTimeRecording.set(nameof(TimeRecording.isActive), false);
_stundenMeisterPlugin.Data.CurrentTimeRecording = null;
}
// By the way. Check for any other active time recording
CheckForActiveTimeRecordingsAndDeactivate();
}
/// <summary>
/// Changes the cost center and activates the timing, if there is currently an active
/// timing
/// </summary>
/// <param name="selectedCostCenter">Costcenter to which the system switches</param>
public void ChangeCostCenter(IElement selectedCostCenter)
{
var costCenter =
_stundenMeisterPlugin.Data?.CurrentTimeRecording
?.getOrDefault<IElement>(nameof(TimeRecording.costCenter));
if (costCenter != null && costCenter == selectedCostCenter)
{
return;
}
if (_stundenMeisterPlugin.Data?.CurrentTimeRecording?.getOrDefault<bool>(nameof(TimeRecording.isActive)) != true)
{
// If, there is no "isActive" time recording, then do not start a new time recording
return;
}
var recordingLogic = new TimeRecordingLogic(_stundenMeisterPlugin);
recordingLogic.StartNewRecording(selectedCostCenter);
}
/// <summary>
/// Checks all time recordings and deactivate them if there are still some
/// active time recordings
/// </summary>
private void CheckForActiveTimeRecordingsAndDeactivate()
{
foreach (var element in _stundenMeisterPlugin.Data.Extent.elements()
.WhenMetaClassIs(
_stundenMeisterPlugin.Data.ClassTimeRecording)
.WhenPropertyHasValue(
nameof(TimeRecording.isActive), true)
.OfType<IElement>())
{
element.set(nameof(TimeRecording.isActive), false);
}
}
/// <summary>
/// Checks whether the time recording is active
/// </summary>
/// <returns>true, if the time recording is active</returns>
public bool IsTimeRecordingActive()
{
var currentTimeRecording = StundenMeisterData.TheOne.CurrentTimeRecording;
return currentTimeRecording != null && currentTimeRecording.getOrDefault<bool>(nameof(TimeRecording.isActive));
}
/// <summary>
/// Updates the timing of the current recording
/// </summary>
public void UpdateCurrentRecording()
{
var currentTimeRecording = StundenMeisterData.TheOne.CurrentTimeRecording;
// There is an active recording. We have to update the information to show the user the latest
// and greatest information.
if (currentTimeRecording == null)
{
// Nothing to do... no active recording
return;
}
var isActive = currentTimeRecording.getOrDefault<bool>(nameof(TimeRecording.isActive));
if (isActive)
{
// Check for current end date
var currentEndDate = currentTimeRecording.get<DateTime>(nameof(TimeRecording.endDate));
// While current time recording is active, advance content
var endDate = DateTime.UtcNow;
if (hibernationActive && (endDate - currentEndDate) > hibernationTime)
{
// Ok, we have a hibernation overflow
_stundenMeisterPlugin.Data.HibernationDetected = true;
}
else
{
// No hibernation, we can continue
_stundenMeisterPlugin.Data.HibernationDetected = false;
currentTimeRecording.set(nameof(TimeRecording.endDate), endDate);
}
}
}
/// <summary>
/// If the current logic is in hibernation, then the use layer must confirm
/// or reject the hibernation before the time estimation will continue
/// </summary>
/// <param name="continueRecording">true, if the hibernation is confirmed</param>
public void ConfirmHibernation(bool continueRecording)
{
if (!_stundenMeisterPlugin.Data.HibernationDetected)
{
// No active hibernation
return;
}
var currentTimeRecording = StundenMeisterData.TheOne.CurrentTimeRecording;
if (currentTimeRecording == null)
{
// Nothing to do... no active recording
return;
}
if (continueRecording)
{
// Ok, it is OK to continue with timing
var endDate = DateTime.UtcNow;
_stundenMeisterPlugin.Data.HibernationDetected = false;
currentTimeRecording.set(nameof(TimeRecording.endDate), endDate);
}
else
{
// No, the session has ended.
EndRecording();
}
_stundenMeisterPlugin.Data.HibernationDetected = false;
}
public TimeSpan CalculateWorkingHoursInDay(DateTime day = default)
{
if (day == default)
{
day = DateTime.Now;
}
var startDate = FindStartOfDay(day);
var endDate = FindEndOfDay(day);
return CalculateWorkingHoursInPeriod(startDate, endDate);
}
/// <summary>
/// Calculates the working hours in the current week
/// </summary>
/// <param name="day">Day to be evaluated</param>
/// <returns>Timespan storing the information</returns>
public TimeSpan CalculateWorkingHoursInWeek(DateTime day = default)
{
if (day == default)
{
day = DateTime.Now;
}
var startDate = FindStartOfWeek(day);
var endDate = FindEndOfWeek(day);
return CalculateWorkingHoursInPeriod(startDate, endDate);
}
public TimeSpan CalculateWorkingHoursInMonth(DateTime day = default)
{
if (day == default)
{
day = DateTime.Now;
}
var startDate = FindStartOfMonth(day);
var endDate = FindEndOfMonth(day);
return CalculateWorkingHoursInPeriod(startDate, endDate);
}
private TimeSpan CalculateWorkingHoursInPeriod(DateTime startDate, DateTime endDate)
{
var result = TimeSpan.Zero;
foreach (var recording in _stundenMeisterPlugin.Data.Extent
.elements()
.WhenMetaClassIs(_stundenMeisterPlugin.Data.ClassTimeRecording)
.OfType<IElement>())
{
var recordingStartDate = recording.getOrDefault<DateTime>(nameof(TimeRecording.startDate));
if (recordingStartDate >= startDate && recordingStartDate < endDate)
{
result = result.Add(GetTimeSpanOfRecording(recording));
}
}
return result;
}
/// <summary>
/// Finds the start of the day
/// </summary>
/// <param name="day">Day to be used</param>
/// <returns>Date of the start of the date (inclusive)</returns>
public DateTime FindStartOfDay(DateTime day)
{
return new DateTime(day.Year, day.Month, day.Day);
}
/// <summary>
/// Finds the end of the day
/// </summary>
/// <param name="day">Day to be used</param>
/// <returns>Date of the end of the date (non-inclusive)</returns>
public DateTime FindEndOfDay(DateTime day)
{
return new DateTime(day.Year, day.Month, day.Day).AddDays(1);
}
public DateTime FindStartOfWeek(DateTime day)
{
var dayOfWeek = day.DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Sunday => new DateTime(day.Year, day.Month, day.Day).AddDays(-6),
DayOfWeek.Monday => new DateTime(day.Year, day.Month, day.Day),
DayOfWeek.Tuesday => new DateTime(day.Year, day.Month, day.Day).AddDays(-1),
DayOfWeek.Wednesday => new DateTime(day.Year, day.Month, day.Day).AddDays(-2),
DayOfWeek.Thursday => new DateTime(day.Year, day.Month, day.Day).AddDays(-3),
DayOfWeek.Friday => new DateTime(day.Year, day.Month, day.Day).AddDays(-4),
DayOfWeek.Saturday => new DateTime(day.Year, day.Month, day.Day).AddDays(-5),
_ => throw new ArgumentOutOfRangeException()
};
}
public DateTime FindEndOfWeek(DateTime day)
{
var dayOfWeek = day.DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Sunday => new DateTime(day.Year, day.Month, day.Day).AddDays(1),
DayOfWeek.Monday => new DateTime(day.Year, day.Month, day.Day).AddDays(7),
DayOfWeek.Tuesday => new DateTime(day.Year, day.Month, day.Day).AddDays(6),
DayOfWeek.Wednesday => new DateTime(day.Year, day.Month, day.Day).AddDays(5),
DayOfWeek.Thursday => new DateTime(day.Year, day.Month, day.Day).AddDays(4),
DayOfWeek.Friday => new DateTime(day.Year, day.Month, day.Day).AddDays(3),
DayOfWeek.Saturday => new DateTime(day.Year, day.Month, day.Day).AddDays(2),
_ => throw new ArgumentOutOfRangeException()
};
}
/// <summary>
/// Finds the first day of the month
/// </summary>
/// <param name="day">Day of which the first day in month is looked up for</param>
/// <returns>The found date</returns>
public DateTime FindStartOfMonth(DateTime day)
{
return new DateTime(day.Year, day.Month, 1);
}
/// <summary>
/// Finds the last day of the month. (The first position in the next year will be returned)
/// </summary>
/// <param name="day">Day of which the last day in month is looked up</param>
/// <returns>The found date</returns>
public DateTime FindEndOfMonth(DateTime day)
{
if (day.Month == 12)
{
return new DateTime(day.Year + 1, 1, 1);
}
return new DateTime(day.Year, day.Month + 1, 1);
}
/// <summary>
/// Gets the timespan of the recording
/// </summary>
/// <param name="timeRecording">Recording to be evaluated</param>
/// <returns>The difference between startDate and endDate</returns>
public TimeSpan GetTimeSpanOfRecording(IElement timeRecording)
{
var startDate = timeRecording.getOrDefault<DateTime>(nameof(TimeRecording.startDate));
var endDate = timeRecording.getOrDefault<DateTime>(nameof(TimeRecording.endDate));
return endDate - startDate;
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
/// <summary>
/// Display story text in a visual novel style dialog box.
/// </summary>
public class SayDialog : MonoBehaviour
{
[Tooltip("Duration to fade dialogue in/out")]
[SerializeField] protected float fadeDuration = 0.25f;
[Tooltip("The continue button UI object")]
[SerializeField] protected Button continueButton;
[Tooltip("The canvas UI object")]
[SerializeField] protected Canvas dialogCanvas;
[Tooltip("The name text UI object")]
[SerializeField] protected Text nameText;
[Tooltip("The story text UI object")]
[SerializeField] protected Text storyText;
public virtual Text StoryText { get { return storyText; } }
[Tooltip("The character UI object")]
[SerializeField] protected Image characterImage;
public virtual Image CharacterImage { get { return characterImage; } }
[Tooltip("Adjust width of story text when Character Image is displayed (to avoid overlapping)")]
[SerializeField] protected bool fitTextWithImage = true;
[Tooltip("Close any other open Say Dialogs when this one is active")]
[SerializeField] protected bool closeOtherDialogs;
protected float startStoryTextWidth;
protected float startStoryTextInset;
protected WriterAudio writerAudio;
protected Writer writer;
protected CanvasGroup canvasGroup;
protected bool fadeWhenDone = true;
protected float targetAlpha = 0f;
protected float fadeCoolDownTimer = 0f;
protected Sprite currentCharacterImage;
// Most recent speaking character
protected static Character speakingCharacter;
protected StringSubstituter stringSubstituter = new StringSubstituter();
// Cache active Say Dialogs to avoid expensive scene search
protected static List<SayDialog> activeSayDialogs = new List<SayDialog>();
protected virtual void Awake()
{
if (!activeSayDialogs.Contains(this))
{
activeSayDialogs.Add(this);
}
}
protected virtual void OnDestroy()
{
activeSayDialogs.Remove(this);
}
protected virtual Writer GetWriter()
{
if (writer != null)
{
return writer;
}
writer = GetComponent<Writer>();
if (writer == null)
{
writer = gameObject.AddComponent<Writer>();
}
return writer;
}
protected virtual CanvasGroup GetCanvasGroup()
{
if (canvasGroup != null)
{
return canvasGroup;
}
canvasGroup = GetComponent<CanvasGroup>();
if (canvasGroup == null)
{
canvasGroup = gameObject.AddComponent<CanvasGroup>();
}
return canvasGroup;
}
protected virtual WriterAudio GetWriterAudio()
{
if (writerAudio != null)
{
return writerAudio;
}
writerAudio = GetComponent<WriterAudio>();
if (writerAudio == null)
{
writerAudio = gameObject.AddComponent<WriterAudio>();
}
return writerAudio;
}
protected virtual void Start()
{
// Dialog always starts invisible, will be faded in when writing starts
GetCanvasGroup().alpha = 0f;
// Add a raycaster if none already exists so we can handle dialog input
GraphicRaycaster raycaster = GetComponent<GraphicRaycaster>();
if (raycaster == null)
{
gameObject.AddComponent<GraphicRaycaster>();
}
// It's possible that SetCharacterImage() has already been called from the
// Start method of another component, so check that no image has been set yet.
// Same for nameText.
if (nameText != null && nameText.text == "")
{
SetCharacterName("", Color.white);
}
if (currentCharacterImage == null)
{
// Character image is hidden by default.
SetCharacterImage(null);
}
}
protected virtual void LateUpdate()
{
UpdateAlpha();
if (continueButton != null)
{
continueButton.gameObject.SetActive( GetWriter().IsWaitingForInput );
}
}
protected virtual void UpdateAlpha()
{
if (GetWriter().IsWriting)
{
targetAlpha = 1f;
fadeCoolDownTimer = 0.1f;
}
else if (fadeWhenDone && Mathf.Approximately(fadeCoolDownTimer, 0f))
{
targetAlpha = 0f;
}
else
{
// Add a short delay before we start fading in case there's another Say command in the next frame or two.
// This avoids a noticeable flicker between consecutive Say commands.
fadeCoolDownTimer = Mathf.Max(0f, fadeCoolDownTimer - Time.deltaTime);
}
CanvasGroup canvasGroup = GetCanvasGroup();
if (fadeDuration <= 0f)
{
canvasGroup.alpha = targetAlpha;
}
else
{
float delta = (1f / fadeDuration) * Time.deltaTime;
float alpha = Mathf.MoveTowards(canvasGroup.alpha, targetAlpha, delta);
canvasGroup.alpha = alpha;
if (alpha <= 0f)
{
// Deactivate dialog object once invisible
gameObject.SetActive(false);
}
}
}
protected virtual void ClearStoryText()
{
if (storyText != null)
{
storyText.text = "";
}
}
#region Public members
/// <summary>
/// Currently active Say Dialog used to display Say text
/// </summary>
public static SayDialog ActiveSayDialog { get; set; }
/// <summary>
/// Returns a SayDialog by searching for one in the scene or creating one if none exists.
/// </summary>
public static SayDialog GetSayDialog()
{
if (ActiveSayDialog == null)
{
SayDialog sd = null;
// Use first active Say Dialog in the scene (if any)
if (activeSayDialogs.Count > 0)
{
sd = activeSayDialogs[0];
}
if (sd != null)
{
ActiveSayDialog = sd;
}
if (ActiveSayDialog == null)
{
// Auto spawn a say dialog object from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/SayDialog");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.SetActive(false);
go.name = "SayDialog";
ActiveSayDialog = go.GetComponent<SayDialog>();
}
}
}
return ActiveSayDialog;
}
/// <summary>
/// Stops all active portrait tweens.
/// </summary>
public static void StopPortraitTweens()
{
// Stop all tweening portraits
var activeCharacters = Character.ActiveCharacters;
for (int i = 0; i < activeCharacters.Count; i++)
{
var c = activeCharacters[i];
if (c.State.portraitImage != null)
{
if (LeanTween.isTweening(c.State.portraitImage.gameObject))
{
LeanTween.cancel(c.State.portraitImage.gameObject, true);
PortraitController.SetRectTransform(c.State.portraitImage.rectTransform, c.State.position);
if (c.State.dimmed == true)
{
c.State.portraitImage.color = new Color(0.5f, 0.5f, 0.5f, 1f);
}
else
{
c.State.portraitImage.color = Color.white;
}
}
}
}
}
/// <summary>
/// Sets the active state of the Say Dialog gameobject.
/// </summary>
public virtual void SetActive(bool state)
{
gameObject.SetActive(state);
}
/// <summary>
/// Sets the active speaking character.
/// </summary>
/// <param name="character">The active speaking character.</param>
public virtual void SetCharacter(Character character)
{
if (character == null)
{
if (characterImage != null)
{
characterImage.gameObject.SetActive(false);
}
if (nameText != null)
{
nameText.text = "";
}
speakingCharacter = null;
}
else
{
var prevSpeakingCharacter = speakingCharacter;
speakingCharacter = character;
// Dim portraits of non-speaking characters
var activeStages = Stage.ActiveStages;
for (int i = 0; i < activeStages.Count; i++)
{
var stage = activeStages[i];
if (stage.DimPortraits)
{
var charactersOnStage = stage.CharactersOnStage;
for (int j = 0; j < charactersOnStage.Count; j++)
{
var c = charactersOnStage[j];
if (prevSpeakingCharacter != speakingCharacter)
{
if (c != null && !c.Equals(speakingCharacter))
{
stage.SetDimmed(c, true);
}
else
{
stage.SetDimmed(c, false);
}
}
}
}
}
string characterName = character.NameText;
if (characterName == "")
{
// Use game object name as default
characterName = character.GetObjectName();
}
SetCharacterName(characterName, character.NameColor);
}
}
/// <summary>
/// Sets the character image to display on the Say Dialog.
/// </summary>
public virtual void SetCharacterImage(Sprite image)
{
if (characterImage == null)
{
return;
}
if (image != null)
{
characterImage.sprite = image;
characterImage.gameObject.SetActive(true);
currentCharacterImage = image;
}
else
{
characterImage.gameObject.SetActive(false);
if (startStoryTextWidth != 0)
{
storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth);
}
}
// Adjust story text box to not overlap image rect
if (fitTextWithImage &&
storyText != null &&
characterImage.gameObject.activeSelf)
{
if (Mathf.Approximately(startStoryTextWidth, 0f))
{
startStoryTextWidth = storyText.rectTransform.rect.width;
startStoryTextInset = storyText.rectTransform.offsetMin.x;
}
// Clamp story text to left or right depending on relative position of the character image
if (storyText.rectTransform.position.x < characterImage.rectTransform.position.x)
{
storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
else
{
storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
}
}
/// <summary>
/// Sets the character name to display on the Say Dialog.
/// Supports variable substitution e.g. John {$surname}
/// </summary>
public virtual void SetCharacterName(string name, Color color)
{
if (nameText != null)
{
var subbedName = stringSubstituter.SubstituteStrings(name);
nameText.text = subbedName;
nameText.color = color;
}
}
/// <summary>
/// Write a line of story text to the Say Dialog. Starts coroutine automatically.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual void Say(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, AudioClip voiceOverClip, Action onComplete)
{
StartCoroutine(DoSay(text, clearPrevious, waitForInput, fadeWhenDone, stopVoiceover, voiceOverClip, onComplete));
}
/// <summary>
/// Write a line of story text to the Say Dialog. Must be started as a coroutine.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual IEnumerator DoSay(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, AudioClip voiceOverClip, Action onComplete)
{
var writer = GetWriter();
if (writer.IsWriting || writer.IsWaitingForInput)
{
writer.Stop();
while (writer.IsWriting || writer.IsWaitingForInput)
{
yield return null;
}
}
if (closeOtherDialogs)
{
for (int i = 0; i < activeSayDialogs.Count; i++)
{
var sd = activeSayDialogs[i];
if (sd.gameObject != gameObject)
{
sd.SetActive(false);
}
}
}
gameObject.SetActive(true);
this.fadeWhenDone = fadeWhenDone;
// Voice over clip takes precedence over a character sound effect if provided
AudioClip soundEffectClip = null;
if (voiceOverClip != null)
{
WriterAudio writerAudio = GetWriterAudio();
writerAudio.OnVoiceover(voiceOverClip);
}
else if (speakingCharacter != null)
{
soundEffectClip = speakingCharacter.SoundEffect;
}
yield return StartCoroutine(writer.Write(text, clearPrevious, waitForInput, stopVoiceover, soundEffectClip, onComplete));
}
/// <summary>
/// Tell the Say Dialog to fade out once writing and player input have finished.
/// </summary>
public virtual bool FadeWhenDone { get {return fadeWhenDone; } set { fadeWhenDone = value; } }
/// <summary>
/// Stop the Say Dialog while its writing text.
/// </summary>
public virtual void Stop()
{
fadeWhenDone = true;
GetWriter().Stop();
}
/// <summary>
/// Stops writing text and clears the Say Dialog.
/// </summary>
public virtual void Clear()
{
ClearStoryText();
// Kill any active write coroutine
StopAllCoroutines();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Core;
using Orleans.GrainDirectory;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Scheduler;
using Orleans.Storage;
using Microsoft.Extensions.DependencyInjection;
namespace Orleans.Runtime
{
/// <summary>
/// Maintains additional per-activation state that is required for Orleans internal operations.
/// MUST lock this object for any concurrent access
/// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc.
/// </summary>
internal class ActivationData : IGrainActivationContext, IActivationData, IInvokable, IDisposable
{
// This class is used for activations that have extension invokers. It keeps a dictionary of
// invoker objects to use with the activation, and extend the default invoker
// defined for the grain class.
// Note that in all cases we never have more than one copy of an actual invoker;
// we may have a ExtensionInvoker per activation, in the worst case.
private class ExtensionInvoker : IGrainMethodInvoker, IGrainExtensionMap
{
// Because calls to ExtensionInvoker are allways made within the activation context,
// we rely on the single-threading guarantee of the runtime and do not protect the map with a lock.
private Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>> extensionMap; // key is the extension interface ID
/// <summary>
/// Try to add an extension for the specific interface ID.
/// Fail and return false if there is already an extension for that interface ID.
/// Note that if an extension invoker handles multiple interface IDs, it can only be associated
/// with one of those IDs when added, and so only conflicts on that one ID will be detected and prevented.
/// </summary>
/// <param name="invoker"></param>
/// <param name="handler"></param>
/// <returns></returns>
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension handler)
{
if (extensionMap == null)
{
extensionMap = new Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>>(1);
}
if (extensionMap.ContainsKey(invoker.InterfaceId)) return false;
extensionMap.Add(invoker.InterfaceId, new Tuple<IGrainExtension, IGrainExtensionMethodInvoker>(handler, invoker));
return true;
}
/// <summary>
/// Removes all extensions for the specified interface id.
/// Returns true if the chained invoker no longer has any extensions and may be safely retired.
/// </summary>
/// <param name="extension"></param>
/// <returns>true if the chained invoker is now empty, false otherwise</returns>
public bool Remove(IGrainExtension extension)
{
int interfaceId = 0;
foreach(int iface in extensionMap.Keys)
if (extensionMap[iface].Item1 == extension)
{
interfaceId = iface;
break;
}
if (interfaceId == 0) // not found
throw new InvalidOperationException(String.Format("Extension {0} is not installed",
extension.GetType().FullName));
extensionMap.Remove(interfaceId);
return extensionMap.Count == 0;
}
public bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
if (extensionMap == null) return false;
foreach (var ext in extensionMap.Values)
if (extensionType == ext.Item1.GetType())
{
result = ext.Item1;
return true;
}
return false;
}
/// <summary>
/// Invokes the appropriate grain or extension method for the request interface ID and method ID.
/// First each extension invoker is tried; if no extension handles the request, then the base
/// invoker is used to handle the request.
/// The base invoker will throw an appropriate exception if the request is not recognized.
/// </summary>
/// <param name="grain"></param>
/// <param name="request"></param>
/// <returns></returns>
public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request)
{
if (extensionMap == null || !extensionMap.ContainsKey(request.InterfaceId))
throw new InvalidOperationException(
String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", request.InterfaceId));
var invoker = extensionMap[request.InterfaceId].Item2;
var extension = extensionMap[request.InterfaceId].Item1;
return invoker.Invoke(extension, request);
}
public bool IsExtensionInstalled(int interfaceId)
{
return extensionMap != null && extensionMap.ContainsKey(interfaceId);
}
public int InterfaceId
{
get { return 0; } // 0 indicates an extension invoker that may have multiple intefaces inplemented by extensions.
}
public ushort InterfaceVersion
{
get { return 0; }
}
/// <summary>
/// Gets the extension from this instance if it is available.
/// </summary>
/// <param name="interfaceId">The interface id.</param>
/// <param name="extension">The extension.</param>
/// <returns>
/// <see langword="true"/> if the extension is found, <see langword="false"/> otherwise.
/// </returns>
public bool TryGetExtension(int interfaceId, out IGrainExtension extension)
{
Tuple<IGrainExtension, IGrainExtensionMethodInvoker> value;
if (extensionMap != null && extensionMap.TryGetValue(interfaceId, out value))
{
extension = value.Item1;
}
else
{
extension = null;
}
return extension != null;
}
}
internal class GrainActivationContextFactory
{
public IGrainActivationContext Context { get; set; }
}
// This is the maximum amount of time we expect a request to continue processing
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
private readonly NodeConfiguration nodeConfiguration;
public readonly TimeSpan CollectionAgeLimit;
private readonly Logger logger;
private IGrainMethodInvoker lastInvoker;
private IServiceScope serviceScope;
// This is the maximum number of enqueued request messages for a single activation before we write a warning log or reject new requests.
private LimitValue maxEnqueuedRequestsLimit;
private HashSet<IGrainTimer> timers;
public ActivationData(
ActivationAddress addr,
string genericArguments,
PlacementStrategy placedUsing,
MultiClusterRegistrationStrategy registrationStrategy,
IActivationCollector collector,
TimeSpan ageLimit,
NodeConfiguration nodeConfiguration,
TimeSpan maxWarningRequestProcessingTime,
TimeSpan maxRequestProcessingTime,
IRuntimeClient runtimeClient)
{
if (null == addr) throw new ArgumentNullException(nameof(addr));
if (null == placedUsing) throw new ArgumentNullException(nameof(placedUsing));
if (null == collector) throw new ArgumentNullException(nameof(collector));
logger = LogManager.GetLogger("ActivationData", LoggerType.Runtime);
this.lifecycle = new GrainLifecycle(logger);
this.maxRequestProcessingTime = maxRequestProcessingTime;
this.maxWarningRequestProcessingTime = maxWarningRequestProcessingTime;
this.nodeConfiguration = nodeConfiguration;
ResetKeepAliveRequest();
Address = addr;
State = ActivationState.Create;
PlacedUsing = placedUsing;
RegistrationStrategy = registrationStrategy;
if (!Grain.IsSystemTarget && !Constants.IsSystemGrain(Grain))
{
this.collector = collector;
}
CollectionAgeLimit = ageLimit;
GrainReference = GrainReference.FromGrainId(addr.Grain, runtimeClient.GrainReferenceRuntime, genericArguments, Grain.IsSystemTarget ? addr.Silo : null);
this.SchedulingContext = new SchedulingContext(this);
}
public Type GrainType => GrainTypeData.Type;
public IGrainIdentity GrainIdentity => this.Identity;
public IServiceProvider ActivationServices => this.serviceScope.ServiceProvider;
#region Method invocation
private ExtensionInvoker extensionInvoker;
public IGrainMethodInvoker GetInvoker(GrainTypeManager typeManager, int interfaceId, string genericGrainType = null)
{
// Return previous cached invoker, if applicable
if (lastInvoker != null && interfaceId == lastInvoker.InterfaceId) // extension invoker returns InterfaceId==0, so this condition will never be true if an extension is installed
return lastInvoker;
if (extensionInvoker != null && extensionInvoker.IsExtensionInstalled(interfaceId))
{
// Shared invoker for all extensions installed on this grain
lastInvoker = extensionInvoker;
}
else
{
// Find the specific invoker for this interface / grain type
lastInvoker = typeManager.GetInvoker(interfaceId, genericGrainType);
}
return lastInvoker;
}
internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension extension)
{
if(extensionInvoker == null)
extensionInvoker = new ExtensionInvoker();
return extensionInvoker.TryAddExtension(invoker, extension);
}
internal void RemoveExtension(IGrainExtension extension)
{
if (extensionInvoker != null)
{
if (extensionInvoker.Remove(extension))
extensionInvoker = null;
}
else
throw new InvalidOperationException("Grain extensions not installed.");
}
internal bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result)
{
result = null;
return extensionInvoker != null && extensionInvoker.TryGetExtensionHandler(extensionType, out result);
}
#endregion
public ISchedulingContext SchedulingContext { get; }
public string GrainTypeName
{
get
{
if (GrainInstanceType == null)
{
throw new ArgumentNullException("GrainInstanceType", "GrainInstanceType has not been set.");
}
return GrainInstanceType.FullName;
}
}
internal Type GrainInstanceType => GrainTypeData?.Type;
internal void SetGrainInstance(Grain grainInstance)
{
GrainInstance = grainInstance;
}
internal void SetupContext(GrainTypeData typeData, IServiceProvider grainServices)
{
this.GrainTypeData = typeData;
this.Items = new Dictionary<object, object>();
this.serviceScope = grainServices.CreateScope();
SetGrainActivationContextInScopedServices(this.ActivationServices, this);
if (typeData != null)
{
var grainType = typeData.Type;
// Don't ever collect system grains or reminder table grain or memory store grains.
bool doNotCollect = typeof(IReminderTableGrain).IsAssignableFrom(grainType) || typeof(IMemoryStorageGrain).IsAssignableFrom(grainType);
if (doNotCollect)
{
this.collector = null;
}
}
}
private static void SetGrainActivationContextInScopedServices(IServiceProvider sp, IGrainActivationContext context)
{
var contextFactory = sp.GetRequiredService<GrainActivationContextFactory>();
contextFactory.Context = context;
}
public IStorageProvider StorageProvider { get; set; }
private Streams.StreamDirectory streamDirectory;
internal Streams.StreamDirectory GetStreamDirectory()
{
return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory());
}
internal bool IsUsingStreams
{
get { return streamDirectory != null; }
}
internal async Task DeactivateStreamResources()
{
if (streamDirectory == null) return; // No streams - Nothing to do.
if (extensionInvoker == null) return; // No installed extensions - Nothing to do.
if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate)
{
logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this);
return;
}
await streamDirectory.Cleanup(true, false);
}
#region IActivationData
GrainReference IActivationData.GrainReference
{
get { return GrainReference; }
}
public GrainId Identity
{
get { return Grain; }
}
public GrainTypeData GrainTypeData { get; private set; }
public Grain GrainInstance { get; private set; }
public ActivationId ActivationId { get { return Address.Activation; } }
public ActivationAddress Address { get; private set; }
public IServiceProvider ServiceProvider => this.serviceScope?.ServiceProvider;
public IDictionary<object, object> Items { get; private set; }
private readonly GrainLifecycle lifecycle;
public IGrainLifecycle ObservableLifecycle => lifecycle;
internal ILifecycleObserver Lifecycle => lifecycle;
public void OnTimerCreated(IGrainTimer timer)
{
AddTimer(timer);
}
#endregion
#region Catalog
internal readonly GrainReference GrainReference;
public SiloAddress Silo { get { return Address.Silo; } }
public GrainId Grain { get { return Address.Grain; } }
public ActivationState State { get; private set; }
public void SetState(ActivationState state)
{
State = state;
}
// Don't accept any new messages and stop all timers.
public void PrepareForDeactivation()
{
SetState(ActivationState.Deactivating);
deactivationStartTime = DateTime.UtcNow;
StopAllTimers();
}
/// <summary>
/// If State == Invalid, this may contain a forwarding address for incoming messages
/// </summary>
public ActivationAddress ForwardingAddress { get; set; }
private IActivationCollector collector;
internal bool IsExemptFromCollection
{
get { return collector == null; }
}
public DateTime CollectionTicket { get; private set; }
private bool collectionCancelledFlag;
public bool TrySetCollectionCancelledFlag()
{
lock (this)
{
if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false;
collectionCancelledFlag = true;
return true;
}
}
public void ResetCollectionCancelledFlag()
{
lock (this)
{
collectionCancelledFlag = false;
}
}
public void ResetCollectionTicket()
{
CollectionTicket = default(DateTime);
}
public void SetCollectionTicket(DateTime ticket)
{
if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket");
if (CollectionTicket != default(DateTime))
{
throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket.");
}
CollectionTicket = ticket;
}
#endregion
#region Dispatcher
public PlacementStrategy PlacedUsing { get; private set; }
public MultiClusterRegistrationStrategy RegistrationStrategy { get; private set; }
// Currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy.
internal bool IsStatelessWorker { get { return PlacedUsing is StatelessWorkerPlacement; } }
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
internal bool IsUsingGrainDirectory { get { return !IsStatelessWorker; } }
public Message Running { get; private set; }
// the number of requests that are currently executing on this activation.
// includes reentrant and non-reentrant requests.
private int numRunning;
private DateTime currentRequestStartTime;
private DateTime becameIdle;
private DateTime deactivationStartTime;
public void RecordRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning++;
if (Running != null) return;
// This logic only works for non-reentrant activations
// Consider: Handle long request detection for reentrant activations.
Running = message;
currentRequestStartTime = DateTime.UtcNow;
}
public void ResetRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
numRunning--;
if (numRunning == 0)
{
becameIdle = DateTime.UtcNow;
if (!IsExemptFromCollection)
{
collector.TryRescheduleCollection(this);
}
}
// The below logic only works for non-reentrant activations.
if (Running != null && !message.Equals(Running)) return;
Running = null;
currentRequestStartTime = DateTime.MinValue;
}
private long inFlightCount;
private long enqueuedOnDispatcherCount;
/// <summary>
/// Number of messages that are actively being processed [as opposed to being in the Waiting queue].
/// In most cases this will be 0 or 1, but for Reentrant grains can be >1.
/// </summary>
public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } }
/// <summary>
/// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed].
/// </summary>
public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } }
/// <summary>Increment the number of in-flight messages currently being processed.</summary>
public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); }
/// <summary>Decrement the number of in-flight messages currently being processed.</summary>
public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); }
/// <summary>Increment the number of messages currently in the prcess of being received.</summary>
public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); }
/// <summary>Decrement the number of messages currently in the prcess of being received.</summary>
public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); }
/// <summary>
/// grouped by sending activation: responses first, then sorted by id
/// </summary>
private List<Message> waiting;
public int WaitingCount
{
get
{
return waiting == null ? 0 : waiting.Count;
}
}
public enum EnqueueMessageResult
{
Success,
ErrorInvalidActivation,
ErrorStuckActivation,
}
/// <summary>
/// Insert in a FIFO order
/// </summary>
/// <param name="message"></param>
public EnqueueMessageResult EnqueueMessage(Message message)
{
lock (this)
{
if (State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message);
return EnqueueMessageResult.ErrorInvalidActivation;
}
if (State == ActivationState.Deactivating)
{
var deactivatingTime = DateTime.UtcNow - deactivationStartTime;
if (deactivatingTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current activation {ToDetailedString()} marked as Deactivating for {deactivatingTime}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
}
if (Running != null)
{
var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime;
if (currentRequestActiveTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current request has been active for {currentRequestActiveTime} for activation {ToDetailedString()}. Currently executing {Running}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
// Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations
else if (currentRequestActiveTime > maxWarningRequestProcessingTime)
{
logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing,
"Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.",
currentRequestActiveTime, this.ToDetailedString(), Running, message);
}
}
waiting = waiting ?? new List<Message>();
waiting.Add(message);
return EnqueueMessageResult.Success;
}
}
/// <summary>
/// Check whether this activation is overloaded.
/// Returns LimitExceededException if overloaded, otherwise <c>null</c>c>
/// </summary>
/// <param name="log">Logger to use for reporting any overflow condition</param>
/// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns>
public LimitExceededException CheckOverloaded(Logger log)
{
LimitValue limitValue = GetMaxEnqueuedRequestLimit();
int maxRequestsHardLimit = limitValue.HardLimitThreshold;
int maxRequestsSoftLimit = limitValue.SoftLimitThreshold;
if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set
int count = GetRequestCount();
if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit
{
log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests,
String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}",
count, this, maxRequestsHardLimit));
return new LimitExceededException(limitValue.Name, count, maxRequestsHardLimit, this.ToString());
}
if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit
{
log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests,
String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}",
count, this, maxRequestsSoftLimit));
return null;
}
return null;
}
internal int GetRequestCount()
{
lock (this)
{
long numInDispatcher = EnqueuedOnDispatcherCount;
long numActive = InFlightCount;
long numWaiting = WaitingCount;
return (int)(numInDispatcher + numActive + numWaiting);
}
}
private LimitValue GetMaxEnqueuedRequestLimit()
{
if (maxEnqueuedRequestsLimit != null) return maxEnqueuedRequestsLimit;
if (GrainInstanceType != null)
{
string limitName = CodeGeneration.GrainInterfaceUtils.IsStatelessWorker(GrainInstanceType.GetTypeInfo())
? LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER
: LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
maxEnqueuedRequestsLimit = nodeConfiguration.LimitManager.GetLimit(limitName); // Cache for next time
return maxEnqueuedRequestsLimit;
}
return nodeConfiguration.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
}
public Message PeekNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0) return waiting[0];
return null;
}
public void DequeueNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0)
waiting.RemoveAt(0);
}
internal List<Message> DequeueAllWaitingMessages()
{
lock (this)
{
if (waiting == null) return null;
List<Message> tmp = waiting;
waiting = null;
return tmp;
}
}
#endregion
#region Activation collection
public bool IsInactive
{
get
{
return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0);
}
}
public bool IsCurrentlyExecuting
{
get
{
return numRunning > 0 ;
}
}
/// <summary>
/// Returns how long this activation has been idle.
/// </summary>
public TimeSpan GetIdleness(DateTime now)
{
if (now == default(DateTime))
throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now");
return now - becameIdle;
}
/// <summary>
/// Returns whether this activation has been idle long enough to be collected.
/// </summary>
public bool IsStale(DateTime now)
{
return GetIdleness(now) >= CollectionAgeLimit;
}
private DateTime keepAliveUntil;
public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } }
public void DelayDeactivation(TimeSpan timespan)
{
if (timespan <= TimeSpan.Zero)
{
// reset any current keepAliveUntill
ResetKeepAliveRequest();
}
else if (timespan == TimeSpan.MaxValue)
{
// otherwise creates negative time.
keepAliveUntil = DateTime.MaxValue;
}
else
{
keepAliveUntil = DateTime.UtcNow + timespan;
}
}
public void ResetKeepAliveRequest()
{
keepAliveUntil = DateTime.MinValue;
}
public List<Action> OnInactive { get; set; } // ActivationData
public void AddOnInactive(Action action) // ActivationData
{
lock (this)
{
if (OnInactive == null)
{
OnInactive = new List<Action>();
}
OnInactive.Add(action);
}
}
public void RunOnInactive()
{
lock (this)
{
if (OnInactive == null) return;
var actions = OnInactive;
OnInactive = null;
foreach (var action in actions)
{
action();
}
}
}
#endregion
#region In-grain Timers
internal void AddTimer(IGrainTimer timer)
{
lock(this)
{
if (timers == null)
{
timers = new HashSet<IGrainTimer>();
}
timers.Add(timer);
}
}
private void StopAllTimers()
{
lock (this)
{
if (timers == null) return;
foreach (var timer in timers)
{
timer.Stop();
}
}
}
public void OnTimerDisposed(IGrainTimer orleansTimerInsideGrain)
{
lock (this) // need to lock since dispose can be called on finalizer thread, outside garin context (not single threaded).
{
timers.Remove(orleansTimerInsideGrain);
}
}
internal Task WaitForAllTimersToFinish()
{
lock(this)
{
if (timers == null)
{
return Task.CompletedTask;
}
var tasks = new List<Task>();
var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set.
foreach (var timer in timerCopy)
{
// first call dispose, then wait to finish.
Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown");
tasks.Add(timer.GetCurrentlyExecutingTickTask());
}
return Task.WhenAll(tasks);
}
}
#endregion
#region Printing functions
public string DumpStatus()
{
var sb = new StringBuilder();
lock (this)
{
sb.AppendFormat(" {0}", ToDetailedString());
if (Running != null)
{
sb.AppendFormat(" Processing message: {0}", Running);
}
if (waiting!=null && waiting.Count > 0)
{
sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue());
}
}
return sb.ToString();
}
public override string ToString()
{
return String.Format("[Activation: {0}{1}{2}{3} State={4}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString(),
State);
}
internal string ToDetailedString(bool includeExtraDetails = false)
{
return
String.Format(
"[Activation: {0}{1}{2}{3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]",
Silo.ToLongString(),
Grain.ToDetailedString(),
ActivationId,
GetActivationInfoString(),
State, // 4
WaitingCount, // 5 NonReentrancyQueueSize
EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher
InFlightCount, // 7 InFlightCount
numRunning, // 8 NumRunning
GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan
CollectionAgeLimit, // 10 CollectionAgeLimit
(includeExtraDetails && Running != null) ? " CurrentlyExecuting=" + Running : ""); // 11: Running
}
public string Name
{
get
{
return String.Format("[Activation: {0}{1}{2}{3}]",
Silo,
Grain,
ActivationId,
GetActivationInfoString());
}
}
/// <summary>
/// Return string containing dump of the queue of waiting work items
/// </summary>
/// <returns></returns>
/// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks>
internal string PrintWaitingQueue()
{
return Utils.EnumerableToString(waiting);
}
private string GetActivationInfoString()
{
var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty;
return GrainInstanceType == null ? placement :
String.Format(" #GrainType={0} Placement={1}", GrainInstanceType.FullName, placement);
}
#endregion
public void Dispose()
{
IDisposable disposable = serviceScope;
if (disposable != null) disposable.Dispose();
this.serviceScope = null;
}
}
internal static class StreamResourceTestControl
{
internal static bool TestOnlySuppressStreamCleanupOnDeactivate;
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.AspNet.Razor.Text;
namespace Microsoft.AspNet.Razor.Generator.Compiler.CSharp
{
public class CSharpCodeWriter : CodeWriter
{
public CSharpCodeWriter()
{
LineMappingManager = new LineMappingManager();
}
public LineMappingManager LineMappingManager { get; private set; }
public new CSharpCodeWriter Write(string data)
{
return (CSharpCodeWriter)base.Write(data);
}
public new CSharpCodeWriter Indent(int size)
{
return (CSharpCodeWriter)base.Indent(size);
}
public new CSharpCodeWriter ResetIndent()
{
return (CSharpCodeWriter)base.ResetIndent();
}
public new CSharpCodeWriter SetIndent(int size)
{
return (CSharpCodeWriter)base.SetIndent(size);
}
public new CSharpCodeWriter IncreaseIndent(int size)
{
return (CSharpCodeWriter)base.IncreaseIndent(size);
}
public new CSharpCodeWriter DecreaseIndent(int size)
{
return (CSharpCodeWriter)base.DecreaseIndent(size);
}
public new CSharpCodeWriter WriteLine(string data)
{
return (CSharpCodeWriter)base.WriteLine(data);
}
public new CSharpCodeWriter WriteLine()
{
return (CSharpCodeWriter)base.WriteLine();
}
public CSharpCodeWriter WriteVariableDeclaration(string type, string name, string value)
{
Write(type).Write(" ").Write(name);
if (!String.IsNullOrEmpty(value))
{
Write(" = ").Write(value);
}
else
{
Write(" = null");
}
WriteLine(";");
return this;
}
public CSharpCodeWriter WriteComment(string comment)
{
return Write("// ").WriteLine(comment);
}
public CSharpCodeWriter WriteBooleanLiteral(bool value)
{
return Write(value.ToString().ToLowerInvariant());
}
public CSharpCodeWriter WriteStartAssignment(string name)
{
return Write(name).Write(" = ");
}
public CSharpCodeWriter WriteParameterSeparator()
{
return Write(", ");
}
public CSharpCodeWriter WriteStartNewObject(string typeName)
{
return Write("new ").Write(typeName).Write("(");
}
public CSharpCodeWriter WriteLocationTaggedString(LocationTagged<string> value)
{
WriteStartMethodInvocation("Tuple.Create");
WriteStringLiteral(value.Value);
WriteParameterSeparator();
Write(value.Location.AbsoluteIndex.ToString(CultureInfo.CurrentCulture));
WriteEndMethodInvocation(false);
return this;
}
public CSharpCodeWriter WriteStringLiteral(string literal)
{
if (literal.Length >= 256 && literal.Length <= 1500 && literal.IndexOf('\0') == -1)
{
WriteVerbatimStringLiteral(literal);
}
else
{
WriteCStyleStringLiteral(literal);
}
return this;
}
public CSharpCodeWriter WriteLineHiddenDirective()
{
return WriteLine("#line hidden");
}
public CSharpCodeWriter WritePragma(string value)
{
return Write("#pragma ").WriteLine(value);
}
public CSharpCodeWriter WriteUsing(string name)
{
return WriteUsing(name, endLine: true);
}
public CSharpCodeWriter WriteUsing(string name, bool endLine)
{
Write(String.Format("using {0}", name));
if(endLine)
{
WriteLine(";");
}
return this;
}
public CSharpCodeWriter WriteLineDefaultDirective()
{
return WriteLine("#line default");
}
public CSharpCodeWriter WriteStartReturn()
{
return Write("return ");
}
public CSharpCodeWriter WriteReturn(string value)
{
return WriteReturn(value, endLine: true);
}
public CSharpCodeWriter WriteReturn(string value, bool endLine)
{
Write("return ").Write(value);
if (endLine)
{
Write(";");
}
return WriteLine();
}
public CSharpCodeWriter WriteLineNumberDirective(int lineNumber, string file)
{
return Write("#line ").Write(lineNumber.ToString()).Write(" \"").Write(file).WriteLine("\"");
}
public CSharpCodeWriter WriteStartMethodInvocation(string methodName)
{
return WriteStartMethodInvocation(methodName, new string[0]);
}
public CSharpCodeWriter WriteStartMethodInvocation(string methodName, string[] genericArguments)
{
Write(methodName);
if (genericArguments.Length > 0)
{
Write("<").Write(string.Join(", ", genericArguments)).Write(">");
}
return Write("(");
}
public CSharpCodeWriter WriteEndMethodInvocation()
{
return WriteEndMethodInvocation(endLine: true);
}
public CSharpCodeWriter WriteEndMethodInvocation(bool endLine)
{
Write(")");
if (endLine)
{
WriteLine(";");
}
return this;
}
public CSharpCodeWriter WriteMethodInvocation(string methodName, params string[] parameters)
{
return WriteMethodInvocation(methodName, endLine: true, parameters: parameters);
}
public CSharpCodeWriter WriteMethodInvocation(string methodName, bool endLine, params string[] parameters)
{
return WriteStartMethodInvocation(methodName).Write(string.Join(", ", parameters)).WriteEndMethodInvocation(endLine);
}
public CSharpDisableWarningScope BuildDisableWarningScope(int warning)
{
return new CSharpDisableWarningScope(this, warning);
}
public CSharpCodeWritingScope BuildScope()
{
return new CSharpCodeWritingScope(this);
}
public CSharpCodeWritingScope BuildLambda(params string[] parameterNames)
{
return BuildLambda(true, parameterNames);
}
public CSharpCodeWritingScope BuildLambda(bool endLine, params string[] parameterNames)
{
Write("(").Write(string.Join(", ", parameterNames)).Write(") => ");
var scope = new CSharpCodeWritingScope(this);
if (endLine)
{
// End the lambda with a semicolon
scope.OnClose += () =>
{
WriteLine(";");
};
}
return scope;
}
public CSharpCodeWritingScope BuildNamespace(string name)
{
Write("namespace ").WriteLine(name);
return new CSharpCodeWritingScope(this);
}
public CSharpCodeWritingScope BuildClassDeclaration(string accessibility, string name)
{
return BuildClassDeclaration(accessibility, name, Enumerable.Empty<string>());
}
public CSharpCodeWritingScope BuildClassDeclaration(string accessibility, string name, string baseType)
{
return BuildClassDeclaration(accessibility, name, new string[] { baseType });
}
public CSharpCodeWritingScope BuildClassDeclaration(string accessibility, string name, IEnumerable<string> baseTypes)
{
Write(accessibility).Write(" class ").Write(name);
if (baseTypes.Count() > 0)
{
Write(" : ");
Write(string.Join(", ", baseTypes));
}
WriteLine();
return new CSharpCodeWritingScope(this);
}
public CSharpCodeWritingScope BuildConstructor(string name)
{
return BuildConstructor("public", name);
}
public CSharpCodeWritingScope BuildConstructor(string accessibility, string name)
{
return BuildConstructor(accessibility, name, Enumerable.Empty<KeyValuePair<string, string>>());
}
public CSharpCodeWritingScope BuildConstructor(string accessibility, string name, IEnumerable<KeyValuePair<string, string>> parameters)
{
Write(accessibility).Write(" ").Write(name).Write("(").Write(string.Join(", ", parameters.Select(p => p.Key + " " + p.Value))).WriteLine(")");
return new CSharpCodeWritingScope(this);
}
public CSharpCodeWritingScope BuildMethodDeclaration(string accessibility, string returnType, string name)
{
return BuildMethodDeclaration(accessibility, returnType, name, Enumerable.Empty<KeyValuePair<string, string>>());
}
public CSharpCodeWritingScope BuildMethodDeclaration(string accessibility, string returnType, string name, IEnumerable<KeyValuePair<string, string>> parameters)
{
Write(accessibility).Write(" ").Write(returnType).Write(" ").Write(name).Write("(").Write(string.Join(", ", parameters.Select(p => p.Key + " " + p.Value))).WriteLine(")");
return new CSharpCodeWritingScope(this);
}
// TODO: Do I need to look at the document content to determine its mapping length?
public CSharpLineMappingWriter BuildLineMapping(SourceLocation documentLocation, int contentLength, string sourceFilename)
{
return new CSharpLineMappingWriter(this, documentLocation, contentLength, sourceFilename);
}
private void WriteVerbatimStringLiteral(string literal)
{
Write("@\"");
foreach (char c in literal)
{
if (c == '\"')
{
Write("\"\"");
}
else
{
Write(c.ToString());
}
}
Write("\"");
}
private void WriteCStyleStringLiteral(string literal)
{
// From CSharpCodeGenerator.QuoteSnippetStringCStyle in CodeDOM
Write("\"");
for (int i = 0; i < literal.Length; i++)
{
switch (literal[i])
{
case '\r':
Write("\\r");
break;
case '\t':
Write("\\t");
break;
case '\"':
Write("\\\"");
break;
case '\'':
Write("\\\'");
break;
case '\\':
Write("\\\\");
break;
case '\0':
Write("\\\0");
break;
case '\n':
Write("\\n");
break;
case '\u2028':
case '\u2029':
Write("\\u");
Write(((int)literal[i]).ToString("X4", CultureInfo.InvariantCulture));
break;
default:
Write(literal[i].ToString());
break;
}
if (i > 0 && i % 80 == 0)
{
// If current character is a high surrogate and the following
// character is a low surrogate, don't break them.
// Otherwise when we write the string to a file, we might lose
// the characters.
if (Char.IsHighSurrogate(literal[i])
&& (i < literal.Length - 1)
&& Char.IsLowSurrogate(literal[i + 1]))
{
Write(literal[++i].ToString());
}
Write("\" +");
Write(Environment.NewLine);
Write("\"");
}
}
Write("\"");
}
}
}
| |
using Shouldly;
using System;
using Xunit;
namespace Valit.Tests.Float
{
public class Float_IsEqualTo_Tests
{
[Fact]
public void Float_IsEqualTo_For_Not_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, float>)null)
.IsEqualTo(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Float_IsEqualTo_For_Not_Nullable_Value_And_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, float>)null)
.IsEqualTo((float?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Float_IsEqualTo_For_Nullable_Value_And_Not_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, float?>)null)
.IsEqualTo(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Float_IsEqualTo_For_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, float?>)null)
.IsEqualTo((float?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Theory]
[InlineData(10, false)]
[InlineData(Single.NaN, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_NaN_And_Value(float value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, false)]
[InlineData(Single.NaN, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_NaN_And_NullableValue(float? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, false)]
[InlineData(Single.NaN, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_NullableNaN_And_Value(float value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, false)]
[InlineData(Single.NaN, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_NullableNaN_And_NullableValue(float? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(10, true)]
[InlineData(11, false)]
[InlineData(9, false)]
[InlineData(Single.NaN, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_Not_Nullable_Values(float value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData((float)10, true)]
[InlineData((float)11, false)]
[InlineData((float)9, false)]
[InlineData(Single.NaN, false)]
[InlineData(null, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_Not_Nullable_Value_And_Nullable_Value(float? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, 10, true)]
[InlineData(false, 11, false)]
[InlineData(false, 9, false)]
[InlineData(true, 10, false)]
[InlineData(false, Single.NaN, false)]
[InlineData(true, Single.NaN, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_Nullable_Value_And_Not_Nullable_Value(bool useNullValue, float value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, (float)10, true)]
[InlineData(false, (float)11, false)]
[InlineData(false, (float)9, false)]
[InlineData(false, Single.NaN, false)]
[InlineData(false, null, false)]
[InlineData(true, (float)10, false)]
[InlineData(true, Single.NaN, false)]
[InlineData(true, null, false)]
public void Float_IsEqualTo_Returns_Proper_Results_For_Nullable_Values(bool useNullValue, float? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
#region ARRANGE
public Float_IsEqualTo_Tests()
{
_model = new Model();
}
private readonly Model _model;
class Model
{
public float Value => 10;
public float NaN => Single.NaN;
public float? NullableValue => 10;
public float? NullValue => null;
public float? NullableNaN => Single.NaN;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Faithlife.Utility
{
/// <summary>
/// Provides methods for manipulating dictionaries.
/// </summary>
public static class DictionaryUtility
{
/// <summary>
/// Returns true if there is a one-to-one relationship between every key-value pair.
/// </summary>
/// <remarks>Uses the default equality comparer for TValue if none is specified.</remarks>
public static bool AreEqual<TKey, TValue>(IReadOnlyDictionary<TKey, TValue>? left, IReadOnlyDictionary<TKey, TValue>? right, IEqualityComparer<TValue>? comparer = null)
where TKey : notnull
{
comparer ??= EqualityComparer<TValue>.Default;
if (left == right)
return true;
if (left is null || right is null || left.Count != right.Count)
return false;
foreach (var pair in left)
{
if (!right.TryGetValue(pair.Key, out var value) || !comparer.Equals(pair.Value, value))
return false;
}
return true;
}
/// <summary>
/// Wraps the dictionary in a read-only dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary to wrap.</param>
/// <returns>The read-only dictionary.</returns>
public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
where TKey : notnull => new(dictionary);
/// <summary>
/// Represents the sequence of key-value pairs as a <see cref="IReadOnlyDictionary{TKey,TValue}"/>.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="keyValuePairs">The key-value pairs.</param>
/// <returns>A <see cref="IReadOnlyDictionary{TKey,TValue}"/> containing the key-value pairs in the sequence.</returns>
/// <remarks>If the sequence is an <see cref="IReadOnlyDictionary{TKey,TValue}"/>, it is returned directly.
/// If it is an <see cref="IDictionary{TKey,TValue}"/>, an adapter is created to wrap it. Otherwise, the sequence
/// is copied into a <see cref="Dictionary{TKey,TValue}"/> and then wrapped in a <see cref="ReadOnlyDictionary{TKey,TValue}"/>.
/// This method is useful for forcing evaluation of a potentially lazy sequence while retaining reasonable
/// performance for sequences that are already an <see cref="IReadOnlyDictionary{TKey,TValue}"/> or <see cref="IDictionary{TKey,TValue}"/>.</remarks>
public static IReadOnlyDictionary<TKey, TValue> AsReadOnlyDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
where TKey : notnull
{
return keyValuePairs as IReadOnlyDictionary<TKey, TValue> ??
(keyValuePairs is IDictionary<TKey, TValue> dictionary ?
(IReadOnlyDictionary<TKey, TValue>) new ReadOnlyDictionaryAdapter<TKey, TValue>(dictionary) :
keyValuePairs.ToDictionary(x => x.Key, x => x.Value).AsReadOnly());
}
/// <summary>
/// Gets a value from the dictionary, adding and returning a new instance if it is missing.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <returns>The new or existing value.</returns>
public static TValue GetOrAddValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
where TKey : notnull
where TValue : new()
{
if (dictionary.TryGetValue(key, out var value))
return value;
value = new TValue();
dictionary.Add(key, value);
return value;
}
/// <summary>
/// Gets a value from the dictionary, adding and returning a new instance if it is missing.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="creator">Used to create a new value if necessary</param>
/// <returns>The new or existing value.</returns>
public static TValue GetOrAddValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> creator)
where TKey : notnull
{
if (dictionary.TryGetValue(key, out var value))
return value;
value = creator();
dictionary.Add(key, value);
return value;
}
/// <summary>
/// Gets a value from the dictionary, returning a default value if it is missing.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <returns>The value, or a default value.</returns>
#if !NETSTANDARD2_0
[Obsolete("Use System.Collections.Generic.CollectionExtensions.GetValueOrDefault instead (available in netcoreapp2.0, netstandard2.1)")]
#endif
public static TValue? GetValueOrDefault<TKey, TValue>(
#if NETSTANDARD2_0
this
#endif
IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
where TKey : notnull
{
// specification for IDictionary<> requires that the returned value be the default if it fails
dictionary.TryGetValue(key, out var value);
return value;
}
/// <summary>
/// Gets a value from the dictionary, returning the specified default value if it is missing.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>The value, or a default value.</returns>
#if !NETSTANDARD2_0
[Obsolete("Use System.Collections.Generic.CollectionExtensions.GetValueOrDefault instead (available in netcoreapp2.0, netstandard2.1)")]
#endif
public static TValue GetValueOrDefault<TKey, TValue>(
#if NETSTANDARD2_0
this
#endif
IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
where TKey : notnull
=> dictionary.TryGetValue(key, out var value) ? value : defaultValue;
/// <summary>
/// Gets a value from the dictionary, returning the generated default value if it is missing.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="getDefaultValue">The default value generator.</param>
/// <returns>The value, or a default value.</returns>
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> getDefaultValue)
where TKey : notnull
=> dictionary.TryGetValue(key, out var value) ? value : getDefaultValue();
/// <summary>
/// Creates a key value pair.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>The key value pair.</returns>
#if !NETSTANDARD2_0
[Obsolete("Use System.Collections.Generic.KeyValuePair.Create instead (available in netcoreapp2.0, netstandard2.1)")]
#endif
public static KeyValuePair<TKey, TValue> CreateKeyValuePair<TKey, TValue>(TKey key, TValue value) => new(key, value);
/// <summary>
/// Tries to add a value to the dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>True if successful, i.e. the key was not already in the dictionary.</returns>
/// <remarks>Unfortunately, there is no more efficient way to do this on an IDictionary than to check
/// ContainsKey before calling Add.</remarks>
#if !NETSTANDARD2_0
[Obsolete("Use System.Collections.Generic.CollectionExtensions.TryAdd instead (available in netcoreapp2.0, netstandard2.1)")]
#endif
public static bool TryAdd<TKey, TValue>(
#if NETSTANDARD2_0
this
#endif
IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
where TKey : notnull
{
if (dictionary.ContainsKey(key))
return false;
dictionary.Add(key, value);
return true;
}
}
}
| |
// *****************************************************************************
//
// Copyright 2004, Weifen Luo
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Weifen Luo
// and are supplied subject to licence terms.
//
// WinFormsUI Library Version 1.0
// *****************************************************************************
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using WeifenLuo.WinFormsUI;
namespace SoftLogik.Win.UI.Controls.Docking
{
[ToolboxItem(false)]
public class DockPaneStripFromBase : DockPaneStripBase
{
#region Private Consts
private const int _ToolWindowStripGapLeft = 4;
private const int _ToolWindowStripGapRight = 3;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 2;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 5;
private const int _ToolWindowImageGapRight = 2;
private const int _ToolWindowTextGapRight = 1;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentToolWindowTabMinHeight = 24;
private const int _DocumentTabMinHeight = 20;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 3;
private const int _DocumentButtonGapBottom = 4;
private const int _DocumentButtonGapBetween = 5;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 3;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 1;
private const int _DocumentTabOverlap = 14;
private const int _DocumentTextExtraHeight = 3;
private const int _DocumentTextExtraWidth = 24;
private const int _DocumentIconGapLeft = 6;
private const int _DocumentIconHeight = 14;
private const int _DocumentIconWidth = 15;
private const string _ResourceImageCloseEnabled = "DockPaneStrip.CloseEnabled.bmp";
private const string _ResourceImageCloseDisabled = "DockPaneStrip.CloseDisabled.bmp";
private const string _ResourceImageOptionsEnabled = "DockPaneStrip.OptionsEnabled.bmp";
private const string _ResourceImageOptionsDisabled = "DockPaneStrip.OptionsDisabled.bmp";
private const string _ResourceImageOverflowEnabled = "DockPaneStrip.OverflowEnabled.bmp";
private const string _ResourceImageOverflowDisabled = "DockPaneStrip.OverflowDisabled.bmp";
private const string _ResourceToolTipClose = "DockPaneStrip_ToolTipClose";
private const string _ResourceToolTipOptions = "DockPaneStrip_ToolTipOptions";
#endregion
#region Private Variables
private int m_offsetX = 0;
private PopupButton m_buttonClose;
private PopupButton m_buttonOptions;
private IContainer m_components;
private ToolTip m_toolTip;
#endregion
#region Customizable Properties
protected virtual int ToolWindowStripGapLeft
{
get
{
return _ToolWindowStripGapLeft;
}
}
protected virtual int ToolWindowStripGapRight
{
get
{
return _ToolWindowStripGapRight;
}
}
protected virtual int ToolWindowImageHeight
{
get
{
return _ToolWindowImageHeight;
}
}
protected virtual int ToolWindowImageWidth
{
get
{
return _ToolWindowImageWidth;
}
}
protected virtual int ToolWindowImageGapTop
{
get
{
return _ToolWindowImageGapTop;
}
}
protected virtual int ToolWindowImageGapBottom
{
get
{
return _ToolWindowImageGapBottom;
}
}
protected virtual int ToolWindowImageGapLeft
{
get
{
return _ToolWindowImageGapLeft;
}
}
protected virtual int ToolWindowImageGapRight
{
get
{
return _ToolWindowImageGapRight;
}
}
protected virtual int ToolWindowTextGapRight
{
get
{
return _ToolWindowTextGapRight;
}
}
protected virtual int ToolWindowTabSeperatorGapTop
{
get
{
return _ToolWindowTabSeperatorGapTop;
}
}
protected virtual int ToolWindowTabSeperatorGapBottom
{
get
{
return _ToolWindowTabSeperatorGapBottom;
}
}
private static Image _imageCloseEnabled = null;
protected virtual Image ImageCloseEnabled
{
get
{
if (_imageCloseEnabled == null)
{
_imageCloseEnabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageCloseEnabled);
}
return _imageCloseEnabled;
}
}
private static Image _imageCloseDisabled = null;
protected virtual Image ImageCloseDisabled
{
get
{
if (_imageCloseDisabled == null)
{
_imageCloseDisabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageCloseDisabled);
}
return _imageCloseDisabled;
}
}
private static Image _imageOptionsEnabled = null;
protected virtual Image ImageOptionsEnabled
{
get
{
if (_imageOptionsEnabled == null)
{
_imageOptionsEnabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageOptionsEnabled);
}
return _imageOptionsEnabled;
}
}
private static Image _imageOptionsDisabled = null;
protected virtual Image ImageOptionsDisabled
{
get
{
if (_imageOptionsDisabled == null)
{
_imageOptionsDisabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageOptionsDisabled);
}
return _imageOptionsDisabled;
}
}
private static Image _imageOverflowEnabled = null;
protected virtual Image ImageOverflowEnabled
{
get
{
if (_imageOverflowEnabled == null)
{
_imageOverflowEnabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageOverflowEnabled);
}
return _imageOverflowEnabled;
}
}
private static Image _imageOverflowDisabled = null;
protected virtual Image ImageOverflowDisabled
{
get
{
if (_imageOverflowDisabled == null)
{
_imageOverflowDisabled = ResourceHelper.LoadExtenderBitmap(_ResourceImageOverflowDisabled);
}
return _imageOverflowDisabled;
}
}
private static string _toolTipClose = null;
protected virtual string ToolTipClose
{
get
{
if (_toolTipClose == null)
{
_toolTipClose = ResourceHelper.GetString(_ResourceToolTipClose);
}
return _toolTipClose;
}
}
private static string _toolTipOptions = null;
protected virtual string ToolTipOptions
{
get
{
if (_toolTipOptions == null)
{
_toolTipOptions = ResourceHelper.GetString(_ResourceToolTipOptions);
}
return _toolTipOptions;
}
}
private static StringFormat _toolWindowTextStringFormat = null;
protected virtual StringFormat ToolWindowTextStringFormat
{
get
{
if (_toolWindowTextStringFormat == null)
{
_toolWindowTextStringFormat = new StringFormat(StringFormat.GenericTypographic);
_toolWindowTextStringFormat.Trimming = StringTrimming.EllipsisCharacter;
_toolWindowTextStringFormat.LineAlignment = StringAlignment.Center;
_toolWindowTextStringFormat.FormatFlags = StringFormatFlags.NoWrap;
}
return _toolWindowTextStringFormat;
}
}
private static StringFormat _documentTextStringFormat = null;
public static StringFormat DocumentTextStringFormat
{
get
{
if (_documentTextStringFormat == null)
{
_documentTextStringFormat = new StringFormat(StringFormat.GenericTypographic);
_documentTextStringFormat.Alignment = StringAlignment.Center;
_documentTextStringFormat.Trimming = StringTrimming.EllipsisPath;
_documentTextStringFormat.LineAlignment = StringAlignment.Center;
_documentTextStringFormat.FormatFlags = StringFormatFlags.NoWrap;
}
return _documentTextStringFormat;
}
}
protected virtual int DocumentToolWindowTabMinHeight
{
get
{
return _DocumentToolWindowTabMinHeight;
}
}
protected virtual int DocumentTabMinHeight
{
get
{
return _DocumentTabMinHeight;
}
}
protected virtual int DocumentTabMaxWidth
{
get
{
return _DocumentTabMaxWidth;
}
}
protected virtual int DocumentButtonGapTop
{
get
{
return _DocumentButtonGapTop;
}
}
protected virtual int DocumentButtonGapBottom
{
get
{
return _DocumentButtonGapBottom;
}
}
protected virtual int DocumentButtonGapBetween
{
get
{
return _DocumentButtonGapBetween;
}
}
protected virtual int DocumentButtonGapRight
{
get
{
return _DocumentButtonGapRight;
}
}
protected virtual int DocumentTabGapTop
{
get
{
return _DocumentTabGapTop;
}
}
protected virtual int DocumentTabGapLeft
{
get
{
return _DocumentTabGapLeft;
}
}
protected virtual int DocumentTabGapRight
{
get
{
return _DocumentTabGapRight;
}
}
protected virtual int DocumentTextExtraHeight
{
get
{
return _DocumentTextExtraHeight;
}
}
protected virtual int DocumentTextExtraWidth
{
get
{
return _DocumentTextExtraWidth;
}
}
protected virtual int DocumentIconGapLeft
{
get
{
return _DocumentIconGapLeft;
}
}
protected virtual int DocumentIconWidth
{
get
{
return _DocumentIconWidth;
}
}
protected virtual int DocumentIconHeight
{
get
{
return _DocumentIconHeight;
}
}
protected virtual void OnBeginDrawTabStrip(DockPane.AppearanceStyle appearance)
{
}
protected virtual void OnEndDrawTabStrip(DockPane.AppearanceStyle appearance)
{
}
protected virtual void OnBeginDrawTab(DockPane.AppearanceStyle appearance)
{
}
protected virtual void OnEndDrawTab(DockPane.AppearanceStyle appearance)
{
}
protected virtual Pen OutlineInnerPen
{
get
{
return SystemPens.ControlText;
}
}
protected virtual Pen OutlineOuterPen
{
get
{
return new Pen(Color.FromArgb(127, 157, 185));
}
}
protected virtual Brush ActiveBackBrush
{
get
{
return SystemBrushes.Control;
}
}
protected virtual Brush ActiveTextBrush
{
get
{
return SystemBrushes.ControlText;
}
}
protected virtual Pen TabSeperatorPen
{
get
{
return SystemPens.GrayText;
}
}
protected virtual Brush InactiveTextBrush
{
get
{
return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark);
}
}
#endregion
#region new + Dispose Methods
protected internal DockPaneStripFromBase(DockPane pane)
: base(pane)
{
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
SuspendLayout();
Font = SystemInformation.MenuFont;
BackColor = Color.FromArgb(228, 226, 213);
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_buttonClose = new PopupButton(ImageCloseEnabled, ImageCloseDisabled);
m_buttonClose.IsActivated = true;
m_buttonClose.ActiveBackColorGradientBegin = Color.FromArgb(228, 226, 213);
m_buttonClose.ActiveBackColorGradientEnd = Color.FromArgb(228, 226, 213);
m_buttonClose.ToolTipText = ToolTipClose;
m_buttonClose.Anchor = AnchorStyles.Top | AnchorStyles.Right;
m_buttonOptions = new PopupButton(ImageOptionsEnabled, ImageOptionsDisabled);
m_buttonOptions.IsActivated = true;
m_buttonOptions.ActiveBackColorGradientBegin = Color.FromArgb(228, 226, 213);
m_buttonOptions.ActiveBackColorGradientEnd = Color.FromArgb(228, 226, 213);
m_buttonOptions.ToolTipText = ToolTipOptions;
m_buttonOptions.Anchor = AnchorStyles.Top | AnchorStyles.Right;
m_buttonClose.Click += new System.EventHandler(Close_Click);
m_buttonOptions.Click += new System.EventHandler(Options_Click);
Controls.AddRange(new Control[] { m_buttonClose, m_buttonOptions });
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region (Measure Height) Private Methods
protected override int MeasureHeight()
{
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.ToolWindow)
{
return MeasureHeight_ToolWindow();
}
else
{
return MeasureHeight_Document();
}
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
{
return 0;
}
int height = Math.Max(Font.Height, ToolWindowImageHeight) + ToolWindowImageGapTop + ToolWindowImageGapBottom;
if (height < DocumentToolWindowTabMinHeight)
{
height = DocumentToolWindowTabMinHeight;
}
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(Font.Height + DocumentTabGapTop + DocumentTextExtraHeight, ImageCloseEnabled.Height + DocumentButtonGapTop + DocumentButtonGapBottom);
if (height < DocumentTabMinHeight)
{
height = DocumentTabMinHeight;
}
return height;
}
#endregion
#region (OnPaint + OnRefreshChanges) Protected Methods
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle rect = TabsRectangle;
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.Document)
{
rect.X -= DocumentTabGapLeft;
rect.Width += DocumentTabGapLeft;
using (LinearGradientBrush brush = new LinearGradientBrush(rect, Color.FromArgb(228, 226, 213), Color.FromArgb(228, 226, 213), LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(brush, rect);
}
}
else
{
using (LinearGradientBrush brush = new LinearGradientBrush(rect, Color.FromArgb(231, 231, 218), Color.FromArgb(231, 231, 218), LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(brush, rect);
}
}
DrawTabStrip(e.Graphics);
}
protected override void OnResize(System.EventArgs e)
{
base.OnResize(e);
int count = Tabs.Count;
Rectangle tabrect = TabsRectangle;
// Resize to a bigger window
if (count > 1)
{
if (OffsetX < 0 && GetTabRectangle(count - 1).Right < tabrect.Right)
{
OffsetX += (tabrect.Right - GetTabRectangle(count - 1).Right);
if (DockPane.DockPanel.ShowDocumentIcon)
{
OffsetX += DocumentIconWidth;
}
if (OffsetX > 0)
{
OffsetX = 0;
}
OnRefreshChanges();
}
}
//Resize to a smaller window
IDockContent content = null;
//INSTANT C# NOTE: The ending condition of VB 'For' loops is tested only on entry to the loop. Instant C# has created a temporary variable in order to use the initial value of count for every iteration:
int tempFor1 = count;
for (int i = 0; i < tempFor1; i++)
{
content = Tabs[i].Content;
if (content == DockPane.ActiveContent)
{
if (!(tabrect.Contains(GetTabRectangle(i))))
{
EnsureTabVisible(content);
}
}
}
}
protected override void OnRefreshChanges()
{
CalculateTabs();
SetInertButtons();
Invalidate();
}
#endregion
#region (GetOutlinePath) Private Method
protected override GraphicsPath GetOutlinePath(int index)
{
Point[] pts = new Point[8];
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.Document)
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Bottom))).Y;
Rectangle rectPaneClient = DockPane.ClientRectangle;
pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y));
pts[1] = PointToScreen(new Point(rectTab.Left, rectTab.Bottom));
pts[2] = PointToScreen(new Point(rectTab.Left, rectTab.Top));
pts[3] = PointToScreen(new Point(rectTab.Right + _DocumentTabOverlap, rectTab.Top));
pts[4] = PointToScreen(new Point(rectTab.Right + _DocumentTabOverlap, rectTab.Bottom));
pts[5] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y));
pts[6] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Bottom));
pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Bottom));
}
else
{
Rectangle rectTab = GetTabRectangle(index);
rectTab.Intersect(TabsRectangle);
int y = DockPane.PointToClient(PointToScreen(new Point(0, rectTab.Top))).Y + 1;
Rectangle rectPaneClient = DockPane.ClientRectangle;
pts[0] = DockPane.PointToScreen(new Point(rectPaneClient.Left, rectPaneClient.Top));
pts[1] = DockPane.PointToScreen(new Point(rectPaneClient.Right, rectPaneClient.Top));
pts[2] = DockPane.PointToScreen(new Point(rectPaneClient.Right, y));
pts[3] = PointToScreen(new Point(rectTab.Right + 1, rectTab.Top));
pts[4] = PointToScreen(new Point(rectTab.Right + 1, rectTab.Bottom));
pts[5] = PointToScreen(new Point(rectTab.Left + 1, rectTab.Bottom));
pts[6] = PointToScreen(new Point(rectTab.Left + 1, rectTab.Top));
pts[7] = DockPane.PointToScreen(new Point(rectPaneClient.Left, y));
}
GraphicsPath path = new GraphicsPath();
path.AddLines(pts);
return path;
}
#endregion
#region (Calculate Tabs) Private Methods
private void CalculateTabs()
{
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.ToolWindow)
{
CalculateTabs_ToolWindow();
}
else
{
CalculateTabs_Document();
}
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
{
return;
}
Rectangle rectTabStrip = ClientRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (DockPaneTabFromBase tab in Tabs)
{
tab.MaxWidth = GetTabOriginalWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = (int)System.Math.Floor((double)totalWidth / countTabs);
int remainedTabs = countTabs;
anyWidthWithinAverage = true;
while (anyWidthWithinAverage && remainedTabs > 0)
{
anyWidthWithinAverage = false;
foreach (DockPaneTabFromBase tab in Tabs)
{
if (tab.Flag)
{
continue;
}
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs -= 1;
}
}
if (remainedTabs != 0)
{
averageWidth = (int)System.Math.Floor(((double)totalWidth - totalAllocatedWidth) / remainedTabs);
}
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (DockPaneTabFromBase tab in Tabs)
{
if (tab.Flag)
{
continue;
}
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth -= 1;
}
else
{
tab.TabWidth = averageWidth;
}
}
}
}
private void CalculateTabs_Document()
{
int countTabs = Tabs.Count;
if (countTabs == 0)
{
return;
}
Rectangle rectTabStrip = ClientRectangle;
int x = rectTabStrip.X + DocumentTabGapLeft + OffsetX;
foreach (DockPaneTabFromBase tab in Tabs)
{
tab.TabX = x;
tab.TabWidth = Math.Min(GetTabOriginalWidth(Tabs.IndexOf(tab)), DocumentTabMaxWidth);
x += tab.TabWidth;
}
}
#endregion
#region (GetTabOriginalWidth) Private Methods
protected virtual int GetTabOriginalWidth(int index)
{
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.ToolWindow)
{
return GetTabOriginalWidth_ToolWindow(index);
}
else
{
return GetTabOriginalWidth_Document(index);
}
}
private int GetTabOriginalWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
using (Graphics g = CreateGraphics())
{
SizeF sizeString = g.MeasureString(content.DockHandler.TabText, Font);
return ToolWindowImageWidth + System.Convert.ToInt32(sizeString.Width) + 1 + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight;
}
}
private int GetTabOriginalWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
using (Graphics g = CreateGraphics())
{
SizeF sizeText = new SizeF();
//If content Is DockPane.ActiveContent AndAlso DockPane.IsActiveDocumentPane Then
using (Font boldFont = new Font(this.Font, FontStyle.Bold))
{
sizeText = g.MeasureString(content.DockHandler.TabText, boldFont, DocumentTabMaxWidth, DocumentTextStringFormat);
}
//Else
// sizeText = g.MeasureString(content.DockHandler.TabText, Font, DocumentTabMaxWidth, DocumentTextStringFormat)
//End If
if (DockPane.DockPanel.ShowDocumentIcon)
{
return System.Convert.ToInt32(sizeText.Width) + 1 + DocumentTextExtraWidth + DocumentIconWidth + DocumentIconGapLeft;
}
else
{
return System.Convert.ToInt32(sizeText.Width) + 1 + DocumentTextExtraWidth;
}
}
}
#endregion
#region (DrawTabStrip) Private Methods
protected virtual void DrawTabStrip(Graphics g)
{
OnBeginDrawTabStrip(Appearance);
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.Document)
{
DrawTabStrip_Document(g);
}
else
{
DrawTabStrip_ToolWindow(g);
}
OnEndDrawTabStrip(Appearance);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
{
return;
}
g.DrawLine(OutlineOuterPen, ClientRectangle.Left, ClientRectangle.Bottom - 1, ClientRectangle.Right, ClientRectangle.Bottom - 1);
// Draw the tabs
Rectangle rectTabs = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
g.SetClip(rectTabs, CombineMode.Replace);
int j = 0;
//INSTANT C# NOTE: The ending condition of VB 'For' loops is tested only on entry to the loop. Instant C# has created a temporary variable in order to use the initial value of count for every iteration:
int tempFor1 = count;
for (int i = 0; i < tempFor1; i++)
{
rectTab = GetTabRectangle(i);
if (rectTab.IntersectsWith(rectTabs))
{
DrawTab(g, Tabs[i].Content, rectTab, j);
j = j + 1;
}
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
// TODO: Clean up and add properties for colors
g.SmoothingMode = SmoothingMode.AntiAlias;
//INSTANT C# NOTE: The ending condition of VB 'For' loops is tested only on entry to the loop. Instant C# has created a temporary variable in order to use the initial value of Tabs.Count for every iteration:
int tempFor1 = Tabs.Count;
for (int i = 0; i < tempFor1; i++)
{
Rectangle tabrect = GetTabRectangle(i);
Rectangle rectIcon = new Rectangle(tabrect.X + ToolWindowImageGapLeft, tabrect.Y + tabrect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = tabrect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight;
if (DockPane.ActiveContent == Tabs[i].Content)
{
// color area as the tab
g.FillRectangle(new SolidBrush(Color.FromArgb(252, 252, 254)), ClientRectangle.X, ClientRectangle.Y - 1, ClientRectangle.Width - 1, tabrect.Y + 2);
DrawHelper.DrawTab(g, tabrect, Corners.Bottom, GradientType.Flat, Color.FromArgb(252, 252, 254), Color.FromArgb(252, 252, 254), Color.FromArgb(172, 168, 153), false);
// line to the left
g.DrawLine(TabSeperatorPen, tabrect.X, tabrect.Y + 1, ClientRectangle.X, tabrect.Y + 1);
// line to the right
g.DrawLine(TabSeperatorPen, tabrect.X + tabrect.Width, tabrect.Y + 1, ClientRectangle.Width, tabrect.Y + 1);
// text
g.DrawString(Tabs[i].Content.DockHandler.TabText, Font, new SolidBrush(Color.Black), rectText, ToolWindowTextStringFormat);
}
else
{
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(Tabs[i].Content) + 1 && Tabs.IndexOf(Tabs[i].Content) != Tabs.Count - 1)
{
g.DrawLine(TabSeperatorPen, tabrect.X + tabrect.Width - 1, tabrect.Y + ToolWindowTabSeperatorGapTop, tabrect.X + tabrect.Width - 1, tabrect.Y + tabrect.Height - 1 - ToolWindowTabSeperatorGapBottom);
}
g.DrawString(Tabs[i].Content.DockHandler.TabText, Font, InactiveTextBrush, rectText, ToolWindowTextStringFormat);
}
if (tabrect.Contains(rectIcon))
{
g.DrawIcon(Tabs[i].Content.DockHandler.Icon, rectIcon);
}
}
}
#endregion
#region (GetTabRectangle) Private Methods
protected virtual Rectangle GetTabRectangle(int index)
{
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.ToolWindow)
{
return GetTabRectangle_ToolWindow(index);
}
else
{
return GetTabRectangle_Document(index);
}
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = ClientRectangle;
DockPaneTabFromBase tab = (DockPaneTabFromBase)((Tabs[index]));
return new Rectangle(tab.TabX, rectTabStrip.Y + 2, tab.TabWidth, rectTabStrip.Height - 3);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = ClientRectangle;
DockPaneTabFromBase tab = (DockPaneTabFromBase)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y + DocumentTabGapTop, tab.TabWidth, rectTabStrip.Height - DocumentTabGapTop);
}
#endregion
#region (DrawTab) Private Methods
private void DrawTab(Graphics g, IDockContent content, Rectangle rect, int index)
{
OnBeginDrawTab(Appearance);
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.ToolWindow)
{
DrawTab_ToolWindow(g, content, rect, index);
}
else
{
DrawTab_Document(g, content, rect, index);
}
OnEndDrawTab(Appearance);
}
private void DrawTab_ToolWindow(Graphics g, IDockContent content, Rectangle rect, int index)
{
Rectangle rectIcon = new Rectangle(rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight;
g.SmoothingMode = SmoothingMode.AntiAlias;
if (DockPane.ActiveContent == content)
{
DrawHelper.DrawTab(g, rect, Corners.Bottom, GradientType.Flat, Color.LightBlue, Color.WhiteSmoke, Color.Gray, false);
g.DrawString(content.DockHandler.TabText, Font, ActiveTextBrush, rectText, ToolWindowTextStringFormat);
}
else
{
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(content) + 1)
{
g.DrawLine(TabSeperatorPen, rect.X + rect.Width - 1, rect.Y + ToolWindowTabSeperatorGapTop, rect.X + rect.Width - 1, rect.Y + rect.Height - 1 - ToolWindowTabSeperatorGapBottom);
}
g.DrawString(content.DockHandler.TabText, Font, InactiveTextBrush, rectText, ToolWindowTextStringFormat);
}
if (rect.Contains(rectIcon))
{
g.DrawIcon(content.DockHandler.Icon, rectIcon);
}
}
private void DrawTab_Document(Graphics g, IDockContent content, Rectangle rect, int index)
{
Rectangle rectText = rect;
//INSTANT C# NOTE: The VB integer division operator \ was replaced 1 time(s) by the regular division operator /
rectText.X += (int)System.Math.Floor((double)DocumentTextExtraWidth / 2);
rectText.Width -= DocumentTextExtraWidth;
rectText.X += _DocumentTabOverlap;
if (index == 0)
{
rect.Width += _DocumentTabOverlap;
}
else
{
rect.X += _DocumentTabOverlap;
}
g.SmoothingMode = SmoothingMode.AntiAlias;
if (DockPane.ActiveContent == content)
{
if (index == 0)
{
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += DocumentIconGapLeft;
rectText.Width -= DocumentIconGapLeft;
}
}
else
{
rect.X -= _DocumentTabOverlap;
rect.Width += _DocumentTabOverlap;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += DocumentIconGapLeft;
rectText.Width -= DocumentIconGapLeft;
}
}
// Draw Tab & Text
DrawHelper.DrawDocumentTab(g, rect, Color.White, Color.White, Color.FromArgb(127, 157, 185), TabDrawType.Active, true);
if (DockPane.IsActiveDocumentPane)
{
using (Font boldFont = new Font(this.Font, FontStyle.Bold))
{
g.DrawString(content.DockHandler.TabText, boldFont, ActiveTextBrush, rectText, DocumentTextStringFormat);
}
}
else
{
g.DrawString(content.DockHandler.TabText, Font, InactiveTextBrush, rectText, DocumentTextStringFormat);
}
// Draw Icon
if (DockPane.DockPanel.ShowDocumentIcon)
{
Icon icon = content.DockHandler.Icon;
Rectangle rectIcon = new Rectangle();
if (index == 0)
{
rectIcon = new Rectangle(rect.X + DocumentIconGapLeft + _DocumentTabOverlap, System.Convert.ToInt32(rectText.Y + (rect.Height - DocumentIconHeight) / 2), DocumentIconWidth, DocumentIconHeight);
}
else
{
rectIcon = new Rectangle(rect.X + DocumentIconGapLeft + _DocumentTabOverlap, System.Convert.ToInt32(rectText.Y + (rect.Height - DocumentIconHeight) / 2), DocumentIconWidth, DocumentIconHeight);
}
g.DrawIcon(content.DockHandler.Icon, rectIcon);
}
}
else
{
if (index == 0)
{
DrawHelper.DrawDocumentTab(g, rect, Color.FromArgb(254, 253, 253), Color.FromArgb(241, 239, 226), Color.FromArgb(172, 168, 153), TabDrawType.First, true);
}
else
{
DrawHelper.DrawDocumentTab(g, rect, Color.FromArgb(254, 253, 253), Color.FromArgb(241, 239, 226), Color.FromArgb(172, 168, 153), TabDrawType.Inactive, true);
}
g.DrawLine(OutlineOuterPen, rect.X, ClientRectangle.Bottom - 1, rect.X + rect.Width, ClientRectangle.Bottom - 1);
g.DrawString(content.DockHandler.TabText, Font, InactiveTextBrush, rectText, DocumentTextStringFormat);
}
}
#endregion
#region (Buttons Related) Private Methods
private void SetInertButtons()
{
// Set the visibility of the inert buttons
if (DockPane.DockState == DockState.Document)
{
m_buttonClose.Visible = true;
m_buttonOptions.Visible = true;
}
else
{
m_buttonClose.Visible = false;
m_buttonOptions.Visible = false;
}
// Enable/disable overflow button
int count = Tabs.Count;
if (count != 0)
{
Rectangle rectTabs = TabsRectangle;
if (GetTabRectangle(count - 1).Right > rectTabs.Right || GetTabRectangle(0).Left < rectTabs.Left)
{
m_buttonOptions.ImageEnabled = ImageOverflowEnabled;
m_buttonOptions.ImageDisabled = ImageOverflowDisabled;
}
else
{
m_buttonOptions.ImageEnabled = ImageOptionsEnabled;
m_buttonOptions.ImageDisabled = ImageOptionsDisabled;
}
}
// Enable/disable close button
if (DockPane.ActiveContent == null)
{
m_buttonClose.Enabled = false;
}
else
{
m_buttonClose.Enabled = DockPane.ActiveContent.DockHandler.CloseButton;
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
Rectangle rectTabStrip = ClientRectangle;
// Set position and size of the buttons
int buttonWidth = ImageCloseEnabled.Width;
int buttonHeight = ImageCloseEnabled.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
//INSTANT C# NOTE: The VB integer division operator \ was replaced 1 time(s) by the regular division operator /
buttonWidth = buttonWidth * ((int)System.Math.Floor((double)height / buttonHeight));
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
m_buttonClose.Size = buttonSize;
m_buttonOptions.Size = buttonSize;
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
m_buttonClose.Location = new Point(x, y);
Point point = m_buttonClose.Location;
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
m_buttonOptions.Location = point;
OnRefreshChanges();
base.OnLayout(levent);
}
private void Close_Click(object sender, EventArgs e)
{
int i = 0;
int width = -1;
//INSTANT C# NOTE: The ending condition of VB 'For' loops is tested only on entry to the loop. Instant C# has created a temporary variable in order to use the initial value of Tabs.Count for every iteration:
int tempFor1 = Tabs.Count;
for (i = 0; i < tempFor1; i++)
{
if (Tabs[i].Content == DockPane.ActiveContent)
{
width = GetTabRectangle(i).Width;
break;
}
}
DockPane.CloseActiveContent();
if (width > 0 && Tabs.Count > 0 && GetTabRectangle(0).X < 0)
{
OffsetX += Math.Min(width, Math.Abs(GetTabRectangle(0).X)) + 4;
OnRefreshChanges();
}
}
private ContextMenuStrip m_contextmenu = new ContextMenuStrip();
private void Options_Click(object sender, EventArgs e)
{
int x = 0;
int y = m_buttonOptions.Location.Y + m_buttonOptions.Height;
m_contextmenu.Items.Clear();
foreach (IDockContent content in DockPane.Contents)
{
ToolStripMenuItem item = (ToolStripMenuItem)(m_contextmenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()));
item.Tag = content;
item.Click += new System.EventHandler(MenuItem_Click);
}
m_contextmenu.Show(m_buttonOptions, x, y);
}
private void MenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (WeifenLuo.WinFormsUI.IDockContent)item.Tag;
if (content != null)
{
EnsureTabVisible(content);
content.DockHandler.Activate();
}
}
}
protected override int GetHitTest(Point ptMouse)
{
Rectangle rectTabStrip = TabsRectangle;
//INSTANT C# NOTE: The ending condition of VB 'For' loops is tested only on entry to the loop. Instant C# has created a temporary variable in order to use the initial value of Tabs.Count for every iteration:
int tempFor1 = Tabs.Count;
for (int i = 0; i < tempFor1; i++)
{
Rectangle rectTab = GetTabRectangle(i);
rectTab.Intersect(rectTabStrip);
if (rectTab.Contains(ptMouse))
{
return i;
}
}
return -1;
}
protected override void OnMouseMove(MouseEventArgs e)
{
int index = GetHitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseMove(e);
if (index != -1)
{
Rectangle rectTab = GetTabRectangle(index);
if (Tabs[index].Content.DockHandler.ToolTipText != null)
{
toolTip = Tabs[index].Content.DockHandler.ToolTipText;
}
else if (rectTab.Width < GetTabOriginalWidth(index))
{
toolTip = Tabs[index].Content.DockHandler.TabText;
}
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
}
#endregion
#region Protected + Private Properties
protected IContainer Components
{
get
{
return m_components;
}
}
private int OffsetX
{
get
{
return m_offsetX;
}
set
{
m_offsetX = value;
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.ToolWindow)
{
return ClientRectangle;
}
Rectangle rectWindow = ClientRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + m_buttonClose.Width * 2 + DocumentButtonGapBetween * 3;
return new Rectangle(x, y, width, height);
}
}
#endregion
protected override void EnsureTabVisible(IDockContent content)
{
if (Appearance != WeifenLuo.WinFormsUI.DockPane.AppearanceStyle.Document)
{
return;
}
Rectangle rectTabStrip = TabsRectangle;
Rectangle rectTab = GetTabRectangle(Tabs.IndexOf(content));
if ((rectTab.Right + _DocumentTabOverlap) > rectTabStrip.Right)
{
OffsetX -= rectTab.Right - rectTabStrip.Right + _DocumentTabOverlap;
rectTab.X -= rectTab.Right - rectTabStrip.Right + _DocumentTabOverlap;
}
if (rectTab.Left < rectTabStrip.Left)
{
OffsetX += rectTabStrip.Left - rectTab.Left;
}
OnRefreshChanges();
}
}
}
| |
using System;
using System.Collections;
using System.Configuration;
using System.Linq;
using System.Reflection;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Linq;
namespace Elmah
{
public class RavenDbErrorLog : ErrorLog
{
private readonly string _connectionStringName;
private readonly string _version;
private IDocumentStore _documentStore;
private static IDocumentStore _externalProvidedDocumentStore;
public RavenDbErrorLog(IDictionary config)
{
if (string.IsNullOrWhiteSpace(_version))
{
_version = RetrieveVersion();
}
if (_externalProvidedDocumentStore != null)
{
_documentStore = _externalProvidedDocumentStore;
}
else
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_connectionStringName = GetConnectionStringName(config);
LoadApplicationName(config);
InitDocumentStore();
}
ConfigureDocumentStore(_documentStore);
}
private void ConfigureDocumentStore(IDocumentStore documentStore)
{
documentStore.Conventions
.RegisterIdConvention<ErrorDocument>((s, databaseCommands, errorDocument) => Guid.NewGuid().ToString());
}
public override string Name
{
get
{
return "RavenDB Error Log, version " + _version;
}
}
public override string Log(Error error)
{
if (error == null)
{
throw new ArgumentNullException("error");
}
var errorXml = ErrorXml.EncodeString(error);
var errorDoc = new ErrorDocument
{
ApplicationName = ApplicationName,
Error = error,
ErrorXml = errorXml
};
using (var session = _documentStore.OpenSession())
{
session.Store(errorDoc);
session.SaveChanges();
}
return errorDoc.Id;
}
public override ErrorLogEntry GetError(string id)
{
ErrorLogEntry result;
ErrorDocument document;
using (var session = _documentStore.OpenSession())
{
document = session.Load<ErrorDocument>(id);
}
if (!string.IsNullOrEmpty(document.ErrorXml))
{
result = new ErrorLogEntry(this, id, ErrorXml.DecodeString(document.ErrorXml));
}
else
{
result = new ErrorLogEntry(this, id, document.Error);
}
return result;
}
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
using (var session = _documentStore.OpenSession())
{
RavenQueryStatistics stats;
IQueryable<ErrorDocument> result
= session.Query<ErrorDocument>()
.Statistics(out stats)
.Skip(pageSize * pageIndex)
.Take(pageSize)
.OrderByDescending(c => c.Error.Time);
if (!string.IsNullOrWhiteSpace(ApplicationName))
{
result = result.Where(x => x.ApplicationName == ApplicationName);
}
foreach (var errorDocument in result)
{
errorEntryList.Add(new ErrorLogEntry(this, errorDocument.Id, errorDocument.Error));
}
return stats.TotalResults;
}
}
private void LoadApplicationName(IDictionary config)
{
// Set the application name as this implementation provides
// per-application isolation over a single store.
var appName = string.Empty;
if (config["applicationName"] != null)
{
appName = (string)config["applicationName"];
}
ApplicationName = appName;
}
private string GetConnectionStringName(IDictionary config)
{
var connectionString = LoadConnectionStringName(config);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new ApplicationException("Connection string is missing for the RavenDB error log.");
return connectionString;
}
private void InitDocumentStore()
{
_documentStore = new DocumentStore
{
ConnectionStringName = _connectionStringName
};
_documentStore.Initialize();
}
private string LoadConnectionStringName(IDictionary config)
{
// From ELMAH source
// First look for a connection string name that can be
// subsequently indexed into the <connectionStrings> section of
// the configuration to get the actual connection string.
var connectionStringName = (string)config["connectionStringName"];
if (!string.IsNullOrEmpty(connectionStringName))
{
var settings = ConfigurationManager.ConnectionStrings[connectionStringName];
if (settings != null)
return connectionStringName;
throw new ApplicationException(string.Format("Could not find a ConnectionString with the name '{0}'.", connectionStringName));
}
throw new ApplicationException("You must specifiy the 'connectionStringName' attribute on the <errorLog /> element.");
}
public static void ConfigureWith(IDocumentStore store)
{
if (store == null)
{
throw new ArgumentNullException("store", "You have to pass an instance of a RavenDB documentstore");
}
_externalProvidedDocumentStore = store;
}
private string RetrieveVersion()
{
var attribute = (AssemblyInformationalVersionAttribute)Assembly.GetExecutingAssembly()
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
.Single();
return attribute.InformationalVersion;
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// QueueLeftItem
/// </summary>
[DataContract(Name = "QueueLeftItem")]
public partial class QueueLeftItem : IEquatable<QueueLeftItem>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="QueueLeftItem" /> class.
/// </summary>
/// <param name="_class">_class.</param>
/// <param name="actions">actions.</param>
/// <param name="blocked">blocked.</param>
/// <param name="buildable">buildable.</param>
/// <param name="id">id.</param>
/// <param name="inQueueSince">inQueueSince.</param>
/// <param name="_params">_params.</param>
/// <param name="stuck">stuck.</param>
/// <param name="task">task.</param>
/// <param name="url">url.</param>
/// <param name="why">why.</param>
/// <param name="cancelled">cancelled.</param>
/// <param name="executable">executable.</param>
public QueueLeftItem(string _class = default(string), List<CauseAction> actions = default(List<CauseAction>), bool blocked = default(bool), bool buildable = default(bool), int id = default(int), int inQueueSince = default(int), string _params = default(string), bool stuck = default(bool), FreeStyleProject task = default(FreeStyleProject), string url = default(string), string why = default(string), bool cancelled = default(bool), FreeStyleBuild executable = default(FreeStyleBuild))
{
this.Class = _class;
this.Actions = actions;
this.Blocked = blocked;
this.Buildable = buildable;
this.Id = id;
this.InQueueSince = inQueueSince;
this.Params = _params;
this.Stuck = stuck;
this.Task = task;
this.Url = url;
this.Why = why;
this.Cancelled = cancelled;
this.Executable = executable;
}
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Actions
/// </summary>
[DataMember(Name = "actions", EmitDefaultValue = false)]
public List<CauseAction> Actions { get; set; }
/// <summary>
/// Gets or Sets Blocked
/// </summary>
[DataMember(Name = "blocked", EmitDefaultValue = true)]
public bool Blocked { get; set; }
/// <summary>
/// Gets or Sets Buildable
/// </summary>
[DataMember(Name = "buildable", EmitDefaultValue = true)]
public bool Buildable { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name = "id", EmitDefaultValue = false)]
public int Id { get; set; }
/// <summary>
/// Gets or Sets InQueueSince
/// </summary>
[DataMember(Name = "inQueueSince", EmitDefaultValue = false)]
public int InQueueSince { get; set; }
/// <summary>
/// Gets or Sets Params
/// </summary>
[DataMember(Name = "params", EmitDefaultValue = false)]
public string Params { get; set; }
/// <summary>
/// Gets or Sets Stuck
/// </summary>
[DataMember(Name = "stuck", EmitDefaultValue = true)]
public bool Stuck { get; set; }
/// <summary>
/// Gets or Sets Task
/// </summary>
[DataMember(Name = "task", EmitDefaultValue = false)]
public FreeStyleProject Task { get; set; }
/// <summary>
/// Gets or Sets Url
/// </summary>
[DataMember(Name = "url", EmitDefaultValue = false)]
public string Url { get; set; }
/// <summary>
/// Gets or Sets Why
/// </summary>
[DataMember(Name = "why", EmitDefaultValue = false)]
public string Why { get; set; }
/// <summary>
/// Gets or Sets Cancelled
/// </summary>
[DataMember(Name = "cancelled", EmitDefaultValue = true)]
public bool Cancelled { get; set; }
/// <summary>
/// Gets or Sets Executable
/// </summary>
[DataMember(Name = "executable", EmitDefaultValue = false)]
public FreeStyleBuild Executable { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class QueueLeftItem {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Actions: ").Append(Actions).Append("\n");
sb.Append(" Blocked: ").Append(Blocked).Append("\n");
sb.Append(" Buildable: ").Append(Buildable).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" InQueueSince: ").Append(InQueueSince).Append("\n");
sb.Append(" Params: ").Append(Params).Append("\n");
sb.Append(" Stuck: ").Append(Stuck).Append("\n");
sb.Append(" Task: ").Append(Task).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append(" Why: ").Append(Why).Append("\n");
sb.Append(" Cancelled: ").Append(Cancelled).Append("\n");
sb.Append(" Executable: ").Append(Executable).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as QueueLeftItem);
}
/// <summary>
/// Returns true if QueueLeftItem instances are equal
/// </summary>
/// <param name="input">Instance of QueueLeftItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(QueueLeftItem input)
{
if (input == null)
{
return false;
}
return
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.Actions == input.Actions ||
this.Actions != null &&
input.Actions != null &&
this.Actions.SequenceEqual(input.Actions)
) &&
(
this.Blocked == input.Blocked ||
this.Blocked.Equals(input.Blocked)
) &&
(
this.Buildable == input.Buildable ||
this.Buildable.Equals(input.Buildable)
) &&
(
this.Id == input.Id ||
this.Id.Equals(input.Id)
) &&
(
this.InQueueSince == input.InQueueSince ||
this.InQueueSince.Equals(input.InQueueSince)
) &&
(
this.Params == input.Params ||
(this.Params != null &&
this.Params.Equals(input.Params))
) &&
(
this.Stuck == input.Stuck ||
this.Stuck.Equals(input.Stuck)
) &&
(
this.Task == input.Task ||
(this.Task != null &&
this.Task.Equals(input.Task))
) &&
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url))
) &&
(
this.Why == input.Why ||
(this.Why != null &&
this.Why.Equals(input.Why))
) &&
(
this.Cancelled == input.Cancelled ||
this.Cancelled.Equals(input.Cancelled)
) &&
(
this.Executable == input.Executable ||
(this.Executable != null &&
this.Executable.Equals(input.Executable))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Class != null)
{
hashCode = (hashCode * 59) + this.Class.GetHashCode();
}
if (this.Actions != null)
{
hashCode = (hashCode * 59) + this.Actions.GetHashCode();
}
hashCode = (hashCode * 59) + this.Blocked.GetHashCode();
hashCode = (hashCode * 59) + this.Buildable.GetHashCode();
hashCode = (hashCode * 59) + this.Id.GetHashCode();
hashCode = (hashCode * 59) + this.InQueueSince.GetHashCode();
if (this.Params != null)
{
hashCode = (hashCode * 59) + this.Params.GetHashCode();
}
hashCode = (hashCode * 59) + this.Stuck.GetHashCode();
if (this.Task != null)
{
hashCode = (hashCode * 59) + this.Task.GetHashCode();
}
if (this.Url != null)
{
hashCode = (hashCode * 59) + this.Url.GetHashCode();
}
if (this.Why != null)
{
hashCode = (hashCode * 59) + this.Why.GetHashCode();
}
hashCode = (hashCode * 59) + this.Cancelled.GetHashCode();
if (this.Executable != null)
{
hashCode = (hashCode * 59) + this.Executable.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using Avalonia.Input;
//using Android.InputMethodServices;
using System.Collections.Generic;
using Android.Views;
namespace Avalonia.Android.Platform.Input
{
public class AndroidKeyboardDevice : KeyboardDevice, IKeyboardDevice {
private static readonly Dictionary<Keycode, Key> KeyDic = new Dictionary<Keycode, Key>
{
// { Keycode.Cancel?, Key.Cancel },
{ Keycode.Del, Key.Back },
{ Keycode.Tab, Key.Tab },
// { Keycode.Linefeed?, Key.LineFeed },
{ Keycode.Clear, Key.Clear },
{ Keycode.Enter, Key.Return },
{ Keycode.MediaPause, Key.Pause },
//{ Keycode.?, Key.CapsLock }
//{ Keycode.?, Key.HangulMode }
//{ Keycode.?, Key.JunjaMode }
//{ Keycode.?, Key.FinalMode }
//{ Keycode.?, Key.KanjiMode }
{ Keycode.Escape, Key.Escape },
//{ Keycode.?, Key.ImeConvert }
//{ Keycode.?, Key.ImeNonConvert }
//{ Keycode.?, Key.ImeAccept }
//{ Keycode.?, Key.ImeModeChange }
{ Keycode.Space, Key.Space },
{ Keycode.PageUp, Key.Prior },
{ Keycode.PageDown, Key.PageDown },
// { Keycode.end?, Key.End },
{ Keycode.Home, Key.Home },
{ Keycode.DpadLeft, Key.Left },
{ Keycode.DpadUp, Key.Up },
{ Keycode.DpadRight, Key.Right },
{ Keycode.DpadDown, Key.Down },
// { Keycode.ButtonSelect?, Key.Select },
// { Keycode.print?, Key.Print },
//{ Keycode.execute?, Key.Execute },
// { Keycode.snap, Key.Snapshot }
{ Keycode.Insert, Key.Insert },
{ Keycode.ForwardDel, Key.Delete },
//{ Keycode.help, Key.Help },
//{ Keycode.?, Key.D0 }
//{ Keycode.?, Key.D1 }
//{ Keycode.?, Key.D2 }
//{ Keycode.?, Key.D3 }
//{ Keycode.?, Key.D4 }
//{ Keycode.?, Key.D5 }
//{ Keycode.?, Key.D6 }
//{ Keycode.?, Key.D7 }
//{ Keycode.?, Key.D8 }
//{ Keycode.?, Key.D9 }
{ Keycode.A, Key.A },
{ Keycode.B, Key.B },
{ Keycode.C, Key.C },
{ Keycode.D, Key.D },
{ Keycode.E, Key.E },
{ Keycode.F, Key.F },
{ Keycode.G, Key.G },
{ Keycode.H, Key.H },
{ Keycode.I, Key.I },
{ Keycode.J, Key.J },
{ Keycode.K, Key.K },
{ Keycode.L, Key.L },
{ Keycode.M, Key.M },
{ Keycode.N, Key.N },
{ Keycode.O, Key.O },
{ Keycode.P, Key.P },
{ Keycode.Q, Key.Q },
{ Keycode.R, Key.R },
{ Keycode.S, Key.S },
{ Keycode.T, Key.T },
{ Keycode.U, Key.U },
{ Keycode.V, Key.V },
{ Keycode.W, Key.W },
{ Keycode.X, Key.X },
{ Keycode.Y, Key.Y },
{ Keycode.Z, Key.Z },
//{ Keycode.a, Key.A },
//{ Keycode.b, Key.B },
//{ Keycode.c, Key.C },
//{ Keycode.d, Key.D },
//{ Keycode.e, Key.E },
//{ Keycode.f, Key.F },
//{ Keycode.g, Key.G },
//{ Keycode.h, Key.H },
//{ Keycode.i, Key.I },
//{ Keycode.j, Key.J },
//{ Keycode.k, Key.K },
//{ Keycode.l, Key.L },
//{ Keycode.m, Key.M },
//{ Keycode.n, Key.N },
//{ Keycode.o, Key.O },
//{ Keycode.p, Key.P },
//{ Keycode.q, Key.Q },
//{ Keycode.r, Key.R },
//{ Keycode.s, Key.S },
//{ Keycode.t, Key.T },
//{ Keycode.u, Key.U },
//{ Keycode.v, Key.V },
//{ Keycode.w, Key.W },
//{ Keycode.x, Key.X },
//{ Keycode.y, Key.Y },
//{ Keycode.z, Key.Z },
//{ Keycode.?, Key.LWin }
//{ Keycode.?, Key.RWin }
//{ Keycode.?, Key.Apps }
//{ Keycode.?, Key.Sleep }
//{ Keycode.?, Key.NumPad0 }
//{ Keycode.?, Key.NumPad1 }
//{ Keycode.?, Key.NumPad2 }
//{ Keycode.?, Key.NumPad3 }
//{ Keycode.?, Key.NumPad4 }
//{ Keycode.?, Key.NumPad5 }
//{ Keycode.?, Key.NumPad6 }
//{ Keycode.?, Key.NumPad7 }
//{ Keycode.?, Key.NumPad8 }
//{ Keycode.?, Key.NumPad9 }
{ Keycode.NumpadMultiply, Key.Multiply },
{ Keycode.NumpadAdd, Key.Add },
{ Keycode.NumpadComma, Key.Separator },
{ Keycode.NumpadSubtract, Key.Subtract },
//{ Keycode.numpaddecimal?, Key.Decimal }
{ Keycode.NumpadDivide, Key.Divide },
{ Keycode.F1, Key.F1 },
{ Keycode.F2, Key.F2 },
{ Keycode.F3, Key.F3 },
{ Keycode.F4, Key.F4 },
{ Keycode.F5, Key.F5 },
{ Keycode.F6, Key.F6 },
{ Keycode.F7, Key.F7 },
{ Keycode.F8, Key.F8 },
{ Keycode.F9, Key.F9 },
{ Keycode.F10, Key.F10 },
{ Keycode.F11, Key.F11 },
{ Keycode.F12, Key.F12 },
//{ Keycode.f13, Key.F13 },
//{ Keycode.F14, Key.F14 },
//{ Keycode.L5, Key.F15 },
//{ Keycode.F16, Key.F16 },
//{ Keycode.F17, Key.F17 },
//{ Keycode.L8, Key.F18 },
//{ Keycode.L9, Key.F19 },
//{ Keycode.L10, Key.F20 },
//{ Keycode.R1, Key.F21 },
//{ Keycode.R2, Key.F22 },
//{ Keycode.F23, Key.F23 },
//{ Keycode.R4, Key.F24 },
// { Keycode.numpad, Key.NumLock }
{ Keycode.ScrollLock, Key.Scroll },
{ Keycode.ShiftLeft, Key.LeftShift },
//{ Keycode.?, Key.RightShift }
//{ Keycode.?, Key.LeftCtrl }
//{ Keycode.?, Key.RightCtrl }
//{ Keycode.?, Key.LeftAlt }
//{ Keycode.?, Key.RightAlt }
//{ Keycode.?, Key.BrowserBack }
//{ Keycode.?, Key.BrowserForward }
//{ Keycode.?, Key.BrowserRefresh }
//{ Keycode.?, Key.BrowserStop }
//{ Keycode.?, Key.BrowserSearch }
//{ Keycode.?, Key.BrowserFavorites }
//{ Keycode.?, Key.BrowserHome }
//{ Keycode.?, Key.VolumeMute }
//{ Keycode.?, Key.VolumeDown }
//{ Keycode.?, Key.VolumeUp }
//{ Keycode.?, Key.MediaNextTrack }
//{ Keycode.?, Key.MediaPreviousTrack }
//{ Keycode.?, Key.MediaStop }
//{ Keycode.?, Key.MediaPlayPause }
//{ Keycode.?, Key.LaunchMail }
//{ Keycode.?, Key.SelectMedia }
//{ Keycode.?, Key.LaunchApplication1 }
//{ Keycode.?, Key.LaunchApplication2 }
//{ Keycode.?, Key.OemSemicolon }
//{ Keycode.?, Key.OemPlus }
//{ Keycode.?, Key.OemComma }
//{ Keycode.?, Key.OemMinus }
//{ Keycode.?, Key.OemPeriod }
//{ Keycode.?, Key.Oem2 }
//{ Keycode.?, Key.OemTilde }
//{ Keycode.?, Key.AbntC1 }
//{ Keycode.?, Key.AbntC2 }
//{ Keycode.?, Key.Oem4 }
//{ Keycode.?, Key.OemPipe }
//{ Keycode.?, Key.OemCloseBrackets }
//{ Keycode.?, Key.Oem7 }
//{ Keycode.?, Key.Oem8 }
//{ Keycode.?, Key.Oem102 }
//{ Keycode.?, Key.ImeProcessed }
//{ Keycode.?, Key.System }
//{ Keycode.?, Key.OemAttn }
//{ Keycode.?, Key.OemFinish }
//{ Keycode.?, Key.DbeHiragana }
//{ Keycode.?, Key.OemAuto }
//{ Keycode.?, Key.DbeDbcsChar }
//{ Keycode.?, Key.OemBackTab }
//{ Keycode.?, Key.Attn }
//{ Keycode.?, Key.DbeEnterWordRegisterMode }
//{ Keycode.?, Key.DbeEnterImeConfigureMode }
//{ Keycode.?, Key.EraseEof }
//{ Keycode.?, Key.Play }
//{ Keycode.?, Key.Zoom }
//{ Keycode.?, Key.NoName }
//{ Keycode.?, Key.DbeEnterDialogConversionMode }
//{ Keycode.?, Key.OemClear }
//{ Keycode.?, Key.DeadCharProcessed }
};
internal static Key ConvertKey(Keycode key) {
Key result;
return KeyDic.TryGetValue(key, out result) ? result : Key.None;
}
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
namespace Nez
{
/// <summary>
/// Describes a 2D-rectangle.
/// </summary>
[DebuggerDisplay( "{DebugDisplayString,nq}" )]
public struct RectangleF : IEquatable<RectangleF>
{
static RectangleF emptyRectangle = new RectangleF();
/// <summary>
/// The x coordinate of the top-left corner of this <see cref="RectangleF"/>.
/// </summary>
public float x;
/// <summary>
/// The y coordinate of the top-left corner of this <see cref="RectangleF"/>.
/// </summary>
public float y;
/// <summary>
/// The width of this <see cref="RectangleF"/>.
/// </summary>
public float width;
/// <summary>
/// The height of this <see cref="RectangleF"/>.
/// </summary>
public float height;
#region Public Properties
/// <summary>
/// Returns a <see cref="RectangleF"/> with X=0, Y=0, Width=0, Height=0.
/// </summary>
public static RectangleF empty
{
get { return emptyRectangle; }
}
/// <summary>
/// returns a RectangleF of float.Min/Max values
/// </summary>
/// <value>The max rect.</value>
public static RectangleF maxRect { get { return new RectangleF( float.MinValue / 2, float.MinValue / 2, float.MaxValue, float.MaxValue ); } }
/// <summary>
/// Returns the x coordinate of the left edge of this <see cref="RectangleF"/>.
/// </summary>
public float left
{
get { return this.x; }
}
/// <summary>
/// Returns the x coordinate of the right edge of this <see cref="RectangleF"/>.
/// </summary>
public float right
{
get { return ( this.x + this.width ); }
}
/// <summary>
/// Returns the y coordinate of the top edge of this <see cref="RectangleF"/>.
/// </summary>
public float top
{
get { return this.y; }
}
/// <summary>
/// Returns the y coordinate of the bottom edge of this <see cref="RectangleF"/>.
/// </summary>
public float bottom
{
get { return ( this.y + this.height ); }
}
/// <summary>
/// gets the max point of the rectangle, the bottom-right corner
/// </summary>
/// <value>The max.</value>
public Vector2 max { get { return new Vector2( right, bottom ); } }
/// <summary>
/// Whether or not this <see cref="RectangleF"/> has a <see cref="Width"/> and
/// <see cref="Height"/> of 0, and a <see cref="Location"/> of (0, 0).
/// </summary>
public bool isEmpty
{
get
{
return ( ( ( ( this.width == 0 ) && ( this.height == 0 ) ) && ( this.x == 0 ) ) && ( this.y == 0 ) );
}
}
/// <summary>
/// The top-left coordinates of this <see cref="RectangleF"/>.
/// </summary>
public Vector2 location
{
get
{
return new Vector2( this.x, this.y );
}
set
{
x = value.X;
y = value.Y;
}
}
/// <summary>
/// The width-height coordinates of this <see cref="RectangleF"/>.
/// </summary>
public Vector2 size
{
get
{
return new Vector2( this.width, this.height );
}
set
{
width = value.X;
height = value.Y;
}
}
/// <summary>
/// A <see cref="Point"/> located in the center of this <see cref="RectangleF"/>.
/// </summary>
/// <remarks>
/// If <see cref="Width"/> or <see cref="Height"/> is an odd number,
/// the center point will be rounded down.
/// </remarks>
public Vector2 center
{
get { return new Vector2( this.x + ( this.width / 2 ), this.y + ( this.height / 2 ) ); }
}
#endregion
// temp Matrixes used for bounds calculation
static Matrix2D _tempMat, _transformMat;
internal string DebugDisplayString
{
get
{
return string.Concat(
this.x, " ",
this.y, " ",
this.width, " ",
this.height
);
}
}
/// <summary>
/// Creates a new instance of <see cref="RectangleF"/> struct, with the specified
/// position, width, and height.
/// </summary>
/// <param name="x">The x coordinate of the top-left corner of the created <see cref="RectangleF"/>.</param>
/// <param name="y">The y coordinate of the top-left corner of the created <see cref="RectangleF"/>.</param>
/// <param name="width">The width of the created <see cref="RectangleF"/>.</param>
/// <param name="height">The height of the created <see cref="RectangleF"/>.</param>
public RectangleF( float x, float y, float width, float height )
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/// <summary>
/// Creates a new instance of <see cref="RectangleF"/> struct, with the specified
/// location and size.
/// </summary>
/// <param name="location">The x and y coordinates of the top-left corner of the created <see cref="RectangleF"/>.</param>
/// <param name="size">The width and height of the created <see cref="RectangleF"/>.</param>
public RectangleF( Vector2 location, Vector2 size )
{
this.x = location.X;
this.y = location.Y;
this.width = size.X;
this.height = size.Y;
}
/// <summary>
/// creates a RectangleF given min/max points (top-left, bottom-right points)
/// </summary>
/// <returns>The minimum max points.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
public static RectangleF fromMinMax( Vector2 min, Vector2 max )
{
return new RectangleF( min.X, min.Y, max.X - min.X, max.Y - min.Y );
}
/// <summary>
/// creates a RectangleF given min/max points (top-left, bottom-right points)
/// </summary>
/// <returns>The minimum max points.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
public static RectangleF fromMinMax( float minX, float minY, float maxX, float maxY )
{
return new RectangleF( minX, minY, maxX - minX, maxY - minY );
}
/// <summary>
/// given the points of a polygon calculates the bounds
/// </summary>
/// <returns>The from polygon points.</returns>
/// <param name="points">Points.</param>
public static RectangleF rectEncompassingPoints( Vector2[] points )
{
// we need to find the min/max x/y values
var minX = float.PositiveInfinity;
var minY = float.PositiveInfinity;
var maxX = float.NegativeInfinity;
var maxY = float.NegativeInfinity;
for( var i = 0; i < points.Length; i++ )
{
var pt = points[i];
if( pt.X < minX )
minX = pt.X;
if( pt.X > maxX )
maxX = pt.X;
if( pt.Y < minY )
minY = pt.Y;
if( pt.Y > maxY )
maxY = pt.Y;
}
return RectangleF.fromMinMax( minX, minY, maxX, maxY );
}
#region Public Methods
/// <summary>
/// gets the position of the specified edge
/// </summary>
/// <returns>The side.</returns>
/// <param name="edge">Side.</param>
public float getSide( Edge edge )
{
switch( edge )
{
case Edge.Top:
return top;
case Edge.Bottom:
return bottom;
case Edge.Left:
return left;
case Edge.Right:
return right;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Gets whether or not the provided coordinates lie within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="x">The x coordinate of the point to check for containment.</param>
/// <param name="y">The y coordinate of the point to check for containment.</param>
/// <returns><c>true</c> if the provided coordinates lie inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool contains( int x, int y )
{
return ( ( ( ( this.x <= x ) && ( x < ( this.x + this.width ) ) ) && ( this.y <= y ) ) && ( y < ( this.y + this.height ) ) );
}
/// <summary>
/// Gets whether or not the provided coordinates lie within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="x">The x coordinate of the point to check for containment.</param>
/// <param name="y">The y coordinate of the point to check for containment.</param>
/// <returns><c>true</c> if the provided coordinates lie inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool contains( float x, float y )
{
return ( ( ( ( this.x <= x ) && ( x < ( this.x + this.width ) ) ) && ( this.y <= y ) ) && ( y < ( this.y + this.height ) ) );
}
/// <summary>
/// Gets whether or not the provided <see cref="Point"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <returns><c>true</c> if the provided <see cref="Point"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool contains( Point value )
{
return ( ( ( ( this.x <= value.X ) && ( value.X < ( this.x + this.width ) ) ) && ( this.y <= value.Y ) ) && ( value.Y < ( this.y + this.height ) ) );
}
/// <summary>
/// Gets whether or not the provided <see cref="Point"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <param name="result"><c>true</c> if the provided <see cref="Point"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise. As an output parameter.</param>
public void contains( ref Point value, out bool result )
{
result = ( ( ( ( this.x <= value.X ) && ( value.X < ( this.x + this.width ) ) ) && ( this.y <= value.Y ) ) && ( value.Y < ( this.y + this.height ) ) );
}
/// <summary>
/// Gets whether or not the provided <see cref="Vector2"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <returns><c>true</c> if the provided <see cref="Vector2"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool contains( Vector2 value )
{
return ( ( ( ( this.x <= value.X ) && ( value.X < ( this.x + this.width ) ) ) && ( this.y <= value.Y ) ) && ( value.Y < ( this.y + this.height ) ) );
}
/// <summary>
/// Gets whether or not the provided <see cref="Vector2"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The coordinates to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <param name="result"><c>true</c> if the provided <see cref="Vector2"/> lies inside this <see cref="RectangleF"/>; <c>false</c> otherwise. As an output parameter.</param>
public void contains( ref Vector2 value, out bool result )
{
result = ( ( ( ( this.x <= value.X ) && ( value.X < ( this.x + this.width ) ) ) && ( this.y <= value.Y ) ) && ( value.Y < ( this.y + this.height ) ) );
}
/// <summary>
/// Gets whether or not the provided <see cref="RectangleF"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The <see cref="RectangleF"/> to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <returns><c>true</c> if the provided <see cref="RectangleF"/>'s bounds lie entirely inside this <see cref="RectangleF"/>; <c>false</c> otherwise.</returns>
public bool contains( RectangleF value )
{
return ( ( ( ( this.x <= value.x ) && ( ( value.x + value.width ) <= ( this.x + this.width ) ) ) && ( this.y <= value.y ) ) && ( ( value.y + value.height ) <= ( this.y + this.height ) ) );
}
/// <summary>
/// Gets whether or not the provided <see cref="RectangleF"/> lies within the bounds of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="value">The <see cref="RectangleF"/> to check for inclusion in this <see cref="RectangleF"/>.</param>
/// <param name="result"><c>true</c> if the provided <see cref="RectangleF"/>'s bounds lie entirely inside this <see cref="RectangleF"/>; <c>false</c> otherwise. As an output parameter.</param>
public void contains( ref RectangleF value, out bool result )
{
result = ( ( ( ( this.x <= value.x ) && ( ( value.x + value.width ) <= ( this.x + this.width ) ) ) && ( this.y <= value.y ) ) && ( ( value.y + value.height ) <= ( this.y + this.height ) ) );
}
/// <summary>
/// Adjusts the edges of this <see cref="RectangleF"/> by specified horizontal and vertical amounts.
/// </summary>
/// <param name="horizontalAmount">Value to adjust the left and right edges.</param>
/// <param name="verticalAmount">Value to adjust the top and bottom edges.</param>
public void inflate( int horizontalAmount, int verticalAmount )
{
x -= horizontalAmount;
y -= verticalAmount;
width += horizontalAmount * 2;
height += verticalAmount * 2;
}
/// <summary>
/// Adjusts the edges of this <see cref="RectangleF"/> by specified horizontal and vertical amounts.
/// </summary>
/// <param name="horizontalAmount">Value to adjust the left and right edges.</param>
/// <param name="verticalAmount">Value to adjust the top and bottom edges.</param>
public void inflate( float horizontalAmount, float verticalAmount )
{
x -= horizontalAmount;
y -= verticalAmount;
width += horizontalAmount * 2;
height += verticalAmount * 2;
}
/// <summary>
/// Gets whether or not the other <see cref="RectangleF"/> intersects with this rectangle.
/// </summary>
/// <param name="value">The other rectangle for testing.</param>
/// <returns><c>true</c> if other <see cref="RectangleF"/> intersects with this rectangle; <c>false</c> otherwise.</returns>
public bool intersects( RectangleF value )
{
return value.left < right &&
left < value.right &&
value.top < bottom &&
top < value.bottom;
}
/// <summary>
/// Gets whether or not the other <see cref="RectangleF"/> intersects with this rectangle.
/// </summary>
/// <param name="value">The other rectangle for testing.</param>
/// <param name="result"><c>true</c> if other <see cref="RectangleF"/> intersects with this rectangle; <c>false</c> otherwise. As an output parameter.</param>
public void intersects( ref RectangleF value, out bool result )
{
result = value.left < right &&
left < value.right &&
value.top < bottom &&
top < value.bottom;
}
/// <summary>
/// returns true if other intersects rect
/// </summary>
/// <param name="other">other.</param>
public bool intersects( ref RectangleF other )
{
bool result;
intersects( ref other, out result );
return result;
}
public bool rayIntersects( ref Ray2D ray, out float distance )
{
distance = 0f;
var maxValue = float.MaxValue;
if( Math.Abs( ray.direction.X ) < 1E-06f )
{
if( ( ray.start.X < x ) || ( ray.start.X > x + width ) )
return false;
}
else
{
var num11 = 1f / ray.direction.X;
var num8 = ( x - ray.start.X ) * num11;
var num7 = ( x + width - ray.start.X ) * num11;
if( num8 > num7 )
{
var num14 = num8;
num8 = num7;
num7 = num14;
}
distance = MathHelper.Max( num8, distance );
maxValue = MathHelper.Min( num7, maxValue );
if( distance > maxValue )
return false;
}
if( Math.Abs( ray.direction.Y ) < 1E-06f )
{
if( ( ray.start.Y < y ) || ( ray.start.Y > y + height ) )
{
return false;
}
}
else
{
var num10 = 1f / ray.direction.Y;
var num6 = ( y - ray.start.Y ) * num10;
var num5 = ( y + height - ray.start.Y ) * num10;
if( num6 > num5 )
{
var num13 = num6;
num6 = num5;
num5 = num13;
}
distance = MathHelper.Max( num6, distance );
maxValue = MathHelper.Min( num5, maxValue );
if( distance > maxValue )
return false;
}
return true;
}
public float? rayIntersects( Ray ray )
{
var num = 0f;
var maxValue = float.MaxValue;
if( Math.Abs( ray.Direction.X ) < 1E-06f )
{
if( ( ray.Position.X < left ) || ( ray.Position.X > right ) )
return null;
}
else
{
float num11 = 1f / ray.Direction.X;
float num8 = ( left - ray.Position.X ) * num11;
float num7 = ( right - ray.Position.X ) * num11;
if( num8 > num7 )
{
float num14 = num8;
num8 = num7;
num7 = num14;
}
num = MathHelper.Max( num8, num );
maxValue = MathHelper.Min( num7, maxValue );
if( num > maxValue )
return null;
}
if( Math.Abs( ray.Direction.Y ) < 1E-06f )
{
if( ( ray.Position.Y < top ) || ( ray.Position.Y > bottom ) )
return null;
}
else
{
float num10 = 1f / ray.Direction.Y;
float num6 = ( top - ray.Position.Y ) * num10;
float num5 = ( bottom - ray.Position.Y ) * num10;
if( num6 > num5 )
{
float num13 = num6;
num6 = num5;
num5 = num13;
}
num = MathHelper.Max( num6, num );
maxValue = MathHelper.Min( num5, maxValue );
if( num > maxValue )
return null;
}
return new float?( num );
}
public Vector2 getClosestPointOnBoundsToOrigin()
{
var max = this.max;
var minDist = Math.Abs( location.X );
var boundsPoint = new Vector2( location.X, 0 );
if( Math.Abs( max.X ) < minDist )
{
minDist = Math.Abs( max.X );
boundsPoint.X = max.X;
boundsPoint.Y = 0f;
}
if( Math.Abs( max.Y ) < minDist )
{
minDist = Math.Abs( max.Y );
boundsPoint.X = 0f;
boundsPoint.Y = max.Y;
}
if( Math.Abs( location.Y ) < minDist )
{
minDist = Math.Abs( location.Y );
boundsPoint.X = 0;
boundsPoint.Y = location.Y;
}
return boundsPoint;
}
/// <summary>
/// returns the closest point that is in or on the RectangleF to the given point
/// </summary>
/// <returns>The closest point on rectangle to point.</returns>
/// <param name="point">Point.</param>
public Vector2 getClosestPointOnRectangleFToPoint( Vector2 point )
{
// for each axis, if the point is outside the box clamp it to the box else leave it alone
var res = new Vector2();
res.X = MathHelper.Clamp( point.X, left, right );
res.Y = MathHelper.Clamp( point.Y, top, bottom );
return res;
}
/// <summary>
/// gets the closest point that is on the rectangle border to the given point
/// </summary>
/// <returns>The closest point on rectangle border to point.</returns>
/// <param name="point">Point.</param>
public Vector2 getClosestPointOnRectangleBorderToPoint( Vector2 point, out Vector2 edgeNormal )
{
edgeNormal = Vector2.Zero;
// for each axis, if the point is outside the box clamp it to the box else leave it alone
var res = new Vector2();
res.X = MathHelper.Clamp( point.X, left, right );
res.Y = MathHelper.Clamp( point.Y, top, bottom );
// if point is inside the rectangle we need to push res to the border since it will be inside the rect
if( contains( res ) )
{
var dl = res.X - left;
var dr = right - res.X;
var dt = res.Y - top;
var db = bottom - res.Y;
var min = Mathf.minOf( dl, dr, dt, db );
if( min == dt )
{
res.Y = top;
edgeNormal.Y = -1;
}
else if( min == db )
{
res.Y = bottom;
edgeNormal.Y = 1;
}
else if( min == dl )
{
res.X = left;
edgeNormal.X = -1;
}
else
{
res.X = right;
edgeNormal.X = 1;
}
}
else
{
if( res.X == left )
edgeNormal.X = -1;
if( res.X == right )
edgeNormal.X = 1;
if( res.Y == top )
edgeNormal.Y = -1;
if( res.Y == bottom )
edgeNormal.Y = 1;
}
return res;
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that contains overlapping region of two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <returns>Overlapping region of the two rectangles.</returns>
public static RectangleF intersect( RectangleF value1, RectangleF value2 )
{
RectangleF rectangle;
intersect( ref value1, ref value2, out rectangle );
return rectangle;
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that contains overlapping region of two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <param name="result">Overlapping region of the two rectangles as an output parameter.</param>
public static void intersect( ref RectangleF value1, ref RectangleF value2, out RectangleF result )
{
if( value1.intersects( value2 ) )
{
var right_side = Math.Min( value1.x + value1.width, value2.x + value2.width );
var left_side = Math.Max( value1.x, value2.x );
var top_side = Math.Max( value1.y, value2.y );
var bottom_side = Math.Min( value1.y + value1.height, value2.y + value2.height );
result = new RectangleF( left_side, top_side, right_side - left_side, bottom_side - top_side );
}
else
{
result = new RectangleF( 0, 0, 0, 0 );
}
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="offsetX">The x coordinate to add to this <see cref="RectangleF"/>.</param>
/// <param name="offsetY">The y coordinate to add to this <see cref="RectangleF"/>.</param>
public void offset( int offsetX, int offsetY )
{
x += offsetX;
y += offsetY;
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="offsetX">The x coordinate to add to this <see cref="RectangleF"/>.</param>
/// <param name="offsetY">The y coordinate to add to this <see cref="RectangleF"/>.</param>
public void offset( float offsetX, float offsetY )
{
x += offsetX;
y += offsetY;
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="amount">The x and y components to add to this <see cref="RectangleF"/>.</param>
public void offset( Point amount )
{
x += amount.X;
y += amount.Y;
}
/// <summary>
/// Changes the <see cref="Location"/> of this <see cref="RectangleF"/>.
/// </summary>
/// <param name="amount">The x and y components to add to this <see cref="RectangleF"/>.</param>
public void offset( Vector2 amount )
{
x += amount.X;
y += amount.Y;
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that completely contains two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <returns>The union of the two rectangles.</returns>
public static RectangleF union( RectangleF value1, RectangleF value2 )
{
var x = Math.Min( value1.x, value2.x );
var y = Math.Min( value1.y, value2.y );
return new RectangleF( x, y,
Math.Max( value1.right, value2.right ) - x,
Math.Max( value1.bottom, value2.bottom ) - y );
}
/// <summary>
/// Creates a new <see cref="RectangleF"/> that completely contains two other rectangles.
/// </summary>
/// <param name="value1">The first <see cref="RectangleF"/>.</param>
/// <param name="value2">The second <see cref="RectangleF"/>.</param>
/// <param name="result">The union of the two rectangles as an output parameter.</param>
public static void union( ref RectangleF value1, ref RectangleF value2, out RectangleF result )
{
result.x = Math.Min( value1.x, value2.x );
result.y = Math.Min( value1.y, value2.y );
result.width = Math.Max( value1.right, value2.right ) - result.x;
result.height = Math.Max( value1.bottom, value2.bottom ) - result.y;
}
public void calculateBounds( Vector2 parentPosition, Vector2 position, Vector2 origin, Vector2 scale, float rotation, float width, float height )
{
if( rotation == 0f )
{
x = parentPosition.X + position.X - origin.X * scale.X;
y = parentPosition.Y + position.Y - origin.Y * scale.Y;
this.width = width * scale.X;
this.height = height * scale.Y;
}
else
{
// special care for rotated bounds. we need to find our absolute min/max values and create the bounds from that
var worldPosX = parentPosition.X + position.X;
var worldPosY = parentPosition.Y + position.Y;
// set the reference point to world reference taking origin into account
Matrix2D.createTranslation( -worldPosX - origin.X, -worldPosY - origin.Y, out _transformMat );
Matrix2D.createScale( scale.X, scale.Y, out _tempMat ); // scale ->
Matrix2D.multiply( ref _transformMat, ref _tempMat, out _transformMat );
Matrix2D.createRotation( rotation, out _tempMat ); // rotate ->
Matrix2D.multiply( ref _transformMat, ref _tempMat, out _transformMat );
Matrix2D.createTranslation( worldPosX, worldPosY, out _tempMat ); // translate back
Matrix2D.multiply( ref _transformMat, ref _tempMat, out _transformMat );
// TODO: this is a bit silly. we can just leave the worldPos translation in the Matrix and avoid this
// get all four corners in world space
var topLeft = new Vector2( worldPosX, worldPosY );
var topRight = new Vector2( worldPosX + width, worldPosY );
var bottomLeft = new Vector2( worldPosX, worldPosY + height );
var bottomRight = new Vector2( worldPosX + width, worldPosY + height );
// transform the corners into our work space
Vector2Ext.transform( ref topLeft, ref _transformMat, out topLeft );
Vector2Ext.transform( ref topRight, ref _transformMat, out topRight );
Vector2Ext.transform( ref bottomLeft, ref _transformMat, out bottomLeft );
Vector2Ext.transform( ref bottomRight, ref _transformMat, out bottomRight );
// find the min and max values so we can concoct our bounding box
var minX = Mathf.minOf( topLeft.X, bottomRight.X, topRight.X, bottomLeft.X );
var maxX = Mathf.maxOf( topLeft.X, bottomRight.X, topRight.X, bottomLeft.X );
var minY = Mathf.minOf( topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y );
var maxY = Mathf.maxOf( topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y );
location = new Vector2( minX, minY );
this.width = maxX - minX;
this.height = maxY - minY;
}
}
/// <summary>
/// returns a RectangleF that spans the current rect and the provided delta positions
/// </summary>
/// <returns>The swept broadphase box.</returns>
/// <param name="velocityX">Velocity x.</param>
/// <param name="velocityY">Velocity y.</param>
public RectangleF getSweptBroadphaseBounds( float deltaX, float deltaY )
{
var broadphasebox = RectangleF.empty;
broadphasebox.x = deltaX > 0 ? x : x + deltaX;
broadphasebox.y = deltaY > 0 ? y : y + deltaY;
broadphasebox.width = deltaX > 0 ? deltaX + width : width - deltaX;
broadphasebox.height = deltaY > 0 ? deltaY + height : height - deltaY;
return broadphasebox;
}
/// <summary>
/// returns true if the boxes are colliding
/// moveX and moveY will return the movement that b1 must move to avoid the collision
/// </summary>
/// <param name="other">Other.</param>
/// <param name="moveX">Move x.</param>
/// <param name="moveY">Move y.</param>
public bool collisionCheck( ref RectangleF other, out float moveX, out float moveY )
{
moveX = moveY = 0.0f;
var l = other.x - ( x + width );
var r = ( other.x + other.width ) - x;
var t = other.y - ( y + height );
var b = ( other.y + other.height ) - y;
// check that there was a collision
if( l > 0 || r < 0 || t > 0 || b < 0 )
return false;
// find the offset of both sides
moveX = Math.Abs( l ) < r ? l : r;
moveY = Math.Abs( t ) < b ? t : b;
// only use whichever offset is the smallest
if( Math.Abs( moveX ) < Math.Abs( moveY ) )
moveY = 0.0f;
else
moveX = 0.0f;
return true;
}
/// <summary>
/// Calculates the signed depth of intersection between two rectangles.
/// </summary>
/// <returns>
/// The amount of overlap between two intersecting rectangles. These depth values can be negative depending on which sides the rectangles
/// intersect. This allows callers to determine the correct direction to push objects in order to resolve collisions.
/// If the rectangles are not intersecting, Vector2.Zero is returned.
/// </returns>
public static Vector2 getIntersectionDepth( ref RectangleF rectA, ref RectangleF rectB )
{
// calculate half sizes
var halfWidthA = rectA.width / 2.0f;
var halfHeightA = rectA.height / 2.0f;
var halfWidthB = rectB.width / 2.0f;
var halfHeightB = rectB.height / 2.0f;
// calculate centers
var centerA = new Vector2( rectA.left + halfWidthA, rectA.top + halfHeightA );
var centerB = new Vector2( rectB.left + halfWidthB, rectB.top + halfHeightB );
// calculate current and minimum-non-intersecting distances between centers
var distanceX = centerA.X - centerB.X;
var distanceY = centerA.Y - centerB.Y;
var minDistanceX = halfWidthA + halfWidthB;
var minDistanceY = halfHeightA + halfHeightB;
// if we are not intersecting at all, return (0, 0)
if( Math.Abs( distanceX ) >= minDistanceX || Math.Abs( distanceY ) >= minDistanceY )
return Vector2.Zero;
// calculate and return intersection depths
var depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
var depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
return new Vector2( depthX, depthY );
}
/// <summary>
/// Compares whether current instance is equal to specified <see cref="Object"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public override bool Equals( object obj )
{
return ( obj is RectangleF ) && this == ( (RectangleF)obj );
}
/// <summary>
/// Compares whether current instance is equal to specified <see cref="RectangleF"/>.
/// </summary>
/// <param name="other">The <see cref="RectangleF"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public bool Equals( RectangleF other )
{
return this == other;
}
/// <summary>
/// Gets the hash code of this <see cref="RectangleF"/>.
/// </summary>
/// <returns>Hash code of this <see cref="RectangleF"/>.</returns>
public override int GetHashCode()
{
return ( (int)x ^ (int)y ^ (int)width ^ (int)height );
}
/// <summary>
/// Returns a <see cref="String"/> representation of this <see cref="RectangleF"/> in the format:
/// {X:[<see cref="X"/>] Y:[<see cref="Y"/>] Width:[<see cref="Width"/>] Height:[<see cref="Height"/>]}
/// </summary>
/// <returns><see cref="String"/> representation of this <see cref="RectangleF"/>.</returns>
public override string ToString()
{
return string.Format( "X:{0}, Y:{1}, Width: {2}, Height: {3}", x, y, width, height );
}
#endregion
#region Operators
/// <summary>
/// Compares whether two <see cref="RectangleF"/> instances are equal.
/// </summary>
/// <param name="a"><see cref="RectangleF"/> instance on the left of the equal sign.</param>
/// <param name="b"><see cref="RectangleF"/> instance on the right of the equal sign.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public static bool operator ==( RectangleF a, RectangleF b )
{
return ( ( a.x == b.x ) && ( a.y == b.y ) && ( a.width == b.width ) && ( a.height == b.height ) );
}
/// <summary>
/// Compares whether two <see cref="RectangleF"/> instances are not equal.
/// </summary>
/// <param name="a"><see cref="RectangleF"/> instance on the left of the not equal sign.</param>
/// <param name="b"><see cref="RectangleF"/> instance on the right of the not equal sign.</param>
/// <returns><c>true</c> if the instances are not equal; <c>false</c> otherwise.</returns>
public static bool operator !=( RectangleF a, RectangleF b )
{
return !( a == b );
}
public static implicit operator Rectangle( RectangleF self )
{
return RectangleExt.fromFloats( self.x, self.y, self.width, self.height );
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Lucene.Net.Support;
using NUnit.Framework;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Store;
using StringHelper = Lucene.Net.Util.StringHelper;
using TermQuery = Lucene.Net.Search.TermQuery;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
namespace Lucene.Net.Index
{
[TestFixture]
public class TestStressIndexing2:LuceneTestCase
{
internal class AnonymousClassComparator : System.Collections.IComparer
{
public virtual int Compare(System.Object o1, System.Object o2)
{
return String.CompareOrdinal(((IFieldable) o1).Name, ((IFieldable) o2).Name);
}
}
internal static int maxFields = 4;
internal static int bigFieldSize = 10;
internal static bool sameFieldOrder = false;
internal static int mergeFactor = 3;
internal static int maxBufferedDocs = 3;
new internal static int seed = 0;
internal System.Random r;
public class MockIndexWriter:IndexWriter
{
private void InitBlock(TestStressIndexing2 enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestStressIndexing2 enclosingInstance;
public TestStressIndexing2 Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public MockIndexWriter(TestStressIndexing2 enclosingInstance, Directory dir, Analyzer a, bool create, IndexWriter.MaxFieldLength mfl):base(dir, a, create, mfl)
{
InitBlock(enclosingInstance);
}
public /*internal*/ override bool TestPoint(System.String name)
{
// if (name.equals("startCommit")) {
if (Enclosing_Instance.r.Next(4) == 2)
System.Threading.Thread.Sleep(0);
return true;
}
}
#if GALLIO
[Ignore]
// TODO: figure out why this fails in gallio in release mode
#endif
[Test]
public virtual void TestRandomIWReader()
{
this.r = NewRandom();
Directory dir = new MockRAMDirectory();
// TODO: verify equals using IW.getReader
DocsAndWriter dw = IndexRandomIWReader(10, 100, 100, dir);
IndexReader r = dw.writer.GetReader();
dw.writer.Commit();
VerifyEquals(r, dir, "id");
r.Close();
dw.writer.Close();
dir.Close();
}
[Test]
public virtual void TestRandom()
{
r = NewRandom();
Directory dir1 = new MockRAMDirectory();
// dir1 = FSDirectory.open("foofoofoo");
Directory dir2 = new MockRAMDirectory();
// mergeFactor=2; maxBufferedDocs=2; Map docs = indexRandom(1, 3, 2, dir1);
System.Collections.IDictionary docs = IndexRandom(10, 100, 100, dir1);
IndexSerial(docs, dir2);
// verifying verify
// verifyEquals(dir1, dir1, "id");
// verifyEquals(dir2, dir2, "id");
VerifyEquals(dir1, dir2, "id");
}
[Test]
public virtual void TestMultiConfig()
{
// test lots of smaller different params together
r = NewRandom();
for (int i = 0; i < 100; i++)
{
// increase iterations for better testing
sameFieldOrder = r.NextDouble() > 0.5;
mergeFactor = r.Next(3) + 2;
maxBufferedDocs = r.Next(3) + 2;
seed++;
int nThreads = r.Next(5) + 1;
int iter = r.Next(10) + 1;
int range = r.Next(20) + 1;
Directory dir1 = new MockRAMDirectory();
Directory dir2 = new MockRAMDirectory();
System.Collections.IDictionary docs = IndexRandom(nThreads, iter, range, dir1);
IndexSerial(docs, dir2);
VerifyEquals(dir1, dir2, "id");
}
}
internal static Term idTerm = new Term("id", "");
internal IndexingThread[] threads;
internal static System.Collections.IComparer fieldNameComparator;
// This test avoids using any extra synchronization in the multiple
// indexing threads to test that IndexWriter does correctly synchronize
// everything.
public class DocsAndWriter
{
internal System.Collections.IDictionary docs;
internal IndexWriter writer;
}
public virtual DocsAndWriter IndexRandomIWReader(int nThreads, int iterations, int range, Directory dir)
{
System.Collections.Hashtable docs = new System.Collections.Hashtable();
IndexWriter w = new MockIndexWriter(this, dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED);
w.UseCompoundFile = false;
/*
w.setMaxMergeDocs(Integer.MAX_VALUE);
w.setMaxFieldLength(10000);
w.setRAMBufferSizeMB(1);
w.setMergeFactor(10);
***/
// force many merges
w.MergeFactor = mergeFactor;
w.SetRAMBufferSizeMB(.1);
w.SetMaxBufferedDocs(maxBufferedDocs);
threads = new IndexingThread[nThreads];
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = new IndexingThread();
th.w = w;
th.base_Renamed = 1000000 * i;
th.range = range;
th.iterations = iterations;
threads[i] = th;
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Start();
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
// w.optimize();
//w.close();
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = threads[i];
lock (th)
{
CollectionsHelper.AddAllIfNotContains(docs, th.docs);
}
}
_TestUtil.CheckIndex(dir);
DocsAndWriter dw = new DocsAndWriter();
dw.docs = docs;
dw.writer = w;
return dw;
}
public virtual System.Collections.IDictionary IndexRandom(int nThreads, int iterations, int range, Directory dir)
{
System.Collections.IDictionary docs = new System.Collections.Hashtable();
for (int iter = 0; iter < 3; iter++)
{
IndexWriter w = new MockIndexWriter(this, dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED);
w.UseCompoundFile = false;
// force many merges
w.MergeFactor = mergeFactor;
w.SetRAMBufferSizeMB(.1);
w.SetMaxBufferedDocs(maxBufferedDocs);
threads = new IndexingThread[nThreads];
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = new IndexingThread();
th.w = w;
th.base_Renamed = 1000000 * i;
th.range = range;
th.iterations = iterations;
threads[i] = th;
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Start();
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
// w.optimize();
w.Close();
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = threads[i];
lock (th)
{
System.Collections.IEnumerator e = th.docs.Keys.GetEnumerator();
while (e.MoveNext())
{
docs[e.Current] = th.docs[e.Current];
}
}
}
}
_TestUtil.CheckIndex(dir);
return docs;
}
public static void IndexSerial(System.Collections.IDictionary docs, Directory dir)
{
IndexWriter w = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
// index all docs in a single thread
System.Collections.IEnumerator iter = docs.Values.GetEnumerator();
while (iter.MoveNext())
{
Document d = (Document) iter.Current;
var fields = new List<IFieldable>();
fields.AddRange(d.GetFields());
// put fields in same order each time
//{{Lucene.Net-2.9.1}} No, don't change the order of the fields
//SupportClass.CollectionsHelper.Sort(fields, fieldNameComparator);
Document d1 = new Document();
d1.Boost = d.Boost;
for (int i = 0; i < fields.Count; i++)
{
d1.Add((IFieldable) fields[i]);
}
w.AddDocument(d1);
// System.out.println("indexing "+d1);
}
w.Close();
}
public static void VerifyEquals(IndexReader r1, Directory dir2, System.String idField)
{
IndexReader r2 = IndexReader.Open(dir2, true);
VerifyEquals(r1, r2, idField);
r2.Close();
}
public static void VerifyEquals(Directory dir1, Directory dir2, System.String idField)
{
IndexReader r1 = IndexReader.Open(dir1, true);
IndexReader r2 = IndexReader.Open(dir2, true);
VerifyEquals(r1, r2, idField);
r1.Close();
r2.Close();
}
public static void VerifyEquals(IndexReader r1, IndexReader r2, System.String idField)
{
Assert.AreEqual(r1.NumDocs(), r2.NumDocs());
bool hasDeletes = !(r1.MaxDoc == r2.MaxDoc && r1.NumDocs() == r1.MaxDoc);
int[] r2r1 = new int[r2.MaxDoc]; // r2 id to r1 id mapping
TermDocs termDocs1 = r1.TermDocs();
TermDocs termDocs2 = r2.TermDocs();
// create mapping from id2 space to id2 based on idField
idField = StringHelper.Intern(idField);
TermEnum termEnum = r1.Terms(new Term(idField, ""));
do
{
Term term = termEnum.Term;
if (term == null || (System.Object) term.Field != (System.Object) idField)
break;
termDocs1.Seek(termEnum);
if (!termDocs1.Next())
{
// This doc is deleted and wasn't replaced
termDocs2.Seek(termEnum);
Assert.IsFalse(termDocs2.Next());
continue;
}
int id1 = termDocs1.Doc;
Assert.IsFalse(termDocs1.Next());
termDocs2.Seek(termEnum);
Assert.IsTrue(termDocs2.Next());
int id2 = termDocs2.Doc;
Assert.IsFalse(termDocs2.Next());
r2r1[id2] = id1;
// verify stored fields are equivalent
try
{
VerifyEquals(r1.Document(id1), r2.Document(id2));
}
catch (System.Exception t)
{
System.Console.Out.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2 + " term=" + term);
System.Console.Out.WriteLine(" d1=" + r1.Document(id1));
System.Console.Out.WriteLine(" d2=" + r2.Document(id2));
throw t;
}
try
{
// verify term vectors are equivalent
VerifyEquals(r1.GetTermFreqVectors(id1), r2.GetTermFreqVectors(id2));
}
catch (System.Exception e)
{
System.Console.Out.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2);
ITermFreqVector[] tv1 = r1.GetTermFreqVectors(id1);
System.Console.Out.WriteLine(" d1=" + tv1);
if (tv1 != null)
for (int i = 0; i < tv1.Length; i++)
{
System.Console.Out.WriteLine(" " + i + ": " + tv1[i]);
}
ITermFreqVector[] tv2 = r2.GetTermFreqVectors(id2);
System.Console.Out.WriteLine(" d2=" + tv2);
if (tv2 != null)
for (int i = 0; i < tv2.Length; i++)
{
System.Console.Out.WriteLine(" " + i + ": " + tv2[i]);
}
throw e;
}
}
while (termEnum.Next());
termEnum.Close();
// Verify postings
TermEnum termEnum1 = r1.Terms(new Term("", ""));
TermEnum termEnum2 = r2.Terms(new Term("", ""));
// pack both doc and freq into single element for easy sorting
long[] info1 = new long[r1.NumDocs()];
long[] info2 = new long[r2.NumDocs()];
for (; ; )
{
Term term1, term2;
// iterate until we get some docs
int len1;
for (; ; )
{
len1 = 0;
term1 = termEnum1.Term;
if (term1 == null)
break;
termDocs1.Seek(termEnum1);
while (termDocs1.Next())
{
int d1 = termDocs1.Doc;
int f1 = termDocs1.Freq;
info1[len1] = (((long) d1) << 32) | f1;
len1++;
}
if (len1 > 0)
break;
if (!termEnum1.Next())
break;
}
// iterate until we get some docs
int len2;
for (; ; )
{
len2 = 0;
term2 = termEnum2.Term;
if (term2 == null)
break;
termDocs2.Seek(termEnum2);
while (termDocs2.Next())
{
int d2 = termDocs2.Doc;
int f2 = termDocs2.Freq;
info2[len2] = (((long) r2r1[d2]) << 32) | f2;
len2++;
}
if (len2 > 0)
break;
if (!termEnum2.Next())
break;
}
if (!hasDeletes)
Assert.AreEqual(termEnum1.DocFreq(), termEnum2.DocFreq());
Assert.AreEqual(len1, len2);
if (len1 == 0)
break; // no more terms
Assert.AreEqual(term1, term2);
// sort info2 to get it into ascending docid
System.Array.Sort(info2, 0, len2 - 0);
// now compare
for (int i = 0; i < len1; i++)
{
Assert.AreEqual(info1[i], info2[i]);
}
termEnum1.Next();
termEnum2.Next();
}
}
public static void VerifyEquals(Document d1, Document d2)
{
var ff1 = d1.GetFields().OrderBy(x => x.Name).ToList();
var ff2 = d2.GetFields().OrderBy(x => x.Name).ToList();
if (ff1.Count != ff2.Count)
{
System.Console.Out.WriteLine("[" + String.Join(",", ff1.Select(x => x.ToString()).ToArray()) + "]");
System.Console.Out.WriteLine("[" + String.Join(",", ff2.Select(x => x.ToString()).ToArray()) + "]");
Assert.AreEqual(ff1.Count, ff2.Count);
}
for (int i = 0; i < ff1.Count; i++)
{
IFieldable f1 = (IFieldable) ff1[i];
IFieldable f2 = (IFieldable) ff2[i];
if (f1.IsBinary)
{
System.Diagnostics.Debug.Assert(f2.IsBinary);
//TODO
}
else
{
System.String s1 = f1.StringValue;
System.String s2 = f2.StringValue;
if (!s1.Equals(s2))
{
// print out whole doc on error
System.Console.Out.WriteLine("[" + String.Join(",", ff1.Select(x => x.ToString()).ToArray()) + "]");
System.Console.Out.WriteLine("[" + String.Join(",", ff2.Select(x => x.ToString()).ToArray()) + "]");
Assert.AreEqual(s1, s2);
}
}
}
}
public static void VerifyEquals(ITermFreqVector[] d1, ITermFreqVector[] d2)
{
if (d1 == null)
{
Assert.IsTrue(d2 == null);
return ;
}
Assert.IsTrue(d2 != null);
Assert.AreEqual(d1.Length, d2.Length);
for (int i = 0; i < d1.Length; i++)
{
ITermFreqVector v1 = d1[i];
ITermFreqVector v2 = d2[i];
if (v1 == null || v2 == null)
{
System.Console.Out.WriteLine("v1=" + v1 + " v2=" + v2 + " i=" + i + " of " + d1.Length);
}
Assert.AreEqual(v1.Size, v2.Size);
int numTerms = v1.Size;
System.String[] terms1 = v1.GetTerms();
System.String[] terms2 = v2.GetTerms();
int[] freq1 = v1.GetTermFrequencies();
int[] freq2 = v2.GetTermFrequencies();
for (int j = 0; j < numTerms; j++)
{
if (!terms1[j].Equals(terms2[j]))
Assert.AreEqual(terms1[j], terms2[j]);
Assert.AreEqual(freq1[j], freq2[j]);
}
if (v1 is TermPositionVector)
{
Assert.IsTrue(v2 is TermPositionVector);
TermPositionVector tpv1 = (TermPositionVector) v1;
TermPositionVector tpv2 = (TermPositionVector) v2;
for (int j = 0; j < numTerms; j++)
{
int[] pos1 = tpv1.GetTermPositions(j);
int[] pos2 = tpv2.GetTermPositions(j);
Assert.AreEqual(pos1.Length, pos2.Length);
TermVectorOffsetInfo[] offsets1 = tpv1.GetOffsets(j);
TermVectorOffsetInfo[] offsets2 = tpv2.GetOffsets(j);
if (offsets1 == null)
Assert.IsTrue(offsets2 == null);
else
Assert.IsTrue(offsets2 != null);
for (int k = 0; k < pos1.Length; k++)
{
Assert.AreEqual(pos1[k], pos2[k]);
if (offsets1 != null)
{
Assert.AreEqual(offsets1[k].StartOffset, offsets2[k].StartOffset);
Assert.AreEqual(offsets1[k].EndOffset, offsets2[k].EndOffset);
}
}
}
}
}
}
internal class IndexingThread:ThreadClass
{
internal IndexWriter w;
internal int base_Renamed;
internal int range;
internal int iterations;
internal System.Collections.IDictionary docs = new System.Collections.Hashtable(); // Map<String,Document>
internal System.Random r;
public virtual int NextInt(int lim)
{
return r.Next(lim);
}
// start is inclusive and end is exclusive
public virtual int NextInt(int start, int end)
{
return start + r.Next(end - start);
}
internal char[] buffer = new char[100];
private int AddUTF8Token(int start)
{
int end = start + NextInt(20);
if (buffer.Length < 1 + end)
{
char[] newBuffer = new char[(int) ((1 + end) * 1.25)];
Array.Copy(buffer, 0, newBuffer, 0, buffer.Length);
buffer = newBuffer;
}
for (int i = start; i < end; i++)
{
int t = NextInt(6);
if (0 == t && i < end - 1)
{
// Make a surrogate pair
// High surrogate
buffer[i++] = (char) NextInt(0xd800, 0xdc00);
// Low surrogate
buffer[i] = (char) NextInt(0xdc00, 0xe000);
}
else if (t <= 1)
buffer[i] = (char) NextInt(0x80);
else if (2 == t)
buffer[i] = (char) NextInt(0x80, 0x800);
else if (3 == t)
buffer[i] = (char) NextInt(0x800, 0xd800);
else if (4 == t)
buffer[i] = (char) NextInt(0xe000, 0xffff);
else if (5 == t)
{
// Illegal unpaired surrogate
if (r.NextDouble() > 0.5)
buffer[i] = (char) NextInt(0xd800, 0xdc00);
else
buffer[i] = (char) NextInt(0xdc00, 0xe000);
}
}
buffer[end] = ' ';
return 1 + end;
}
public virtual System.String GetString(int nTokens)
{
nTokens = nTokens != 0?nTokens:r.Next(4) + 1;
// Half the time make a random UTF8 string
if (r.NextDouble() > 0.5)
return GetUTF8String(nTokens);
// avoid StringBuffer because it adds extra synchronization.
char[] arr = new char[nTokens * 2];
for (int i = 0; i < nTokens; i++)
{
arr[i * 2] = (char) ('A' + r.Next(10));
arr[i * 2 + 1] = ' ';
}
return new System.String(arr);
}
public virtual System.String GetUTF8String(int nTokens)
{
int upto = 0;
CollectionsHelper.Fill(buffer, (char) 0);
for (int i = 0; i < nTokens; i++)
upto = AddUTF8Token(upto);
return new System.String(buffer, 0, upto);
}
public virtual System.String GetIdString()
{
return System.Convert.ToString(base_Renamed + NextInt(range));
}
public virtual void IndexDoc()
{
Document d = new Document();
System.Collections.ArrayList fields = new System.Collections.ArrayList();
System.String idString = GetIdString();
Field idField = new Field(Lucene.Net.Index.TestStressIndexing2.idTerm.Field, idString, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS);
fields.Add(idField);
int nFields = NextInt(Lucene.Net.Index.TestStressIndexing2.maxFields);
for (int i = 0; i < nFields; i++)
{
Field.TermVector tvVal = Field.TermVector.NO;
switch (NextInt(4))
{
case 0:
tvVal = Field.TermVector.NO;
break;
case 1:
tvVal = Field.TermVector.YES;
break;
case 2:
tvVal = Field.TermVector.WITH_POSITIONS;
break;
case 3:
tvVal = Field.TermVector.WITH_POSITIONS_OFFSETS;
break;
}
switch (NextInt(4))
{
case 0:
fields.Add(new Field("f" + NextInt(100), GetString(1), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS, tvVal));
break;
case 1:
fields.Add(new Field("f" + NextInt(100), GetString(0), Field.Store.NO, Field.Index.ANALYZED, tvVal));
break;
case 2:
fields.Add(new Field("f" + NextInt(100), GetString(0), Field.Store.YES, Field.Index.NO, Field.TermVector.NO));
break;
case 3:
fields.Add(new Field("f" + NextInt(100), GetString(Lucene.Net.Index.TestStressIndexing2.bigFieldSize), Field.Store.YES, Field.Index.ANALYZED, tvVal));
break;
}
}
if (Lucene.Net.Index.TestStressIndexing2.sameFieldOrder)
{
CollectionsHelper.Sort(fields, Lucene.Net.Index.TestStressIndexing2.fieldNameComparator);
}
else
{
// random placement of id field also
int index = NextInt(fields.Count);
fields[0] = fields[index];
fields[index] = idField;
}
for (int i = 0; i < fields.Count; i++)
{
d.Add((IFieldable) fields[i]);
}
w.UpdateDocument(Lucene.Net.Index.TestStressIndexing2.idTerm.CreateTerm(idString), d);
// System.out.println("indexing "+d);
docs[idString] = d;
}
public virtual void DeleteDoc()
{
System.String idString = GetIdString();
w.DeleteDocuments(Lucene.Net.Index.TestStressIndexing2.idTerm.CreateTerm(idString));
docs.Remove(idString);
}
public virtual void DeleteByQuery()
{
System.String idString = GetIdString();
w.DeleteDocuments(new TermQuery(Lucene.Net.Index.TestStressIndexing2.idTerm.CreateTerm(idString)));
docs.Remove(idString);
}
override public void Run()
{
try
{
r = new System.Random((System.Int32) (base_Renamed + range + Lucene.Net.Index.TestStressIndexing2.seed));
for (int i = 0; i < iterations; i++)
{
int what = NextInt(100);
if (what < 5)
{
DeleteDoc();
}
else if (what < 10)
{
DeleteByQuery();
}
else
{
IndexDoc();
}
}
}
catch (System.Exception e)
{
System.Console.Error.WriteLine(e.StackTrace);
Assert.Fail(e.ToString()); // TestCase.fail(e.ToString());
}
lock (this)
{
int generatedAux = docs.Count;
}
}
}
static TestStressIndexing2()
{
fieldNameComparator = new AnonymousClassComparator();
}
}
}
| |
// 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 ExtractInt161()
{
var test = new SimpleUnaryOpTest__ExtractInt161();
try
{
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
}
catch (PlatformNotSupportedException)
{
test.Succeeded = true;
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ExtractInt161
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector128<Int16> _clsVar;
private Vector128<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static SimpleUnaryOpTest__ExtractInt161()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ExtractInt161()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Extract(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Extract(
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Extract(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Extract), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int16)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Extract), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int16)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Extract), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int16)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Extract(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr);
var result = Sse2.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ExtractInt161();
var result = Sse2.Extract(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Extract(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
if ((result[0] != firstOp[1]))
{
Succeeded = false;
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Extract)}<Int16>(Vector128<Int16><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System.Linq;
using NUnit.Framework;
using Shouldly;
using StructureMap.Graph;
using StructureMap.Testing.GenericWidgets;
using StructureMap.Testing.Widget;
namespace StructureMap.Testing.Pipeline
{
[TestFixture]
public class NestedContainerSupportTester
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
}
#endregion
public class ContainerHolder
{
private readonly IContainer _container;
public ContainerHolder(IContainer container)
{
_container = container;
}
public IContainer Container
{
get { return _container; }
}
}
public interface IBar
{
}
public class AFoo : IBar
{
}
public class BFoo : IBar
{
}
public class CFoo : IBar
{
}
public interface IAutomobile
{
}
public class Mustang : IAutomobile
{
}
public interface IEngine
{
}
public class PushrodEngine : IEngine
{
}
[Test]
public void allow_nested_container_to_report_what_it_has()
{
var container = new Container(x => x.For<IAutomobile>().Use<Mustang>());
var nestedContainer = container.GetNestedContainer();
nestedContainer.Inject<IEngine>(new PushrodEngine());
container.WhatDoIHave().ShouldNotBeEmpty().ShouldNotContain(typeof (IEngine).Name);
nestedContainer.WhatDoIHave().ShouldNotBeEmpty().ShouldContain(typeof (IEngine).Name);
}
[Test]
public void NestedContainer_names_should_start_with_nested_container()
{
var container = new Container(x => x.For<IAutomobile>().Use<Mustang>());
var nestedContainer = container.GetNestedContainer();
nestedContainer.Name.ShouldStartWith("Nested-");
}
[Test]
public void disposing_the_child_container_does_not_affect_the_parent_container()
{
var container = new Container(x =>
{
x.Scan(o =>
{
o.TheCallingAssembly();
o.AddAllTypesOf<IBar>();
});
});
container.GetAllInstances<IBar>().Count()
.ShouldBeGreaterThan(0);
using (var nested = container.GetNestedContainer())
{
nested.GetAllInstances<IBar>().Count()
.ShouldBeGreaterThan(0);
}
container.GetAllInstances<IBar>().Count()
.ShouldBeGreaterThan(0);
}
[Test]
public void get_a_nested_container_for_a_profile()
{
var parent = new Container(x =>
{
x.For<IWidget>().Use<ColorWidget>()
.Ctor<string>("color").Is("red");
x.Profile("green", o =>
{
o.For<IWidget>().Use<ColorWidget>()
.Ctor<string>("color").Is("green");
});
});
var child = parent.GetNestedContainer("green");
var childWidget1 = child.GetInstance<IWidget>();
var childWidget2 = child.GetInstance<IWidget>();
var childWidget3 = child.GetInstance<IWidget>();
var parentWidget = parent.GetInstance<IWidget>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldNotBeTheSameAs(parentWidget);
parentWidget.ShouldBeOfType<ColorWidget>().Color.ShouldBe("red");
childWidget1.ShouldBeOfType<ColorWidget>().Color.ShouldBe("green");
}
[Test]
public void inject_into_the_child_does_not_affect_the_parent_container()
{
var parent = new Container(x => x.For<IWidget>().Use<AWidget>());
var child = parent.GetNestedContainer();
var childWidget = new ColorWidget("blue");
child.Inject<IWidget>(childWidget);
// do the check repeatedly
child.GetInstance<IWidget>().ShouldBeTheSameAs(childWidget);
child.GetInstance<IWidget>().ShouldBeTheSameAs(childWidget);
child.GetInstance<IWidget>().ShouldBeTheSameAs(childWidget);
// now, compare to the parent
parent.GetInstance<IWidget>().ShouldNotBeTheSameAs(childWidget);
}
[Test]
public void singleton_service_from_open_type_in_the_parent_is_found_by_the_child()
{
var parent = new Container(x => x.ForSingletonOf(typeof (IService<>)).Use(typeof (Service<>)));
var child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IService<string>>();
var childWidget2 = child.GetInstance<IService<string>>();
var childWidget3 = child.GetInstance<IService<string>>();
var parentWidget = parent.GetInstance<IService<string>>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldBeTheSameAs(parentWidget);
}
[Test]
public void singleton_service_in_the_parent_is_found_by_the_child()
{
var parent = new Container(x => x.ForSingletonOf<IWidget>().Use<AWidget>());
var parentWidget = parent.GetInstance<IWidget>();
var child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IWidget>();
var childWidget2 = child.GetInstance<IWidget>();
parentWidget.ShouldBeTheSameAs(childWidget1);
parentWidget.ShouldBeTheSameAs(childWidget2);
}
[Test]
public void the_nested_container_delivers_itself_as_the_IContainer()
{
var parent = new Container(x => x.For<IWidget>().Use<AWidget>());
var child = parent.GetNestedContainer();
child.GetInstance<IContainer>().ShouldBeTheSameAs(child);
}
[Test]
public void the_nested_container_will_deliver_itself_into_a_constructor_of_something_else()
{
var parent = new Container(x => x.For<IWidget>().Use<AWidget>());
var child = parent.GetNestedContainer();
child.GetInstance<ContainerHolder>().Container.ShouldBeTheSameAs(child);
}
[Test]
public void
transient_open_generics_service_in_the_parent_container_is_effectively_a_singleton_for_the_nested_container()
{
var parent = new Container(x => x.For(typeof (IService<>)).Use(typeof (Service<>)));
var child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IService<string>>();
var childWidget2 = child.GetInstance<IService<string>>();
var childWidget3 = child.GetInstance<IService<string>>();
var parentWidget = parent.GetInstance<IService<string>>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldNotBeTheSameAs(parentWidget);
}
[Test]
public void transient_service_in_the_parent_container_is_effectively_a_singleton_for_the_nested_container()
{
var parent = new Container(x =>
{
// IWidget is a "transient"
x.For<IWidget>().Use<AWidget>();
});
var child = parent.GetNestedContainer();
var childWidget1 = child.GetInstance<IWidget>();
var childWidget2 = child.GetInstance<IWidget>();
var childWidget3 = child.GetInstance<IWidget>();
var parentWidget = parent.GetInstance<IWidget>();
childWidget1.ShouldBeTheSameAs(childWidget2);
childWidget1.ShouldBeTheSameAs(childWidget3);
childWidget1.ShouldNotBeTheSameAs(parentWidget);
}
[Test]
public void nested_container_name_should_contain_parent_container_name()
{
var parent = new Container
{
Name = "Parent"
};
var child = parent.GetNestedContainer();
child.Name.ShouldBe("Nested-Parent");
}
[Test]
public void nested_container_name_with_profile_should_contain_parent_container_name()
{
var parent = new Container
{
Name = "Parent"
};
var child = parent.GetNestedContainer("Default");
child.Name.ShouldBe("Nested-Parent");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// Copyright (c) 2004 Mainsoft Co.
//
// 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 Xunit;
using System.ComponentModel;
using System.Collections;
namespace System.Data.Tests
{
public class DataRelationCollectionTest2
{
private int _changesCounter = 0;
private void Relations_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
_changesCounter++;
}
private DataSet getDataSet()
{
var ds = new DataSet();
DataTable dt1 = DataProvider.CreateParentDataTable();
DataTable dt2 = DataProvider.CreateChildDataTable();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
return ds;
}
public DataRelationCollectionTest2()
{
_changesCounter = 0;
}
[Fact]
public void AddRange()
{
DataSet ds = getDataSet();
DataRelation[] relArray = new DataRelation[2];
relArray[0] = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
relArray[1] = new DataRelation("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
ds.Relations.AddRange(relArray);
Assert.Equal(2, ds.Relations.Count);
Assert.Equal("rel1", ds.Relations[0].RelationName);
Assert.Equal("rel2", ds.Relations[1].RelationName);
ds.Relations.AddRange(null);
}
[Fact]
public void Add_ByDataColumns()
{
DataSet ds = getDataSet();
ds.Relations.Add(ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
Assert.Equal(1, ds.Relations.Count);
Assert.Equal(1, ds.Tables[0].ChildRelations.Count);
Assert.Equal(1, ds.Tables[1].ParentRelations.Count);
Assert.Equal(typeof(UniqueConstraint), ds.Tables[0].Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), ds.Tables[1].Constraints[0].GetType());
}
[Fact]
public void Add_ByNameDataColumns()
{
DataSet ds = getDataSet();
ds.Relations.Add("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
Assert.Equal(1, ds.Relations.Count);
Assert.Equal(1, ds.Tables[0].ChildRelations.Count);
Assert.Equal(1, ds.Tables[1].ParentRelations.Count);
Assert.Equal(typeof(UniqueConstraint), ds.Tables[0].Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), ds.Tables[1].Constraints[0].GetType());
Assert.Equal("rel1", ds.Relations[0].RelationName);
Assert.Equal("rel1", ds.Tables[0].ChildRelations[0].RelationName);
Assert.Equal("rel1", ds.Tables[1].ParentRelations[0].RelationName);
}
[Fact]
public void Add_ByNameDataColumnsWithConstraint()
{
DataSet ds = getDataSet();
ds.Relations.Add("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"], true);
Assert.Equal(1, ds.Relations.Count);
Assert.Equal(1, ds.Tables[0].ChildRelations.Count); //When adding a relation);
Assert.Equal(1, ds.Tables[1].ParentRelations.Count);
Assert.Equal(typeof(UniqueConstraint), ds.Tables[0].Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), ds.Tables[1].Constraints[0].GetType());
Assert.Equal("rel1", ds.Relations[0].RelationName);
Assert.Equal("rel1", ds.Tables[0].ChildRelations[0].RelationName);
Assert.Equal("rel1", ds.Tables[1].ParentRelations[0].RelationName);
}
[Fact]
public void Add_ByNameDataColumnsWithOutConstraint()
{
DataSet ds = getDataSet();
ds.Relations.Add("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"], false);
Assert.Equal(1, ds.Relations.Count);
Assert.Equal(1, ds.Tables[0].ChildRelations.Count); //When adding a relation);
Assert.Equal(1, ds.Tables[1].ParentRelations.Count);
Assert.Equal(0, ds.Tables[0].Constraints.Count);
Assert.Equal(0, ds.Tables[1].Constraints.Count);
Assert.Equal("rel1", ds.Relations[0].RelationName);
Assert.Equal("rel1", ds.Tables[0].ChildRelations[0].RelationName);
Assert.Equal("rel1", ds.Tables[1].ParentRelations[0].RelationName);
}
[Fact]
public void CanRemove()
{
DataSet ds = getDataSet();
ds.Relations.Add(ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
Assert.True(ds.Relations.CanRemove(ds.Relations[0]));
Assert.True(ds.Tables[0].ChildRelations.CanRemove(ds.Tables[0].ChildRelations[0]));
Assert.True(ds.Tables[1].ParentRelations.CanRemove(ds.Tables[1].ParentRelations[0]));
Assert.False(ds.Relations.CanRemove(null));
}
[Fact]
public void CanRemove_DataRelation()
{
DataSet ds = getDataSet();
DataSet ds1 = getDataSet();
DataRelation rel = new DataRelation("rel1",
ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
Assert.False(ds1.Relations.CanRemove(rel));
}
[Fact]
public void Clear()
{
DataSet ds = getDataSet();
ds.Relations.Add(ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
ds.Relations.CollectionChanged += new CollectionChangeEventHandler(Relations_CollectionChanged);
ds.Relations.Clear();
Assert.Equal(0, ds.Relations.Count);
Assert.Equal(1, _changesCounter);
}
/// <summary>
/// Clear was already checked at the clear sub test
/// </summary>
[Fact]
public void CollectionChanged()
{
DataSet ds = getDataSet();
ds.Relations.CollectionChanged += new CollectionChangeEventHandler(Relations_CollectionChanged);
DataRelation rel = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"]
, ds.Tables[1].Columns["ParentId"]);
ds.Relations.Add(rel);
ds.Relations.Remove(rel);
Assert.Equal(2, _changesCounter);
}
[Fact]
public void Contains()
{
DataSet ds = getDataSet();
ds.Relations.Add("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
Assert.True(ds.Relations.Contains("rel1"));
Assert.False(ds.Relations.Contains("RelL"));
Assert.False(ds.Relations.Contains("rel2"));
}
[Fact]
public void CopyTo()
{
DataSet ds = getDataSet();
DataRelation[] dataRelArray = new DataRelation[2];
ds.Relations.Add(new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]));
ds.Relations.CopyTo(dataRelArray, 1);
Assert.Equal("rel1", dataRelArray[1].RelationName);
ds.Relations.CopyTo(dataRelArray, 0);
Assert.Equal("rel1", dataRelArray[0].RelationName);
}
[Fact]
public void Count()
{
DataSet ds = getDataSet();
Assert.Equal(0, ds.Relations.Count);
ds.Relations.Add("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
Assert.Equal(1, ds.Relations.Count);
ds.Relations.Add("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
Assert.Equal(2, ds.Relations.Count);
ds.Relations.Remove("rel2");
Assert.Equal(1, ds.Relations.Count);
ds.Relations.Remove("rel1");
Assert.Equal(0, ds.Relations.Count);
}
[Fact]
public void GetEnumerator()
{
DataSet ds = getDataSet();
int counter = 0;
ds.Relations.Add("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
ds.Relations.Add("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
IEnumerator myEnumerator = ds.Relations.GetEnumerator();
while (myEnumerator.MoveNext())
{
counter++;
Assert.Equal("rel", ((DataRelation)myEnumerator.Current).RelationName.Substring(0, 3));
}
Assert.Equal(2, counter);
}
[Fact]
public void IndexOf_ByDataRelation()
{
DataSet ds = getDataSet();
DataSet ds1 = getDataSet();
DataRelation rel1 = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
DataRelation rel2 = new DataRelation("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
DataRelation rel3 = new DataRelation("rel3", ds1.Tables[0].Columns["ParentId"], ds1.Tables[1].Columns["ParentId"]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
Assert.Equal(1, ds.Relations.IndexOf(rel2));
Assert.Equal(0, ds.Relations.IndexOf(rel1));
Assert.Equal(-1, ds.Relations.IndexOf((DataRelation)null));
Assert.Equal(-1, ds.Relations.IndexOf(rel3));
}
[Fact]
public void IndexOf_ByDataRelationName()
{
DataSet ds = getDataSet();
DataSet ds1 = getDataSet();
DataRelation rel1 = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
DataRelation rel2 = new DataRelation("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
DataRelation rel3 = new DataRelation("rel3", ds1.Tables[0].Columns["ParentId"], ds1.Tables[1].Columns["ParentId"]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
Assert.Equal(1, ds.Relations.IndexOf("rel2"));
Assert.Equal(0, ds.Relations.IndexOf("rel1"));
Assert.Equal(-1, ds.Relations.IndexOf((string)null));
Assert.Equal(-1, ds.Relations.IndexOf("rel3"));
}
[Fact]
public void Item()
{
DataSet ds = getDataSet();
DataRelation rel1 = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
DataRelation rel2 = new DataRelation("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
Assert.Equal("rel1", ds.Relations["rel1"].RelationName);
Assert.Equal("rel2", ds.Relations["rel2"].RelationName);
Assert.Equal("rel1", ds.Relations[0].RelationName);
Assert.Equal("rel2", ds.Relations[1].RelationName);
}
[Fact]
public void Add_DataColumn1()
{
DataSet ds = DataProvider.CreateForeignConstraint();
int originalRelationsCount = ds.Relations.Count;
DataRelation rel = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"]
, ds.Tables[1].Columns["ParentId"]);
ds.Relations.Add(rel);
Assert.Equal(originalRelationsCount + 1, ds.Relations.Count);
Assert.Equal(1, ds.Tables[0].ChildRelations.Count);
Assert.Equal(1, ds.Tables[1].ParentRelations.Count);
Assert.Equal(typeof(UniqueConstraint), ds.Tables[0].Constraints[0].GetType());
Assert.Equal(typeof(ForeignKeyConstraint), ds.Tables[1].Constraints[0].GetType());
AssertExtensions.Throws<ArgumentException>(null, () =>
{
ds.Relations.Add(rel);
});
ds.Relations.Add(null);
}
[Fact]
public void Add_DataColumn2()
{
DataSet ds = GetDataSet();
DataTable dt1 = ds.Tables[0];
DataTable dt2 = ds.Tables[1];
dt1.ChildRelations.Add(new DataRelation("rel1", dt1.Columns["ParentId"], dt2.Columns["ParentId"]));
Assert.Equal(1, dt1.ChildRelations.Count);
Assert.Equal(1, dt2.ParentRelations.Count);
Assert.Equal(1, ds.Relations.Count);
}
[Fact]
public void Add_DataColumn3()
{
DataSet ds = GetDataSet();
ds.Tables[1].ParentRelations.Add(new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]));
Assert.Equal(1, ds.Tables[0].ChildRelations.Count);
Assert.Equal(1, ds.Tables[1].ParentRelations.Count);
Assert.Equal(1, ds.Relations.Count);
}
[Fact]
public void Add_DataColumn4()
{
DataSet ds = GetDataSet();
DataTable dt = new DataTable();
dt.Columns.Add("ParentId");
Assert.Throws<InvalidConstraintException>(() =>
{
ds.Relations.Add(new DataRelation("rel1", dt.Columns[0], ds.Tables[0].Columns[0]));
});
}
[Fact]
public void Add_DataColumn5()
{
DataSet ds = GetDataSet();
}
private DataSet GetDataSet()
{
var ds = new DataSet();
DataTable dt1 = DataProvider.CreateParentDataTable();
DataTable dt2 = DataProvider.CreateChildDataTable();
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
return ds;
}
[Fact]
public void Remove_DataColumn()
{
DataSet ds = getDataSet();
DataSet ds1 = getDataSet();
DataRelation rel1 = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
DataRelation rel2 = new DataRelation("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
Assert.Equal(2, ds.Relations.Count);
ds.Relations.CollectionChanged += new CollectionChangeEventHandler(Relations_CollectionChanged);
//Perform remove
ds.Relations.Remove(rel1);
Assert.Equal(1, ds.Relations.Count);
Assert.Equal("rel2", ds.Relations[0].RelationName);
ds.Relations.Remove(rel2);
Assert.Equal(0, ds.Relations.Count);
Assert.Equal(2, _changesCounter);
ds.Relations.Remove((DataRelation)null);
AssertExtensions.Throws<ArgumentException>(null, () =>
{
DataRelation rel3 = new DataRelation("rel3", ds1.Tables[0].Columns["ParentId"], ds1.Tables[1].Columns["ParentId"]);
ds.Relations.Remove(rel3);
});
}
[Fact]
public void Remove_String()
{
DataSet ds = getDataSet();
DataSet ds1 = getDataSet();
DataRelation rel1 = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
DataRelation rel2 = new DataRelation("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
Assert.Equal(2, ds.Relations.Count);
ds.Relations.CollectionChanged += new CollectionChangeEventHandler(Relations_CollectionChanged);
//Perform remove
ds.Relations.Remove("rel1");
Assert.Equal(1, ds.Relations.Count);
Assert.Equal("rel2", ds.Relations[0].RelationName);
ds.Relations.Remove("rel2");
Assert.Equal(0, ds.Relations.Count);
Assert.Equal(2, _changesCounter);
AssertExtensions.Throws<ArgumentException>(null, () =>
{
ds.Relations.Remove((string)null);
});
AssertExtensions.Throws<ArgumentException>(null, () =>
{
ds.Relations.Remove("rel3");
});
}
private void RemoveAt()
{
DataSet ds = getDataSet();
DataSet ds1 = getDataSet();
DataRelation rel1 = new DataRelation("rel1", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"]);
DataRelation rel2 = new DataRelation("rel2", ds.Tables[0].Columns["String1"], ds.Tables[1].Columns["String1"]);
ds.Relations.Add(rel1);
ds.Relations.Add(rel2);
Assert.Equal(2, ds.Relations.Count);
ds.Relations.CollectionChanged += new CollectionChangeEventHandler(Relations_CollectionChanged);
//Perform remove
ds.Relations.RemoveAt(0);
Assert.Equal(1, ds.Relations.Count);
Assert.Equal("rel2", ds.Relations[0].RelationName);
ds.Relations.RemoveAt(0);
Assert.Equal(0, ds.Relations.Count);
Assert.Equal(2, _changesCounter);
Assert.Throws<IndexOutOfRangeException>(() =>
{
ds.Relations.RemoveAt(-1);
});
}
}
}
| |
namespace Humidifier.ElasticLoadBalancing
{
using System.Collections.Generic;
using LoadBalancerTypes;
public class LoadBalancer : Humidifier.Resource
{
public static class Attributes
{
public static string CanonicalHostedZoneName = "CanonicalHostedZoneName" ;
public static string CanonicalHostedZoneNameID = "CanonicalHostedZoneNameID" ;
public static string DNSName = "DNSName" ;
}
public override string AWSTypeName
{
get
{
return @"AWS::ElasticLoadBalancing::LoadBalancer";
}
}
/// <summary>
/// AccessLoggingPolicy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-accessloggingpolicy
/// Required: False
/// UpdateType: Mutable
/// Type: AccessLoggingPolicy
/// </summary>
public AccessLoggingPolicy AccessLoggingPolicy
{
get;
set;
}
/// <summary>
/// AppCookieStickinessPolicy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-appcookiestickinesspolicy
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: AppCookieStickinessPolicy
/// </summary>
public List<AppCookieStickinessPolicy> AppCookieStickinessPolicy
{
get;
set;
}
/// <summary>
/// AvailabilityZones
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-availabilityzones
/// Required: False
/// UpdateType: Conditional
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic AvailabilityZones
{
get;
set;
}
/// <summary>
/// ConnectionDrainingPolicy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectiondrainingpolicy
/// Required: False
/// UpdateType: Mutable
/// Type: ConnectionDrainingPolicy
/// </summary>
public ConnectionDrainingPolicy ConnectionDrainingPolicy
{
get;
set;
}
/// <summary>
/// ConnectionSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectionsettings
/// Required: False
/// UpdateType: Mutable
/// Type: ConnectionSettings
/// </summary>
public ConnectionSettings ConnectionSettings
{
get;
set;
}
/// <summary>
/// CrossZone
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-crosszone
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic CrossZone
{
get;
set;
}
/// <summary>
/// HealthCheck
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-healthcheck
/// Required: False
/// UpdateType: Conditional
/// Type: HealthCheck
/// </summary>
public HealthCheck HealthCheck
{
get;
set;
}
/// <summary>
/// Instances
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-instances
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Instances
{
get;
set;
}
/// <summary>
/// LBCookieStickinessPolicy
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-lbcookiestickinesspolicy
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: LBCookieStickinessPolicy
/// </summary>
public List<LBCookieStickinessPolicy> LBCookieStickinessPolicy
{
get;
set;
}
/// <summary>
/// Listeners
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-listeners
/// Required: True
/// UpdateType: Mutable
/// Type: List
/// ItemType: Listeners
/// </summary>
public List<Listeners> Listeners
{
get;
set;
}
/// <summary>
/// LoadBalancerName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-elbname
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic LoadBalancerName
{
get;
set;
}
/// <summary>
/// Policies
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-policies
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Policies
/// </summary>
public List<Policies> Policies
{
get;
set;
}
/// <summary>
/// Scheme
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-scheme
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic Scheme
{
get;
set;
}
/// <summary>
/// SecurityGroups
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-securitygroups
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic SecurityGroups
{
get;
set;
}
/// <summary>
/// Subnets
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-subnets
/// Required: False
/// UpdateType: Conditional
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic Subnets
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-elasticloadbalancing-loadbalancer-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Tag
/// </summary>
public List<Tag> Tags
{
get;
set;
}
}
namespace LoadBalancerTypes
{
public class AccessLoggingPolicy
{
/// <summary>
/// EmitInterval
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-emitinterval
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic EmitInterval
{
get;
set;
}
/// <summary>
/// Enabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-enabled
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Enabled
{
get;
set;
}
/// <summary>
/// S3BucketName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-s3bucketname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic S3BucketName
{
get;
set;
}
/// <summary>
/// S3BucketPrefix
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-s3bucketprefix
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic S3BucketPrefix
{
get;
set;
}
}
public class LBCookieStickinessPolicy
{
/// <summary>
/// CookieExpirationPeriod
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html#cfn-elb-lbcookiestickinesspolicy-cookieexpirationperiod
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic CookieExpirationPeriod
{
get;
set;
}
/// <summary>
/// PolicyName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html#cfn-elb-lbcookiestickinesspolicy-policyname
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PolicyName
{
get;
set;
}
}
public class Listeners
{
/// <summary>
/// InstancePort
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-instanceport
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InstancePort
{
get;
set;
}
/// <summary>
/// InstanceProtocol
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-instanceprotocol
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic InstanceProtocol
{
get;
set;
}
/// <summary>
/// LoadBalancerPort
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-loadbalancerport
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LoadBalancerPort
{
get;
set;
}
/// <summary>
/// PolicyNames
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-policynames
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic PolicyNames
{
get;
set;
}
/// <summary>
/// Protocol
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-protocol
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Protocol
{
get;
set;
}
/// <summary>
/// SSLCertificateId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-sslcertificateid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic SSLCertificateId
{
get;
set;
}
}
public class HealthCheck
{
/// <summary>
/// HealthyThreshold
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-healthythreshold
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HealthyThreshold
{
get;
set;
}
/// <summary>
/// Interval
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-interval
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Interval
{
get;
set;
}
/// <summary>
/// Target
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-target
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Target
{
get;
set;
}
/// <summary>
/// Timeout
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-timeout
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Timeout
{
get;
set;
}
/// <summary>
/// UnhealthyThreshold
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-unhealthythreshold
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic UnhealthyThreshold
{
get;
set;
}
}
public class ConnectionSettings
{
/// <summary>
/// IdleTimeout
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectionsettings.html#cfn-elb-connectionsettings-idletimeout
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic IdleTimeout
{
get;
set;
}
}
public class ConnectionDrainingPolicy
{
/// <summary>
/// Enabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html#cfn-elb-connectiondrainingpolicy-enabled
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic Enabled
{
get;
set;
}
/// <summary>
/// Timeout
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html#cfn-elb-connectiondrainingpolicy-timeout
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic Timeout
{
get;
set;
}
}
public class Policies
{
/// <summary>
/// Attributes
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-attributes
/// Required: True
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: Json
/// </summary>
public List<dynamic> Attributes_
{
get;
set;
}
/// <summary>
/// InstancePorts
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-instanceports
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic InstancePorts
{
get;
set;
}
/// <summary>
/// LoadBalancerPorts
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-loadbalancerports
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// PrimitiveItemType: String
/// </summary>
public dynamic LoadBalancerPorts
{
get;
set;
}
/// <summary>
/// PolicyName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policyname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PolicyName
{
get;
set;
}
/// <summary>
/// PolicyType
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policytype
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PolicyType
{
get;
set;
}
}
public class AppCookieStickinessPolicy
{
/// <summary>
/// CookieName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html#cfn-elb-appcookiestickinesspolicy-cookiename
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic CookieName
{
get;
set;
}
/// <summary>
/// PolicyName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html#cfn-elb-appcookiestickinesspolicy-policyname
/// Required: True
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic PolicyName
{
get;
set;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: For writing text to streams in a particular
** encoding.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace System.IO
{
// This class implements a TextWriter for writing characters to a Stream.
// This is designed for character output in a particular Encoding,
// whereas the Stream class is designed for byte input and output.
//
[Serializable]
[ComVisible(true)]
public class StreamWriter : TextWriter
{
// For UTF-8, the values of 1K for the default buffer size and 4K for the
// file stream buffer size are reasonable & give very reasonable
// performance for in terms of construction time for the StreamWriter and
// write perf. Note that for UTF-8, we end up allocating a 4K byte buffer,
// which means we take advantage of adaptive buffering code.
// The performance using UnicodeEncoding is acceptable.
internal const int DefaultBufferSize = 1024; // char[]
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
private const Int32 DontCopyOnWriteLineThreshold = 512;
// Bit bucket - Null has no backing store. Non closable.
public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true);
private Stream stream;
private Encoding encoding;
private Encoder encoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int charPos;
private int charLen;
private bool autoFlush;
private bool haveWrittenPreamble;
private bool closable;
#if MDA_SUPPORTED
[NonSerialized]
// For StreamWriterBufferedDataLost MDA
private MdaHelper mdaHelper;
#endif
// We don't guarantee thread safety on StreamWriter, but we should at
// least prevent users from trying to write anything while an Async
// write from the same thread is in progress.
[NonSerialized]
private volatile Task _asyncWriteTask;
private void CheckAsyncTaskInProgress()
{
// We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety.
// We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress.
Task t = _asyncWriteTask;
if (t != null && !t.IsCompleted)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
}
// The high level goal is to be tolerant of encoding errors when we read and very strict
// when we write. Hence, default StreamWriter encoding will throw on encoding error.
// Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character
// D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the
// internal StreamWriter's state to be irrecoverable as it would have buffered the
// illegal chars and any subsequent call to Flush() would hit the encoding error again.
// Even Close() will hit the exception as it would try to flush the unwritten data.
// Maybe we can add a DiscardBufferedData() method to get out of such situation (like
// StreamReader though for different reason). Either way, the buffered data will be lost!
private static volatile Encoding _UTF8NoBOM;
internal static Encoding UTF8NoBOM {
[FriendAccessAllowed]
get {
if (_UTF8NoBOM == null) {
// No need for double lock - we just want to avoid extra
// allocations in the common case.
UTF8Encoding noBOM = new UTF8Encoding(false, true);
Thread.MemoryBarrier();
_UTF8NoBOM = noBOM;
}
return _UTF8NoBOM;
}
}
internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time
}
public StreamWriter(Stream stream)
: this(stream, UTF8NoBOM, DefaultBufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding)
: this(stream, encoding, DefaultBufferSize, false) {
}
// Creates a new StreamWriter for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
//
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
: this(stream, encoding, bufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
: base(null) // Ask for CurrentCulture all the time
{
if (stream == null || encoding == null)
throw new ArgumentNullException((stream == null ? "stream" : "encoding"));
if (!stream.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Init(stream, encoding, bufferSize, leaveOpen);
}
public StreamWriter(String path)
: this(path, false, UTF8NoBOM, DefaultBufferSize) {
}
public StreamWriter(String path, bool append)
: this(path, append, UTF8NoBOM, DefaultBufferSize) {
}
public StreamWriter(String path, bool append, Encoding encoding)
: this(path, append, encoding, DefaultBufferSize) {
}
[System.Security.SecuritySafeCritical]
public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) {
}
[System.Security.SecurityCritical]
internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost)
: base(null)
{ // Ask for CurrentCulture all the time
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Stream stream = CreateFile(path, append, checkHost);
Init(stream, encoding, bufferSize, false);
}
[System.Security.SecuritySafeCritical]
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
this.stream = streamArg;
this.encoding = encodingArg;
this.encoder = encoding.GetEncoder();
if (bufferSize < MinBufferSize) bufferSize = MinBufferSize;
charBuffer = new char[bufferSize];
byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)];
charLen = bufferSize;
// If we're appending to a Stream that already has data, don't write
// the preamble.
if (stream.CanSeek && stream.Position > 0)
haveWrittenPreamble = true;
closable = !shouldLeaveOpen;
#if MDA_SUPPORTED
if (Mda.StreamWriterBufferedDataLost.Enabled) {
String callstack = null;
if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
callstack = Environment.GetStackTrace(null, false);
mdaHelper = new MdaHelper(this, callstack);
}
#endif
}
[System.Security.SecurityCritical]
private static Stream CreateFile(String path, bool append, bool checkHost) {
FileMode mode = append? FileMode.Append: FileMode.Create;
FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
return f;
}
public override void Close() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing) {
try {
// We need to flush any buffered data if we are being closed/disposed.
// Also, we never close the handles for stdout & friends. So we can safely
// write any buffered data to those streams even during finalization, which
// is generally the right thing to do.
if (stream != null) {
// Note: flush on the underlying stream can throw (ex., low disk space)
#if FEATURE_CORECLR
if (disposing)
#else
if (disposing || (LeaveOpen && stream is __ConsoleStream))
#endif
{
CheckAsyncTaskInProgress();
Flush(true, true);
#if MDA_SUPPORTED
// Disable buffered data loss mda
if (mdaHelper != null)
GC.SuppressFinalize(mdaHelper);
#endif
}
}
}
finally {
// Dispose of our resources if this StreamWriter is closable.
// Note: Console.Out and other such non closable streamwriters should be left alone
if (!LeaveOpen && stream != null) {
try {
// Attempt to close the stream even if there was an IO error from Flushing.
// Note that Stream.Close() can potentially throw here (may or may not be
// due to the same Flush error). In this case, we still need to ensure
// cleaning up internal resources, hence the finally block.
if (disposing)
stream.Close();
}
finally {
stream = null;
byteBuffer = null;
charBuffer = null;
encoding = null;
encoder = null;
charLen = 0;
base.Dispose(disposing);
}
}
}
}
public override void Flush()
{
CheckAsyncTaskInProgress();
Flush(true, true);
}
private void Flush(bool flushStream, bool flushEncoder)
{
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
// Perf boost for Flush on non-dirty writers.
if (charPos==0 && (!flushStream && !flushEncoder))
return;
if (!haveWrittenPreamble) {
haveWrittenPreamble = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
stream.Write(preamble, 0, preamble.Length);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
charPos = 0;
if (count > 0)
stream.Write(byteBuffer, 0, count);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
stream.Flush();
}
public virtual bool AutoFlush {
get { return autoFlush; }
set
{
CheckAsyncTaskInProgress();
autoFlush = value;
if (value) Flush(true, false);
}
}
public virtual Stream BaseStream {
get { return stream; }
}
internal bool LeaveOpen {
get { return !closable; }
}
internal bool HaveWrittenPreamble {
set { haveWrittenPreamble= value; }
}
public override Encoding Encoding {
get { return encoding; }
}
public override void Write(char value)
{
CheckAsyncTaskInProgress();
if (charPos == charLen) Flush(false, false);
charBuffer[charPos] = value;
charPos++;
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer)
{
// This may be faster than the one with the index & count since it
// has to do less argument checking.
if (buffer==null)
return;
CheckAsyncTaskInProgress();
int index = 0;
int count = buffer.Length;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
CheckAsyncTaskInProgress();
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(String value)
{
if (value != null)
{
CheckAsyncTaskInProgress();
int count = value.Length;
int index = 0;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
}
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = value;
charPos++;
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (value != null)
{
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
else
{
return Task.CompletedTask;
}
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, String value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(value != null);
int count = value.Length;
int index = 0;
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(count == 0 || (count > 0 && buffer != null));
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count));
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync();
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task FlushAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overriden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.FlushAsync();
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = FlushAsyncInternal(true, true, charBuffer, charPos);
_asyncWriteTask = task;
return task;
}
private Int32 CharPos_Prop {
set { this.charPos = value; }
}
private bool HaveWrittenPreamble_Prop {
set { this.haveWrittenPreamble = value; }
}
private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
Char[] sCharBuffer, Int32 sCharPos) {
// Perf boost for Flush on non-dirty writers.
if (sCharPos == 0 && !flushStream && !flushEncoder)
return Task.CompletedTask;
Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble,
this.encoding, this.encoder, this.byteBuffer, this.stream);
this.charPos = 0;
return flushTask;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble,
Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
{
if (!haveWrittenPreamble)
{
_this.HaveWrittenPreamble_Prop = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
if (count > 0)
await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
await stream.FlushAsync().ConfigureAwait(false);
}
#endregion
#if MDA_SUPPORTED
// StreamWriterBufferedDataLost MDA
// Instead of adding a finalizer to StreamWriter for detecting buffered data loss
// (ie, when the user forgets to call Close/Flush on the StreamWriter), we will
// have a separate object with normal finalization semantics that maintains a
// back pointer to this StreamWriter and alerts about any data loss
private sealed class MdaHelper
{
private StreamWriter streamWriter;
private String allocatedCallstack; // captures the callstack when this streamwriter was allocated
internal MdaHelper(StreamWriter sw, String cs)
{
streamWriter = sw;
allocatedCallstack = cs;
}
// Finalizer
~MdaHelper()
{
// Make sure people closed this StreamWriter, exclude StreamWriter::Null.
if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) {
String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>";
String callStack = allocatedCallstack;
if (callStack == null)
callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack);
Mda.StreamWriterBufferedDataLost.ReportError(message);
}
}
} // class MdaHelper
#endif // MDA_SUPPORTED
} // class StreamWriter
} // namespace
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Its.Domain.Serialization;
using Microsoft.Its.Recipes;
using Its.Validation;
namespace Microsoft.Its.Domain
{
/// <summary>
/// Provides additional functionality for event-sourced aggregates.
/// </summary>
public static class AggregateExtensions
{
/// <summary>
/// Applies a command to an aggregate.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregate">The aggregate.</param>
/// <param name="command">The command.</param>
/// <returns>The same aggregate with the command applied and any applicable updates performed.</returns>
public static TAggregate Apply<TAggregate>(
this TAggregate aggregate,
ICommand<TAggregate> command)
where TAggregate : class
{
command.ApplyTo(aggregate);
return aggregate;
}
/// <summary>
/// Applies a command to an aggregate.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregate">The aggregate.</param>
/// <param name="command">The command.</param>
/// <returns>The same aggregate with the command applied and any applicable updates performed.</returns>
public static async Task<TAggregate> ApplyAsync<TAggregate>(
this TAggregate aggregate,
ICommand<TAggregate> command)
where TAggregate : class
{
await command.ApplyToAsync(aggregate);
return aggregate;
}
/// <summary>
/// Gets an event sequence containing both the event history and pending events for the specified aggregate.
/// </summary>
/// <param name="aggregate">The aggregate.</param>
/// <returns></returns>
public static IEnumerable<IEvent> Events(this EventSourcedAggregate aggregate)
{
if (aggregate == null)
{
throw new ArgumentNullException("aggregate");
}
if (aggregate.SourceSnapshot != null)
{
throw new InvalidOperationException("Aggregate was sourced from a snapshot, so event history is unavailable.");
}
return aggregate.EventHistory.Concat(aggregate.PendingEvents);
}
/// <summary>
/// Determines whether an aggregate is valid for application of the specified command.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregate">The aggregate.</param>
/// <param name="command">The command.</param>
/// <returns>
/// <c>true</c> if the command can be applied; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidTo<TAggregate>(this TAggregate aggregate, Command<TAggregate> command)
where TAggregate : class
{
return !command.RunAllValidations(aggregate, false).HasFailures;
}
/// <summary>
/// Creates a new instance of the aggregate in memory using its state as of the specified version.
/// </summary>
public static TAggregate AsOfVersion<TAggregate>(this TAggregate aggregate, long version) where TAggregate : EventSourcedAggregate
{
var snapshot = aggregate.SourceSnapshot;
var eventsAsOfVersion = aggregate.EventHistory
.Concat(aggregate.PendingEvents)
.Where(e => e.SequenceNumber <= version);
if (snapshot != null)
{
if (snapshot.Version > version)
{
throw new InvalidOperationException("Snapshot version is later than specified version. Source the aggregate from an earlier snapshot or from events in order to use AsOfVersion.");
}
return AggregateType<TAggregate>.FromSnapshot.Invoke(
snapshot,
eventsAsOfVersion);
}
return AggregateType<TAggregate>.FromEventHistory.Invoke(
aggregate.Id,
eventsAsOfVersion);
}
/// <summary>
/// Updates the specified aggregate with additional events.
/// </summary>
/// <exception cref="System.ArgumentNullException">events</exception>
/// <exception cref="System.InvalidOperationException">Aggregates having pending events cannot be updated.</exception>
/// <remarks>This method can be used when additional events have been appended to an event stream and you would like to bring an in-memory aggregate up to date with those events. If there are new pending events, the aggregate needs to be reset first, and any commands re-applied.</remarks>
internal static void Update<TAggregate>(
this TAggregate aggregate,
IEnumerable<IEvent> events)
where TAggregate : IEventSourced
{
if (events == null)
{
throw new ArgumentNullException("events");
}
if (aggregate.PendingEvents.Any())
{
throw new InvalidOperationException("Aggregates having pending events cannot be updated.");
}
var startingVersion = aggregate.Version;
var pendingEvents = aggregate.PendingEvents
.IfTypeIs<EventSequence>()
.ElseDefault();
foreach (var @event in events
.OfType<IEvent<TAggregate>>()
.Where(e => e.SequenceNumber > startingVersion)
.Do(e =>
{
if (e.SequenceNumber == 0)
{
throw new InvalidOperationException("Event has not been previously stored: " + e.ToJson());
}
})
.ToArray())
{
pendingEvents.Add(@event);
@event.Update(aggregate);
}
aggregate.IfTypeIs<EventSourcedAggregate>()
.ThenDo(a => a.ConfirmSave());
}
/// <summary>
/// Validates the command against the specified aggregate.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregate">The aggregate.</param>
/// <param name="command">The command.</param>
/// <returns>A <see cref="ValidationReport" /> detailing any validation errors.</returns>
public static ValidationReport Validate<TAggregate>(this TAggregate aggregate, Command<TAggregate> command)
where TAggregate : class
{
return command.RunAllValidations(aggregate, false);
}
/// <summary>
/// Returns the version number of the aggregate, which is equal to it's latest event's sequence id.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregate">The aggregate.</param>
/// <returns>The aggregate's version.</returns>
public static long Version<TAggregate>(this TAggregate aggregate)
where TAggregate : EventSourcedAggregate
{
if (aggregate == null)
{
throw new ArgumentNullException("aggregate");
}
return Math.Max(
((EventSequence) aggregate.EventHistory).Version,
((EventSequence) aggregate.PendingEvents).Version);
}
/// <summary>
/// Initializes the interface properties of a snapshot.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregate">The aggregate.</param>
/// <param name="snapshot">The snapshot.</param>
/// <exception cref="System.ArgumentNullException">
/// aggregate
/// or
/// snapshot
/// </exception>
public static void InitializeSnapshot<TAggregate>(this TAggregate aggregate, ISnapshot snapshot)
where TAggregate : class, IEventSourced
{
if (aggregate == null)
{
throw new ArgumentNullException("aggregate");
}
if (snapshot == null)
{
throw new ArgumentNullException("snapshot");
}
if (aggregate.PendingEvents.Any())
{
throw new InvalidOperationException("A snapshot can only be created from an aggregate having no pending events. Save the aggregate before creating a snapshot.");
}
snapshot.AggregateId = aggregate.Id;
snapshot.AggregateTypeName = AggregateType<TAggregate>.EventStreamName;
snapshot.LastUpdated = Clock.Now();
snapshot.Version = aggregate.Version;
snapshot.ETags = aggregate.CreateETagBloomFilter();
}
internal static BloomFilter CreateETagBloomFilter<TAggregate>(this TAggregate aggregate)
where TAggregate : class, IEventSourced
{
return aggregate.IfTypeIs<EventSourcedAggregate>()
.Then(a =>
{
if (a.WasSourcedFromSnapshot)
{
return a.SourceSnapshot.ETags;
}
var bloomFilter = new BloomFilter();
a.EventHistory
.Select(e => e.ETag)
.Where(etag => !string.IsNullOrWhiteSpace(etag))
.ForEach(bloomFilter.Add);
return bloomFilter;
})
.ElseDefault();
}
/// <summary>
/// Determines whether the specified ETag already exists in the aggregate's event stream.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregate">The aggregate.</param>
/// <param name="etag">The etag.</param>
public static bool HasETag<TAggregate>(this TAggregate aggregate, string etag)
where TAggregate : class, IEventSourced
{
if (aggregate == null)
{
throw new ArgumentNullException("aggregate");
}
if (string.IsNullOrWhiteSpace(etag))
{
return false;
}
var eventSourcedAggregate = aggregate as EventSourcedAggregate;
if (eventSourcedAggregate != null)
{
var answer = eventSourcedAggregate.HasETag(etag);
if (answer == ProbabilisticAnswer.Yes)
{
return true;
}
if (answer == ProbabilisticAnswer.No)
{
return false;
}
// ProbabilisticAnswer.Maybe, which means we need to do a lookup
var preconditionVerifier = Configuration.Current
.Container
.Resolve<IETagChecker>();
return Task.Run(() => preconditionVerifier.HasBeenRecorded(
aggregate.Id.ToString(),
etag)).Result;
}
return false;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Language;
using System.Globalization;
using Microsoft.PowerShell.Commands;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Internal;
namespace System.Management.Automation
{
/// <summary>
/// Monad help is an architecture made up of three layers:
/// 1. At the top is get-help commandlet from where help functionality is accessed.
/// 2. At the middle is the help system which collects help objects based on user's request.
/// 3. At the bottom are different help providers which provide help contents for different kinds of information requested.
///
/// Class HelpSystem implements the middle layer of Monad Help.
///
/// HelpSystem will provide functionalitys in following areas,
/// 1. Initialization and management of help providers
/// 2. Help engine: this will invoke different providers based on user's request.
/// 3. Help API: this is the API HelpSystem provide to get-help commandlet.
///
/// Initialization:
/// Initialization of different help providers needs some context information like "ExecutionContext"
///
/// Help engine:
/// By default, HelpInfo will be retrieved in two phase: exact-match phase and search phase.
///
/// Exact-match phase: help providers will be called in appropriate order to retrieve HelpInfo.
/// If a match is found, help engine will stop and return the one and only HelpInfo retrieved.
///
/// Search phase: all relevant help providers will be called to retrieve HelpInfo. (Order doesn't
/// matter in this case) Help engine will not stop until all help providers are called.
///
/// Behaviour of help engine can be modified based on Help API parameters in following ways,
/// 1. limit the number of HelpInfo to be returned.
/// 2. specify which providers will be used.
/// 3. general help info returned in case the search target is empty.
/// 4. default help info (or hint) returned in case no match is found.
///
/// Help Api:
/// Help Api is the function to be called by get-help commandlet.
///
/// Following information needs to be provided in Help Api parameters,
/// 1. search target: (which can be one or multiple strings)
/// 2. help type: limit the type of help to be searched.
/// 3. included fields: the fields to be included in the help info
/// 4. excluded fields: the fields to be excluded in the help info
/// 5. max number of results to be returned:
/// 6. scoring algorithm for help results?
/// 7. help reason: help can be directly invoked by end user or as a result of
/// some command syntax error.
///
/// [gxie, 7-25-04]: included fields, excluded fields and help reason will be handled in
/// get-help commandlet.
///
/// Help API's are internal. The only way to access help is by
/// invoking the get-help command.
///
/// To support the scenario where multiple monad engine running in one process. It
/// is required that each monad engine has its one help system instance.
///
/// Currently each ExecutionContext has a help system instance as its member.
///
/// Help Providers:
/// The basic contract for help providers is to provide help based on the
/// search target.
///
/// The result of help provider invocation can be three things:
/// a. Full help info. (in the case of exact-match and single search result)
/// b. Short help info. (in the case of multiple search result)
/// c. Partial help info. (in the case of some commandlet help info, which
/// should be supplemented by provider help info)
/// d. Help forwarding info. (in the case of alias, which will change the target
/// for alias)
///
/// Help providers may need to provide functionality in following two area,
/// a. caching and indexing to boost performance
/// b. localization
///
/// </summary>
internal class HelpSystem
{
/// <summary>
/// Constructor for HelpSystem.
/// </summary>
/// <param name="context">Execution context for this help system</param>
internal HelpSystem(ExecutionContext context)
{
if (context == null)
{
throw PSTraceSource.NewArgumentNullException("ExecutionContext");
}
_executionContext = context;
Initialize();
}
private ExecutionContext _executionContext;
/// <summary>
/// ExecutionContext for the help system. Different help providers
/// will depend on this to retrieve session related information like
/// session state and command discovery objects.
/// </summary>
/// <value></value>
internal ExecutionContext ExecutionContext
{
get
{
return _executionContext;
}
}
#region Progress Callback
internal delegate void HelpProgressHandler(object sender, HelpProgressInfo arg);
internal event HelpProgressHandler OnProgress;
#endregion
#region Initialization
/// <summary>
/// Initialize help system with an execution context. If the execution context
/// matches the execution context of current singleton HelpSystem object, nothing
/// needs to be done. Otherwise, a new singleton HelpSystem object will be created
/// with the new execution context.
/// </summary>
internal void Initialize()
{
_verboseHelpErrors = LanguagePrimitives.IsTrue(
_executionContext.GetVariableValue(SpecialVariables.VerboseHelpErrorsVarPath, false));
_helpErrorTracer = new HelpErrorTracer(this);
InitializeHelpProviders();
}
#endregion Initialization
#region Help API
/// <summary>
/// Get Help api function. This is the basic form of the Help API using help
/// request.
///
/// Variants of this function are defined below, which will create help request
/// object on fly.
/// </summary>
/// <param name="helpRequest">helpRequest object</param>
/// <returns>An array of HelpInfo object</returns>
internal IEnumerable<HelpInfo> GetHelp(HelpRequest helpRequest)
{
if (helpRequest == null)
return null;
helpRequest.Validate();
ValidateHelpCulture();
return this.DoGetHelp(helpRequest);
}
#endregion Help API
#region Error Handling
private Collection<ErrorRecord> _lastErrors = new Collection<ErrorRecord>();
/// <summary>
/// This is for tracking the last set of errors happened during the help
/// search.
/// </summary>
/// <value></value>
internal Collection<ErrorRecord> LastErrors
{
get
{
return _lastErrors;
}
}
private HelpCategory _lastHelpCategory = HelpCategory.None;
/// <summary>
/// This is the help category to search for help for the last command.
/// </summary>
/// <value>help category to search for help</value>
internal HelpCategory LastHelpCategory
{
get
{
return _lastHelpCategory;
}
}
#endregion
#region Configuration
private bool _verboseHelpErrors = false;
/// <summary>
/// VerboseHelpErrors is used in the case when end user is interested
/// to know all errors happened during a help search. This property
/// is false by default.
///
/// If this property is turned on (by setting session variable "VerboseHelpError"),
/// following two behaviours will be different,
/// a. Help errors will be written to error pipeline regardless the situation.
/// (Normally, help errors will be written to error pipeline if there is no
/// help found and there is no wildcard in help search target).
/// b. Some additional warnings, including maml processing warnings, will be
/// written to error pipeline.
/// </summary>
/// <value></value>
internal bool VerboseHelpErrors
{
get
{
return _verboseHelpErrors;
}
}
#endregion
#region Help Engine
// Cache of search paths that are currently active.
// This will save a lot time when help providers do their searching
private Collection<String> _searchPaths = null;
/// <summary>
/// Gets the search paths for external snapins/modules that are currently loaded.
/// If the current shell is single-shell based, then the returned
/// search path contains all the directories of currently active PSSnapIns/modules.
/// </summary>
/// <returns>a collection of strings representing locations</returns>
internal Collection<string> GetSearchPaths()
{
// return the cache if already present.
if (null != _searchPaths)
{
return _searchPaths;
}
_searchPaths = new Collection<String>();
RunspaceConfigForSingleShell runspace = this.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell;
if (null != runspace)
{
// SingleShell case. Check active snapins...
MshConsoleInfo currentConsole = runspace.ConsoleInfo;
if ((null == currentConsole) || (null == currentConsole.ExternalPSSnapIns))
{
return _searchPaths;
}
foreach (PSSnapInInfo snapin in currentConsole.ExternalPSSnapIns)
{
_searchPaths.Add(snapin.ApplicationBase);
}
}
// add loaded modules paths to the search path
if (null != ExecutionContext.Modules)
{
foreach (PSModuleInfo loadedModule in ExecutionContext.Modules.ModuleTable.Values)
{
if (!_searchPaths.Contains(loadedModule.ModuleBase))
{
_searchPaths.Add(loadedModule.ModuleBase);
}
}
}
return _searchPaths;
}
/// <summary>
/// Get help based on the target, help type, etc
///
/// Help engine retrieve help based on following schemes,
///
/// 1. if help target is empty, get default help
/// 2. if help target is not a search pattern, try to retrieve exact help
/// 3. if help target is a search pattern or step 2 returns no helpInfo, try to search for help
/// (Search for pattern in command name followed by pattern match in help content)
/// 4. if step 3 returns exact one helpInfo object, try to retrieve exact help.
///
/// </summary>
/// <param name="helpRequest">Help request object</param>
/// <returns>An array of HelpInfo object</returns>
private IEnumerable<HelpInfo> DoGetHelp(HelpRequest helpRequest)
{
_lastErrors.Clear();
// Reset SearchPaths
_searchPaths = null;
_lastHelpCategory = helpRequest.HelpCategory;
if (String.IsNullOrEmpty(helpRequest.Target))
{
HelpInfo helpInfo = GetDefaultHelp();
if (helpInfo != null)
{
yield return helpInfo;
}
yield return null;
}
else
{
bool isMatchFound = false;
if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))
{
foreach (HelpInfo helpInfo in ExactMatchHelp(helpRequest))
{
isMatchFound = true;
yield return helpInfo;
}
}
if (!isMatchFound)
{
foreach (HelpInfo helpInfo in SearchHelp(helpRequest))
{
isMatchFound = true;
yield return helpInfo;
}
if (!isMatchFound)
{
// Throwing exception here may not be the
// best thing to do. Instead we can choose to
// a. give a hint
// b. just silently return an empty search result.
// Solution:
// If it is an exact help target, throw exception.
// Otherwise, return empty result set.
if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target) && this.LastErrors.Count == 0)
{
Exception e = new HelpNotFoundException(helpRequest.Target);
ErrorRecord errorRecord = new ErrorRecord(e, "HelpNotFound", ErrorCategory.ResourceUnavailable, null);
this.LastErrors.Add(errorRecord);
yield break;
}
}
}
}
}
/// <summary>
/// Get help that exactly match the target.
///
/// If the helpInfo returned is not complete, we will forward the
/// helpInfo object to appropriate help provider for further processing.
/// (this is implemented by ForwardHelp)
///
/// </summary>
/// <param name="helpRequest">Help request object</param>
/// <returns>HelpInfo object retrieved. Can be Null.</returns>
internal IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
bool isHelpInfoFound = false;
for (int i = 0; i < this.HelpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)this.HelpProviders[i];
if ((helpProvider.HelpCategory & helpRequest.HelpCategory) > 0)
{
foreach (HelpInfo helpInfo in helpProvider.ExactMatchHelp(helpRequest))
{
isHelpInfoFound = true;
foreach (HelpInfo fwdHelpInfo in ForwardHelp(helpInfo, helpRequest))
{
yield return fwdHelpInfo;
}
}
}
// Bug Win7 737383: Win7 RTM shows both function and cmdlet help when there is
// function and cmdlet with the same name. So, ignoring the ScriptCommandHelpProvider's
// results and going to the CommandHelpProvider for further evaluation.
if (isHelpInfoFound && (!(helpProvider is ScriptCommandHelpProvider)))
{
// once helpInfo found from a provider..no need to traverse other providers.
yield break;
}
}
}
/// <summary>
/// Forward help to the help provider with type forwardHelpCategory.
///
/// This is used in the following known scenarios so far
/// 1. Alias: helpInfo returned by Alias is not what end user needed.
/// The real help can be retrieved from Command help provider.
///
/// </summary>
/// <param name="helpInfo"></param>
/// <param name="helpRequest">Help request object</param>
/// <returns>Never returns null.</returns>
/// <remarks>helpInfos is not null or empty.</remarks>
private IEnumerable<HelpInfo> ForwardHelp(HelpInfo helpInfo, HelpRequest helpRequest)
{
Collection<HelpInfo> result = new Collection<HelpInfo>();
// findout if this helpInfo needs to be processed further..
if (helpInfo.ForwardHelpCategory == HelpCategory.None && string.IsNullOrEmpty(helpInfo.ForwardTarget))
{
// this helpInfo is final...so store this in result
// and move on..
yield return helpInfo;
}
else
{
// Find out a capable provider to process this request...
HelpCategory forwardHelpCategory = helpInfo.ForwardHelpCategory;
bool isHelpInfoProcessed = false;
for (int i = 0; i < this.HelpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)this.HelpProviders[i];
if ((helpProvider.HelpCategory & forwardHelpCategory) != HelpCategory.None)
{
isHelpInfoProcessed = true;
// If this help info is processed by this provider already, break
// out of the provider loop...
foreach (HelpInfo fwdResult in helpProvider.ProcessForwardedHelp(helpInfo, helpRequest))
{
// Add each helpinfo to our repository
foreach (HelpInfo fHelpInfo in ForwardHelp(fwdResult, helpRequest))
{
yield return fHelpInfo;
}
// get out of the provider loop..
yield break;
}
}
}
if (!isHelpInfoProcessed)
{
// we are here because no help provider processed the helpinfo..
// so add this to our repository..
yield return helpInfo;
}
}
}
/// <summary>
/// Get the default help info (normally when help target is empty).
/// </summary>
/// <returns></returns>
private HelpInfo GetDefaultHelp()
{
HelpRequest helpRequest = new HelpRequest("default", HelpCategory.DefaultHelp);
foreach (HelpInfo helpInfo in ExactMatchHelp(helpRequest))
{
// return just the first helpInfo object
return helpInfo;
}
return null;
}
/// <summary>
/// Get help that exactly match the target
/// </summary>
/// <param name="helpRequest">help request object</param>
/// <returns>An IEnumerable of HelpInfo object</returns>
private IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest)
{
int countOfHelpInfosFound = 0;
bool searchInHelpContent = false;
bool shouldBreak = false;
HelpProgressInfo progress = new HelpProgressInfo();
progress.Activity = StringUtil.Format(HelpDisplayStrings.SearchingForHelpContent, helpRequest.Target);
progress.Completed = false;
progress.PercentComplete = 0;
try
{
OnProgress(this, progress);
// algorithm:
// 1. Search for pattern (helpRequest.Target) in command name
// 2. If Step 1 fails then search for pattern in help content
do
{
// we should not continue the search loop if we are
// searching in the help content (as this is the last step
// in our search algorithm).
if (searchInHelpContent)
{
shouldBreak = true;
}
for (int i = 0; i < this.HelpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)this.HelpProviders[i];
if ((helpProvider.HelpCategory & helpRequest.HelpCategory) > 0)
{
foreach (HelpInfo helpInfo in helpProvider.SearchHelp(helpRequest, searchInHelpContent))
{
if (_executionContext.CurrentPipelineStopping)
{
yield break;
}
countOfHelpInfosFound++;
yield return helpInfo;
if ((countOfHelpInfosFound >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0))
{
yield break;
}
}
}
}
// no need to do help content search once we have some help topics
// with command name search.
if (countOfHelpInfosFound > 0)
{
yield break;
}
// appears that we did not find any help matching command names..look for
// pattern in help content.
searchInHelpContent = true;
if (this.HelpProviders.Count > 0)
{
progress.PercentComplete += (100 / this.HelpProviders.Count);
OnProgress(this, progress);
}
} while (!shouldBreak);
}
finally
{
progress.Completed = true;
progress.PercentComplete = 100;
OnProgress(this, progress);
}
}
#endregion Help Engine
#region Help Provider Manager
private ArrayList _helpProviders = new ArrayList();
/// <summary>
/// return the list of help providers initialized
/// </summary>
/// <value>a list of help providers</value>
internal ArrayList HelpProviders
{
get
{
return _helpProviders;
}
}
/// <summary>
/// Initialize help providers.
/// </summary>
/// <remarks>
/// Currently we hardcode the sequence of help provider initialization.
/// In the longer run, we probably will load help providers based on some provider catalog. That
/// will allow new providers to be defined by customer.
/// </remarks>
private void InitializeHelpProviders()
{
HelpProvider helpProvider = null;
helpProvider = new AliasHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new ScriptCommandHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new CommandHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new ProviderHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new PSClassHelpProvider(this);
_helpProviders.Add(helpProvider);
/* TH Bug#3141590 - Disable DscResourceHelp for ClientRTM due to perf issue.
#if !CORECLR // TODO:CORECLR Add this back in once we support Get-DscResource
helpProvider = new DscResourceHelpProvider(this);
_helpProviders.Add(helpProvider);
#endif
*/
helpProvider = new HelpFileHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new FaqHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new GlossaryHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new GeneralHelpProvider(this);
_helpProviders.Add(helpProvider);
helpProvider = new DefaultHelpProvider(this);
_helpProviders.Add(helpProvider);
}
#if _HelpProviderReflection
// Eventually we will publicize the provider api and initialize
// help providers using reflection. This is not in v1 right now.
//
private static HelpProviderInfo[] _providerInfos = new HelpProviderInfo[]
{ new HelpProviderInfo("", "AliasHelpProvider", HelpCategory.Alias),
new HelpProviderInfo("", "CommandHelpProvider", HelpCategory.Command),
new HelpProviderInfo("", "ProviderHelpProvider", HelpCategory.Provider),
new HelpProviderInfo("", "OverviewHelpProvider", HelpCategory.Overview),
new HelpProviderInfo("", "GeneralHelpProvider", HelpCategory.General),
new HelpProviderInfo("", "FAQHelpProvider", HelpCategory.FAQ),
new HelpProviderInfo("", "GlossaryHelpProvider", HelpCategory.Glossary),
new HelpProviderInfo("", "HelpFileHelpProvider", HelpCategory.HelpFile),
new HelpProviderInfo("", "DefaultHelpHelpProvider", HelpCategory.DefaultHelp)
};
private void InitializeHelpProviders()
{
for (int i = 0; i < _providerInfos.Length; i++)
{
HelpProvider helpProvider = GetHelpProvider(_providerInfos[i]);
if (helpProvider != null)
{
helpProvider.Initialize(this._executionContext);
_helpProviders.Add(helpProvider);
}
}
}
private HelpProvider GetHelpProvider(HelpProviderInfo providerInfo)
{
Assembly providerAssembly = null;
if (String.IsNullOrEmpty(providerInfo.AssemblyName))
{
providerAssembly = Assembly.GetExecutingAssembly();
}
else
{
providerAssembly = Assembly.Load(providerInfo.AssemblyName);
}
try
{
if (providerAssembly != null)
{
HelpProvider helpProvider =
(HelpProvider)providerAssembly.CreateInstance(providerInfo.ClassName,
false, // don't ignore case
BindingFlags.CreateInstance,
null, // use default binder
null,
null, // use current culture
null // no special activation attributes
);
return helpProvider;
}
}
catch (TargetInvocationException e)
{
System.Console.WriteLine(e.Message);
if (e.InnerException != null)
{
System.Console.WriteLine(e.InnerException.Message);
System.Console.WriteLine(e.InnerException.StackTrace);
}
}
return null;
}
#endif
#endregion Help Provider Manager
#region Help Error Tracer
private HelpErrorTracer _helpErrorTracer;
/// <summary>
/// The error tracer for this help system
/// </summary>
/// <value></value>
internal HelpErrorTracer HelpErrorTracer
{
get
{
return _helpErrorTracer;
}
}
/// <summary>
/// Start a trace frame for a help file
/// </summary>
/// <param name="helpFile"></param>
/// <returns></returns>
internal IDisposable Trace(string helpFile)
{
if (_helpErrorTracer == null)
return null;
return _helpErrorTracer.Trace(helpFile);
}
/// <summary>
/// Trace an error within a help frame, which is tracked by help tracer itself.
/// </summary>
/// <param name="errorRecord"></param>
internal void TraceError(ErrorRecord errorRecord)
{
if (_helpErrorTracer == null)
return;
_helpErrorTracer.TraceError(errorRecord);
}
/// <summary>
/// Trace a collection of errors within a help frame, which is tracked by
/// help tracer itself.
/// </summary>
/// <param name="errorRecords"></param>
internal void TraceErrors(Collection<ErrorRecord> errorRecords)
{
if (_helpErrorTracer == null || errorRecords == null)
return;
_helpErrorTracer.TraceErrors(errorRecords);
}
#endregion
#region Help MUI
private CultureInfo _culture;
/// <summary>
/// Before each help request is serviced, current thread culture will validate
/// against the current culture of help system. If there is a miss match, each
/// help provider will be notified of the culture change.
/// </summary>
private void ValidateHelpCulture()
{
CultureInfo culture = CultureInfo.CurrentUICulture;
if (_culture == null)
{
_culture = culture;
return;
}
if (_culture.Equals(culture))
{
return;
}
_culture = culture;
ResetHelpProviders();
}
/// <summary>
/// Reset help providers providers. This normally corresponds to help culture change.
///
/// Normally help providers will remove cached help content to make sure new help
/// requests will be served with content of right culture.
///
/// </summary>
internal void ResetHelpProviders()
{
if (_helpProviders == null)
return;
for (int i = 0; i < _helpProviders.Count; i++)
{
HelpProvider helpProvider = (HelpProvider)_helpProviders[i];
helpProvider.Reset();
}
return;
}
#endregion
#region ScriptBlock Parse Tokens Caching/Clearing Functionality
private readonly Lazy<Dictionary<Ast, Token[]>> _scriptBlockTokenCache = new Lazy<Dictionary<Ast, Token[]>>(isThreadSafe: true);
internal Dictionary<Ast, Token[]> ScriptBlockTokenCache
{
get { return _scriptBlockTokenCache.Value; }
}
internal void ClearScriptBlockTokenCache()
{
if (_scriptBlockTokenCache.IsValueCreated)
{
_scriptBlockTokenCache.Value.Clear();
}
}
#endregion
}
/// <summary>
/// Help progress info
/// </summary>
internal class HelpProgressInfo
{
internal bool Completed;
internal string Activity;
internal int PercentComplete;
}
/// <summary>
/// This is the structure to keep track of HelpProvider Info.
/// </summary>
internal class HelpProviderInfo
{
internal string AssemblyName = "";
internal string ClassName = "";
internal HelpCategory HelpCategory = HelpCategory.None;
/// <summary>
/// Constructor
/// </summary>
/// <param name="assemblyName">assembly that contains this help provider</param>
/// <param name="className">the class that implements this help provider</param>
/// <param name="helpCategory">help category of this help provider</param>
internal HelpProviderInfo(string assemblyName, string className, HelpCategory helpCategory)
{
this.AssemblyName = assemblyName;
this.ClassName = className;
this.HelpCategory = helpCategory;
}
}
/// <summary>
/// Help categories
/// </summary>
[Flags]
internal enum HelpCategory
{
/// <summary>
/// Undefined help category
/// </summary>
None = 0x00,
/// <summary>
/// Alias help
/// </summary>
Alias = 0x01,
/// <summary>
/// Cmdlet help
/// </summary>
Cmdlet = 0x02,
/// <summary>
/// Provider help
/// </summary>
Provider = 0x04,
/// <summary>
/// General keyword help
/// </summary>
General = 0x10,
/// <summary>
/// FAQ's
/// </summary>
FAQ = 0x20,
/// <summary>
/// Glossary and term definitions
/// </summary>
Glossary = 0x40,
/// <summary>
/// Help that is contained in help file
/// </summary>
HelpFile = 0x80,
/// <summary>
/// Help from a script block
/// </summary>
ScriptCommand = 0x100,
/// <summary>
/// Help for a function
/// </summary>
Function = 0x200,
/// <summary>
/// Help for a filter
/// </summary>
Filter = 0x400,
/// <summary>
/// Help for an external script (i.e. for a *.ps1 file)
/// </summary>
ExternalScript = 0x800,
/// <summary>
/// All help categories.
/// </summary>
All = 0xFFFFF,
///<summary>
/// Default Help
/// </summary>
DefaultHelp = 0x1000,
///<summary>
/// Help for a Workflow
/// </summary>
Workflow = 0x2000,
///<summary>
/// Help for a Configuration
/// </summary>
Configuration = 0x4000,
/// <summary>
/// Help for DSC Resource
/// </summary>
DscResource = 0x8000,
/// <summary>
/// Help for PS Classes
/// </summary>
Class = 0x10000
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
namespace System.Management.Automation
{
/// <summary>
/// Enumerates the items matching a particular name in the scopes specified using
/// the appropriate scoping lookup rules.
/// </summary>
///
/// <typeparam name="T">
/// The type of items that the derived class returns.
/// </typeparam>
///
internal abstract class ScopedItemSearcher<T> : IEnumerator<T>, IEnumerable<T>
{
#region ctor
/// <summary>
/// Constructs a scoped item searcher.
/// </summary>
///
/// <param name="sessionState">
/// The state of the engine instance to enumerate through the scopes.
/// </param>
///
/// <param name="lookupPath">
/// The parsed name of the item to lookup.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="sessionState"/> or <paramref name="lookupPath"/>
/// is null.
/// </exception>
///
internal ScopedItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath)
{
if (sessionState == null)
{
throw PSTraceSource.NewArgumentNullException("sessionState");
}
if (lookupPath == null)
{
throw PSTraceSource.NewArgumentNullException("lookupPath");
}
this.sessionState = sessionState;
_lookupPath = lookupPath;
InitializeScopeEnumerator();
}
#endregion ctor
#region IEnumerable/IEnumerator members
/// <summary>
/// Gets the current object as an IEnumerator
/// </summary>
///
/// <returns>
/// The current object as an IEnumerator.
/// </returns>
///
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()
{
return this;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this;
}
/// <summary>
/// Moves the enumerator to the next matching scoped item.
/// </summary>
///
/// <returns>
/// True if another matching scoped item was found, or false otherwise.
/// </returns>
///
public bool MoveNext()
{
bool result = true;
if (!_isInitialized)
{
InitializeScopeEnumerator();
}
// Enumerate the scopes until a matching scoped item is found
while (_scopeEnumerable.MoveNext())
{
T newCurrentItem;
if (TryGetNewScopeItem(((IEnumerator<SessionStateScope>)_scopeEnumerable).Current, out newCurrentItem))
{
_currentScope = ((IEnumerator<SessionStateScope>)_scopeEnumerable).Current;
_current = newCurrentItem;
result = true;
break;
}
result = false;
if (_isSingleScopeLookup)
{
break;
}
}
return result;
}
/// <summary>
/// Gets the current scoped item
/// </summary>
///
T IEnumerator<T>.Current
{
get
{
return _current;
}
}
public object Current
{
get
{
return _current;
}
}
public void Reset()
{
InitializeScopeEnumerator();
}
public void Dispose()
{
_current = default(T);
_scopeEnumerable.Dispose();
_scopeEnumerable = null;
_isInitialized = false;
GC.SuppressFinalize(this);
}
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
///
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
///
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
///
/// <param name="newCurrentItem">
/// The scope item that the derived class should return.
/// </param>
///
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
///
protected abstract bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out T newCurrentItem);
#endregion IEnumerable/IEnumerator members
/// <summary>
/// Gets the lookup scope that the Current item was found in.
/// </summary>
///
internal SessionStateScope CurrentLookupScope
{
get { return _currentScope; }
}
private SessionStateScope _currentScope;
/// <summary>
/// Gets the scope in which the search begins.
/// </summary>
///
internal SessionStateScope InitialScope
{
get { return _initialScope; }
}
private SessionStateScope _initialScope;
#region private members
private bool TryGetNewScopeItem(
SessionStateScope lookupScope,
out T newCurrentItem)
{
bool result = GetScopeItem(
lookupScope,
_lookupPath,
out newCurrentItem);
return result;
}
private void InitializeScopeEnumerator()
{
// Define the lookup scope and if we have to do single
// level or dynamic lookup based on the lookup variable
_initialScope = sessionState.CurrentScope;
if (_lookupPath.IsGlobal)
{
_initialScope = sessionState.GlobalScope;
_isSingleScopeLookup = true;
}
else if (_lookupPath.IsLocal ||
_lookupPath.IsPrivate)
{
_initialScope = sessionState.CurrentScope;
_isSingleScopeLookup = true;
}
else if (_lookupPath.IsScript)
{
_initialScope = sessionState.ScriptScope;
_isSingleScopeLookup = true;
}
_scopeEnumerable =
new SessionStateScopeEnumerator(_initialScope);
_isInitialized = true;
}
private T _current;
protected SessionStateInternal sessionState;
private VariablePath _lookupPath;
private SessionStateScopeEnumerator _scopeEnumerable;
private bool _isSingleScopeLookup;
private bool _isInitialized;
#endregion private members
} // class ScopedItemSearcher
/// <summary>
/// The scope searcher for variables
/// </summary>
internal class VariableScopeItemSearcher : ScopedItemSearcher<PSVariable>
{
public VariableScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath,
CommandOrigin origin) : base(sessionState, lookupPath)
{
_origin = origin;
}
private readonly CommandOrigin _origin;
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
///
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
///
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
///
/// <param name="variable">
/// The scope item that the derived class should return.
/// </param>
///
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
///
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out PSVariable variable)
{
Diagnostics.Assert(!(name is FunctionLookupPath),
"name was scanned incorrect if we get here and it is a FunctionLookupPath");
bool result = true;
variable = scope.GetVariable(name.QualifiedName, _origin);
// If the variable is private and the lookup scope
// isn't the current scope, claim that the variable
// doesn't exist so that the lookup continues.
if (variable == null ||
(variable.IsPrivate &&
scope != sessionState.CurrentScope))
{
result = false;
}
return result;
}
} // VariableScopeItemSearcher
/// <summary>
/// The scope searcher for aliases
/// </summary>
internal class AliasScopeItemSearcher : ScopedItemSearcher<AliasInfo>
{
public AliasScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath) : base(sessionState, lookupPath)
{
}
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
///
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
///
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
///
/// <param name="alias">
/// The scope item that the derived class should return.
/// </param>
///
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
///
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out AliasInfo alias)
{
Diagnostics.Assert(!(name is FunctionLookupPath),
"name was scanned incorrect if we get here and it is a FunctionLookupPath");
bool result = true;
alias = scope.GetAlias(name.QualifiedName);
// If the alias is private and the lookup scope
// isn't the current scope, claim that the alias
// doesn't exist so that the lookup continues.
if (alias == null ||
((alias.Options & ScopedItemOptions.Private) != 0 &&
scope != sessionState.CurrentScope))
{
result = false;
}
return result;
}
} // AliasScopeItemSearcher
/// <summary>
/// The scope searcher for functions
/// </summary>
internal class FunctionScopeItemSearcher : ScopedItemSearcher<FunctionInfo>
{
public FunctionScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath,
CommandOrigin origin) : base(sessionState, lookupPath)
{
_origin = origin;
}
private readonly CommandOrigin _origin;
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
///
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
///
/// <param name="path">
/// The name of the item to retrieve.
/// </param>
///
/// <param name="script">
/// The scope item that the derived class should return.
/// </param>
///
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
///
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath path,
out FunctionInfo script)
{
Diagnostics.Assert(path is FunctionLookupPath,
"name was scanned incorrect if we get here and it is not a FunctionLookupPath");
bool result = true;
_name = path.IsFunction ? path.UnqualifiedPath : path.QualifiedName;
script = scope.GetFunction(_name);
if (script != null)
{
bool isPrivate;
FilterInfo filterInfo = script as FilterInfo;
if (filterInfo != null)
{
isPrivate = (filterInfo.Options & ScopedItemOptions.Private) != 0;
}
else
{
isPrivate = (script.Options & ScopedItemOptions.Private) != 0;
}
// If the function is private and the lookup scope
// isn't the current scope, claim that the function
// doesn't exist so that the lookup continues.
if (isPrivate &&
scope != sessionState.CurrentScope)
{
result = false;
}
else
{
// Now check the visibility of the variable...
SessionState.ThrowIfNotVisible(_origin, script);
}
}
else
{
result = false;
}
return result;
}
internal string Name
{
get { return _name; }
}
private string _name = String.Empty;
} // FunctionScopeItemSearcher
/// <summary>
/// The scope searcher for drives
/// </summary>
internal class DriveScopeItemSearcher : ScopedItemSearcher<PSDriveInfo>
{
public DriveScopeItemSearcher(
SessionStateInternal sessionState,
VariablePath lookupPath) : base(sessionState, lookupPath)
{
}
/// <summary>
/// Derived classes override this method to return their
/// particular type of scoped item.
/// </summary>
///
/// <param name="scope">
/// The scope to look the item up in.
/// </param>
///
/// <param name="name">
/// The name of the item to retrieve.
/// </param>
///
/// <param name="drive">
/// The scope item that the derived class should return.
/// </param>
///
/// <returns>
/// True if the scope item was found or false otherwise.
/// </returns>
///
protected override bool GetScopeItem(
SessionStateScope scope,
VariablePath name,
out PSDriveInfo drive)
{
Diagnostics.Assert(!(name is FunctionLookupPath),
"name was scanned incorrect if we get here and it is a FunctionLookupPath");
bool result = true;
drive = scope.GetDrive(name.DriveName);
if (drive == null)
{
result = false;
}
return result;
}
} // DriveScopeItemSearcher
} // namespace System.Management.Automation
| |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Rynchodon.Autopilot.Data;
using Rynchodon.Threading;
using Rynchodon.Utility;
using Rynchodon.Utility.Vectors;
using Sandbox.Common.ObjectBuilders;
using Sandbox.Game.Entities;
using Sandbox.ModAPI;
using Sandbox.ModAPI.Interfaces;
using VRage;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRageMath;
namespace Rynchodon.Autopilot.Movement
{
/// <summary>
/// Tracks the direction and power of a grids thrusters.
/// </summary>
public class ThrustProfiler
{
public struct ForceInDirection
{
public Base6Directions.Direction Direction;
public float Force;
public override string ToString()
{
return "Direction: " + Direction + ", Force: " + Force;
}
}
private const float maxThrustOverrideValue = 100f, minThrustOverrideValue = 1f;
private static ITerminalProperty<float> TP_ThrustOverride;
private IMyCubeBlock m_autopilot;
private IMyCubeGrid myGrid;
private MyPlanet m_planetAtmos;
private float m_airDensity;
private float? m_gravStrength;
private ulong m_nextUpdate;
private FastResourceLock lock_thrustersInDirection = new FastResourceLock();
private List<MyThrust>[] m_thrustersInDirection = new List<MyThrust>[6];
private float[] m_totalThrustForce = new float[6];
/// <summary>Direction with strongest thrusters.</summary>
private ForceInDirection m_primaryForce = new ForceInDirection() { Direction = Base6Directions.Direction.Forward };
/// <summary>Direction, perpendicular to primary, with strongest thrusters.</summary>
private ForceInDirection m_secondaryForce = new ForceInDirection() { Direction = Base6Directions.Direction.Up };
public IMyCubeGrid Grid { get { return myGrid; } }
/// <summary>Forward is the direction with the strongest thrusters and upward is the direction, perpendicular to forward, that has the strongest thrusters.</summary>
public StandardFlight Standard { get; private set; }
/// <summary>Upward is the direction with the strongest thrusters and forward is the direction, perpendicular to upward, that has the strongest thrusters.</summary>
public StandardFlight Gravity { get; private set; }
/// <summary>Maximum force of thrusters in direction of Standard's forward.</summary>
public float PrimaryForce { get { return m_primaryForce.Force; } }
/// <summary>Maximum force of thrusters in direction of Standard's upward.</summary>
public float SecondaryForce { get { return m_secondaryForce.Force; } }
/// <summary>Gravitational acceleration in grid space.</summary>
public DirectionGrid LocalGravity { get; private set; }
/// <summary>Gravitational acceleration in world space.</summary>
public DirectionWorld WorldGravity { get; private set; }
/// <summary>Thrust ratio to conteract gravity.</summary>
public DirectionGrid GravityReactRatio { get; private set; }
/// <summary>The ship has thrusters that can operate effectively in atmosphere.</summary>
public bool CapableAtmo { get; private set; }
/// <summary>The ship has thrusters that can operate effectively in space.</summary>
public bool CapableSpace { get; private set; }
public float GravityStrength
{
get
{
if (!m_gravStrength.HasValue)
m_gravStrength = WorldGravity.vector.Length();
return m_gravStrength.Value;
}
}
private Logable Log { get { return new Logable(m_autopilot); } }
public ThrustProfiler(IMyCubeBlock autopilot)
{
if (autopilot == null)
throw new NullReferenceException("autopilot");
m_autopilot = autopilot;
myGrid = autopilot.CubeGrid;
Standard = new StandardFlight(autopilot, Base6Directions.Direction.Forward, Base6Directions.Direction.Up);
Gravity = new StandardFlight(autopilot, Base6Directions.Direction.Up, Base6Directions.Direction.Forward);
for (int i = 0; i < 6; i++)
m_thrustersInDirection[i] = new List<MyThrust>();
CubeGridCache cache = CubeGridCache.GetFor(myGrid);
if (cache == null)
return;
foreach (MyThrust thrust in cache.BlocksOfType(typeof(MyObjectBuilder_Thrust)))
newThruster(thrust);
myGrid.OnBlockAdded += grid_OnBlockAdded;
myGrid.OnBlockRemoved += grid_OnBlockRemoved;
MyAPIGateway.Utilities.InvokeOnGameThread(ClearOverrides);
}
/// <summary>
/// Adds thruster to thrustersInDirection
/// </summary>
/// <param name="thruster">The new thruster</param>
private void newThruster(MyThrust thruster)
{
Log.DebugLog("thruster == null", Logger.severity.ERROR, condition: thruster == null);
if (TP_ThrustOverride == null)
TP_ThrustOverride = thruster.GetProperty("Override") as ITerminalProperty<float>;
using (lock_thrustersInDirection.AcquireExclusiveUsing())
m_thrustersInDirection[(int)Base6Directions.GetFlippedDirection(thruster.Orientation.Forward)].Add(thruster);
if (TP_ThrustOverride.GetValue(thruster) != 0f)
TP_ThrustOverride.SetValue(thruster, 0f);
}
/// <summary>
/// if added is a thruster, call newThruster()
/// </summary>
/// <param name="added">block that was added</param>
private void grid_OnBlockAdded(IMySlimBlock added)
{
MyThrust thrust = added.FatBlock as MyThrust;
if (thrust == null)
return;
try { newThruster(thrust); }
catch (Exception e)
{ Log.AlwaysLog("Exception: " + e, Logger.severity.ERROR); }
}
/// <summary>
/// if removed is a thruster, remove it from thrustersInDirection
/// </summary>
/// <remarks>
/// if a working block is destroyed, block_IsWorkingChange() is called first
/// </remarks>
/// <param name="removed">block that was removed</param>
private void grid_OnBlockRemoved(IMySlimBlock removed)
{
try
{
if (removed.FatBlock == null)
return;
MyThrust asThrust = removed.FatBlock as MyThrust;
if (asThrust == null)
return;
using (lock_thrustersInDirection.AcquireExclusiveUsing())
m_thrustersInDirection[(int)Base6Directions.GetFlippedDirection(asThrust.Orientation.Forward)].Remove(asThrust);
Log.DebugLog("removed thruster = " + removed.FatBlock.DefinitionDisplayNameText + "/" + asThrust.DisplayNameText, Logger.severity.DEBUG);
return;
}
catch (Exception e)
{ Log.AlwaysLog("Exception: " + e, Logger.severity.ERROR); }
}
/// <summary>
/// get the force in a direction
/// </summary>
/// <param name="direction">the direction of force / acceleration</param>
public float GetForceInDirection(Base6Directions.Direction direction, bool adjustForGravity = false)
{
float force = m_totalThrustForce[(int)direction];
if (adjustForGravity)
{
float change = Base6Directions.GetVector(direction).Dot(LocalGravity) * myGrid.Physics.Mass;
//Log.DebugLog("For direction " + direction + ", and force " + force + ", Gravity adjusts available force by " + change + ", after adjustment: " + (force + change), "GetForceInDirection()");
force += change;
}
//Log.DebugLog("direction: " + direction + "(" + (int)direction + ")" + ", force: " + force);
return force;
//return Math.Max(force, 1f); // a minimum of 1 N prevents dividing by zero
}
public void Update()
{
// sometimes called from Game Thread when world is loaded, has not been an issue so far
//Log.DebugLog("Not on autopilot thread: " + ThreadTracker.ThreadName + ", from: " + callerPath + "." + callerMember, Logger.severity.ERROR, condition: !ThreadTracker.ThreadName.StartsWith("Autopilot"));
if (Globals.UpdateCount < m_nextUpdate)
return;
m_nextUpdate = Globals.UpdateCount + ShipAutopilot.UpdateFrequency;
//for (int i = m_totalThrustForce.Length - 1; i >= 0; i--)
// m_totalThrustForce[i] = 0f;
CapableAtmo = false; CapableSpace = false;
Vector3D position = myGrid.GetPosition();
bool first = true;
Vector3 worldGravity = Vector3.Zero;
m_planetAtmos = null;
m_airDensity = 0f;
foreach (MyPlanet planet in Globals.AllPlanets())
if (planet.IsPositionInGravityWell(position))
{
if (first)
{
first = false;
m_gravStrength = planet.GetGravityMultiplier(position) * 9.81f;
Vector3 direction = planet.GetWorldGravityNormalized(ref position);
worldGravity = m_gravStrength.Value * direction;
}
else
{
worldGravity += planet.GetWorldGravity(position);
m_gravStrength = null;
}
if (planet.HasAtmosphere)
{
m_airDensity += planet.GetAirDensity(position);
m_planetAtmos = planet;
}
}
CalcForceInDirection(Base6Directions.Direction.Forward);
CalcForceInDirection(Base6Directions.Direction.Backward);
CalcForceInDirection(Base6Directions.Direction.Up);
CalcForceInDirection(Base6Directions.Direction.Down);
CalcForceInDirection(Base6Directions.Direction.Left);
CalcForceInDirection(Base6Directions.Direction.Right);
if (worldGravity.LengthSquared() < 0.01f)
{
//Log.DebugLog("Not in gravity well", "Update()");
WorldGravity = Vector3.Zero;
LocalGravity = Vector3.Zero;
m_gravStrength = 0f;
return;
}
WorldGravity = worldGravity;
LocalGravity = new DirectionGrid() { vector = Vector3.Transform(worldGravity, myGrid.WorldMatrixNormalizedInv.GetOrientation()) };
Vector3 gravityReactRatio = Vector3.Zero;
if (LocalGravity.vector.X > 0)
gravityReactRatio.X = -LocalGravity.vector.X * myGrid.Physics.Mass / GetForceInDirection(Base6Directions.Direction.Left);
else
gravityReactRatio.X = -LocalGravity.vector.X * myGrid.Physics.Mass / GetForceInDirection(Base6Directions.Direction.Right);
if (LocalGravity.vector.Y > 0)
gravityReactRatio.Y = -LocalGravity.vector.Y * myGrid.Physics.Mass / GetForceInDirection(Base6Directions.Direction.Down);
else
gravityReactRatio.Y = -LocalGravity.vector.Y * myGrid.Physics.Mass / GetForceInDirection(Base6Directions.Direction.Up);
if (LocalGravity.vector.Z > 0)
gravityReactRatio.Z = -LocalGravity.vector.Z * myGrid.Physics.Mass / GetForceInDirection(Base6Directions.Direction.Forward);
else
gravityReactRatio.Z = -LocalGravity.vector.Z * myGrid.Physics.Mass / GetForceInDirection(Base6Directions.Direction.Backward);
GravityReactRatio = gravityReactRatio;
Log.DebugLog("Gravity: " + WorldGravity + ", local: " + LocalGravity + ", react: " + gravityReactRatio + ", air density: " + m_airDensity);
}
private float GetThrusterMaxForce(MyThrust thruster)
{
float thrusterForce = thruster.BlockDefinition.ForceMagnitude * (thruster as IMyThrust).ThrustMultiplier;
if (thruster.BlockDefinition.EffectivenessAtMaxInfluence != 1f || thruster.BlockDefinition.EffectivenessAtMinInfluence != 1f)
{
if (!CapableAtmo && thruster.BlockDefinition.EffectivenessAtMaxInfluence > thruster.BlockDefinition.EffectivenessAtMinInfluence)
CapableAtmo = true;
if (!CapableSpace && thruster.BlockDefinition.EffectivenessAtMinInfluence > thruster.BlockDefinition.EffectivenessAtMaxInfluence)
CapableSpace = true;
if (m_airDensity <= thruster.BlockDefinition.MinPlanetaryInfluence)
thrusterForce *= thruster.BlockDefinition.EffectivenessAtMinInfluence;
else if (m_airDensity >= thruster.BlockDefinition.MaxPlanetaryInfluence)
thrusterForce *= thruster.BlockDefinition.EffectivenessAtMaxInfluence;
else
{
float effectRange = thruster.BlockDefinition.EffectivenessAtMaxInfluence - thruster.BlockDefinition.EffectivenessAtMinInfluence;
float influenceRange = thruster.BlockDefinition.MaxPlanetaryInfluence - thruster.BlockDefinition.MinPlanetaryInfluence;
float effectiveness = (m_airDensity - thruster.BlockDefinition.MinPlanetaryInfluence) * effectRange / influenceRange + thruster.BlockDefinition.EffectivenessAtMinInfluence;
//Log.DebugLog("for thruster " + thruster.DisplayNameText + ", effectiveness: " + effectiveness + ", max force: " + thrusterForce + ", effect range: " + effectRange + ", influence range: " + influenceRange);
thrusterForce *= effectiveness;
}
}
else
{
CapableAtmo = true;
CapableSpace = true;
}
return thrusterForce;
}
private float CalcForceInDirection(Base6Directions.Direction direction)
{
float force = 0;
using (lock_thrustersInDirection.AcquireSharedUsing())
foreach (MyThrust thruster in m_thrustersInDirection[(int)direction])
if (!thruster.Closed && thruster.IsWorking)
force += GetThrusterMaxForce(thruster);
m_totalThrustForce[(int)direction] = force;
if (direction == m_primaryForce.Direction)
{
//Log.DebugLog("updating primary force, direction: " + direction + ", force: " + force, "CalcForceInDirection()");
m_primaryForce.Force = force;
}
else if (force > m_primaryForce.Force * 1.1f)
{
Log.DebugLog("stronger than primary force, direction: " + direction + ", force: " + force + ", acceleration: " + force / myGrid.Physics.Mass + ", primary: " + m_primaryForce, Logger.severity.DEBUG);
m_secondaryForce = m_primaryForce;
m_primaryForce.Direction = direction;
m_primaryForce.Force = force;
if (m_secondaryForce.Direction == Base6Directions.GetFlippedDirection(m_primaryForce.Direction))
m_secondaryForce = new ForceInDirection() { Direction = Base6Directions.GetPerpendicular(m_primaryForce.Direction) };
Log.DebugLog("secondary: " + m_secondaryForce);
Standard.SetMatrixOrientation(m_primaryForce.Direction, m_secondaryForce.Direction);
Gravity.SetMatrixOrientation(m_secondaryForce.Direction, m_primaryForce.Direction);
}
else if (direction == m_secondaryForce.Direction)
{
//Log.DebugLog("updating secondary force, direction: " + direction + ", force: " + force, "CalcForceInDirection()");
m_secondaryForce.Force = force;
}
else if (force > m_secondaryForce.Force * 1.1f && direction != Base6Directions.GetFlippedDirection(m_primaryForce.Direction))
{
Log.DebugLog("stronger than secondary force, direction: " + direction + ", force: " + force + ", acceleration: " + force / myGrid.Physics.Mass + ", secondary: " + m_secondaryForce, Logger.severity.DEBUG);
m_secondaryForce.Direction = direction;
m_secondaryForce.Force = force;
Standard.SetMatrixOrientation(m_primaryForce.Direction, m_secondaryForce.Direction);
Gravity.SetMatrixOrientation(m_secondaryForce.Direction, m_primaryForce.Direction);
}
//Log.DebugLog("direction: " + direction + "(" + (int)direction + ")" + ", force: " + force);
return force;
}
#region Override
/// <summary>
/// Set the overrides of thrusters to match MoveForceRatio. Should be called on game thread.
/// </summary>
public void SetOverrides(ref DirectionGrid MoveForceRatio)
{
if (MoveForceRatio.vector.X >= 0f)
{
SetOverrides(Base6Directions.Direction.Right, MoveForceRatio.vector.X);
ClearOverrides(Base6Directions.Direction.Left);
}
else
{
ClearOverrides(Base6Directions.Direction.Right);
SetOverrides(Base6Directions.Direction.Left, -MoveForceRatio.vector.X);
}
if (MoveForceRatio.vector.Y >= 0f)
{
SetOverrides(Base6Directions.Direction.Up, MoveForceRatio.vector.Y);
ClearOverrides(Base6Directions.Direction.Down);
}
else
{
ClearOverrides(Base6Directions.Direction.Up);
SetOverrides(Base6Directions.Direction.Down, -MoveForceRatio.vector.Y);
}
if (MoveForceRatio.vector.Z >= 0f)
{
SetOverrides(Base6Directions.Direction.Backward, MoveForceRatio.vector.Z);
ClearOverrides(Base6Directions.Direction.Forward);
}
else
{
ClearOverrides(Base6Directions.Direction.Backward);
SetOverrides(Base6Directions.Direction.Forward, -MoveForceRatio.vector.Z);
}
}
/// <summary>
/// Set all overrides to zero. Should be called on game thread.
/// </summary>
public void ClearOverrides()
{
ClearOverrides(Base6Directions.Direction.Right);
ClearOverrides(Base6Directions.Direction.Left);
ClearOverrides(Base6Directions.Direction.Up);
ClearOverrides(Base6Directions.Direction.Down);
ClearOverrides(Base6Directions.Direction.Backward);
ClearOverrides(Base6Directions.Direction.Forward);
}
/// <summary>
/// Sets the overrides in a direction to match a particular force ratio.
/// </summary>
private void SetOverrides(Base6Directions.Direction direction, float ratio)
{
float force = GetForceInDirection(direction) * ratio;
// no need to lock thrustersInDirection, it is updated on game thread
foreach (MyThrust thruster in m_thrustersInDirection[(int)direction])
if (!thruster.Closed && thruster.IsWorking)
{
if (force <= 0f)
{
if (TP_ThrustOverride.GetValue(thruster) != 0f)
TP_ThrustOverride.SetValue(thruster, 0f);
continue;
}
float maxForce = GetThrusterMaxForce(thruster);
if (maxForce > force)
{
float overrideValue = Math.Max(force / maxForce * maxThrustOverrideValue, minThrustOverrideValue);
if (TP_ThrustOverride.GetValue(thruster) != overrideValue)
TP_ThrustOverride.SetValue(thruster, overrideValue);
//Log.DebugLog("direction: " + direction + ", thruster: " + thruster.DisplayNameText + ", add partial force " + force + " of " + maxForce + ", overrideValue: " + overrideValue, "SetOverrides()");
force = 0f;
}
else
{
if (TP_ThrustOverride.GetValue(thruster) != maxThrustOverrideValue)
TP_ThrustOverride.SetValue(thruster, maxThrustOverrideValue);
force -= maxForce;
//Log.DebugLog("direction: " + direction + ", thruster at full force: " + thruster.DisplayNameText, "SetOverrides()");
}
}
}
/// <summary>
/// Clears all overrides in a particular direcion.
/// </summary>
private void ClearOverrides(Base6Directions.Direction direction)
{
// no need to lock thrustersInDirection, it is updated on game thread
foreach (MyThrust thruster in m_thrustersInDirection[(int)direction])
if (!thruster.Closed && thruster.IsWorking && TP_ThrustOverride.GetValue(thruster) != 0f)
TP_ThrustOverride.SetValue(thruster, 0f);
}
#endregion Override
/// <summary>
/// Determines if the ship has enough force to accelerate in the specified direction. Checks against gravity.
/// </summary>
/// <param name="accelertation">The minimum acceleration required, in m/s/s</param>
public bool CanMoveDirection(Base6Directions.Direction direction, float acceleration = 1f)
{
Update();
return GetForceInDirection(direction, true) > Grid.Physics.Mass * acceleration;
}
/// <summary>
/// Determines if the ship has enough force to accelerate forward. Checks against gravity.
/// </summary>
/// <param name="acceleration">The ammount of acceleration required, in m/s/s</param>
public bool CanMoveForward(float acceleration = 1f)
{
Update();
return GetForceInDirection(Base6Directions.GetDirection(Standard.LocalMatrix.Forward), true) > Grid.Physics.Mass * acceleration;
}
/// <summary>
/// Determines if the ship has enough force to move in any direction. Checks against gravity.
/// </summary>
/// <param name="acceleration">The minimum acceleration required, in m/s/s</param>
public bool CanMoveAnyDirection(float acceleration = 1f)
{
Update();
float force = Grid.Physics.Mass * acceleration;
foreach (Base6Directions.Direction direction in Base6Directions.EnumDirections)
if (GetForceInDirection(direction, true) < force)
{
Log.DebugLog("Limited thrust in direction: " + direction);
return false;
}
return true;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ToolStripRenderer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.Windows.Forms.Internal;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Windows.Forms.Layout;
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer"]/*' />
public class ToolStripSystemRenderer : ToolStripRenderer {
[ThreadStatic()]
private static VisualStyleRenderer renderer = null;
private ToolStripRenderer toolStripHighContrastRenderer;
public ToolStripSystemRenderer() {
}
internal ToolStripSystemRenderer(bool isDefault) : base(isDefault) {
}
internal override ToolStripRenderer RendererOverride {
get {
if (DisplayInformation.HighContrast) {
return HighContrastRenderer;
}
return null;
}
}
internal ToolStripRenderer HighContrastRenderer {
get {
if (toolStripHighContrastRenderer == null) {
toolStripHighContrastRenderer = new ToolStripHighContrastRenderer(/*renderLikeSystem*/true);
}
return toolStripHighContrastRenderer;
}
}
/// <devdoc>
/// Draw the background color
/// </devdoc>
private static VisualStyleRenderer VisualStyleRenderer {
get {
if (Application.RenderWithVisualStyles) {
if (renderer == null && VisualStyleRenderer.IsElementDefined(VisualStyleElement.ToolBar.Button.Normal)) {
renderer = new VisualStyleRenderer(VisualStyleElement.ToolBar.Button.Normal);
}
}
else {
renderer = null;
}
return renderer;
}
}
/// <devdoc>
/// Fill the item's background as bounded by the rectangle
/// </devdoc>
private static void FillBackground(Graphics g, Rectangle bounds, Color backColor) {
// Fill the background with the item's back color
if (backColor.IsSystemColor) {
g.FillRectangle(SystemBrushes.FromSystemColor(backColor), bounds);
}
else {
using (Brush backBrush = new SolidBrush(backColor)) {
g.FillRectangle(backBrush, bounds);
}
}
}
/// <devdoc>
/// returns true if you are required to dispose the pen
/// </devdoc>
private static bool GetPen(Color color, ref Pen pen) {
if (color.IsSystemColor) {
pen = SystemPens.FromSystemColor(color);
return false;
}
else{
pen = new Pen(color);
return true;
}
}
/// <devdoc>
/// translates the winbar item state into a toolbar state, which is something the renderer understands
/// </devdoc>
private static int GetItemState(ToolStripItem item) {
return (int)GetToolBarState(item);
}
/// <devdoc>
/// translates the winbar item state into a toolbar state, which is something the renderer understands
/// </devdoc>
private static int GetSplitButtonDropDownItemState(ToolStripSplitButton item) {
return (int)GetSplitButtonToolBarState(item, true);
}
/// <devdoc>
/// translates the winbar item state into a toolbar state, which is something the renderer understands
/// </devdoc>
private static int GetSplitButtonItemState(ToolStripSplitButton item) {
return (int)GetSplitButtonToolBarState(item, false);
}
/// <devdoc>
/// translates the winbar item state into a toolbar state, which is something the renderer understands
/// </devdoc>
private static ToolBarState GetSplitButtonToolBarState(ToolStripSplitButton button, bool dropDownButton) {
ToolBarState state = ToolBarState.Normal;
if (button != null) {
if (!button.Enabled) {
state = ToolBarState.Disabled;
}
else if (dropDownButton){
if (button.DropDownButtonPressed || button.ButtonPressed) {
state = ToolBarState.Pressed;
}
else if (button.DropDownButtonSelected || button.ButtonSelected) {
state = ToolBarState.Hot;
}
}
else{
if (button.ButtonPressed) {
state = ToolBarState.Pressed;
}
else if (button.ButtonSelected) {
state = ToolBarState.Hot;
}
}
}
return state;
}
/// <devdoc>
/// translates the winbar item state into a toolbar state, which is something the renderer understands
/// </devdoc>
private static ToolBarState GetToolBarState(ToolStripItem item) {
ToolBarState state = ToolBarState.Normal;
if (item != null) {
if (!item.Enabled) {
state = ToolBarState.Disabled;
}
if (item is ToolStripButton && ((ToolStripButton)item).Checked) {
state = ToolBarState.Checked;
}
else if (item.Pressed) {
state = ToolBarState.Pressed;
}
else if (item.Selected) {
state = ToolBarState.Hot;
}
}
return state;
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderBackground"]/*' />
/// <devdoc>
/// Draw the winbar background. ToolStrip users should override this if they want to draw differently.
/// </devdoc>
protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) {
ToolStrip toolStrip = e.ToolStrip;
Graphics g = e.Graphics;
Rectangle bounds= e.AffectedBounds;
if (!ShouldPaintBackground(toolStrip)) {
return;
}
if (toolStrip is StatusStrip) {
RenderStatusStripBackground(e);
}
else {
if (DisplayInformation.HighContrast) {
FillBackground(g, bounds, SystemColors.ButtonFace);
}
else if (DisplayInformation.LowResolution) {
FillBackground(g, bounds, (toolStrip is ToolStripDropDown) ? SystemColors.ControlLight : e.BackColor);
}
else if (toolStrip.IsDropDown) {
FillBackground(g, bounds, (!ToolStripManager.VisualStylesEnabled) ?
e.BackColor : SystemColors.Menu);
}
else if (toolStrip is MenuStrip) {
FillBackground(g, bounds, (!ToolStripManager.VisualStylesEnabled) ?
e.BackColor : SystemColors.MenuBar);
}
else if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Band.Normal)) {
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
vsRenderer.SetParameters(VisualStyleElement.ToolBar.Bar.Normal);
vsRenderer.DrawBackground(g, bounds);
}
else {
FillBackground(g, bounds, (!ToolStripManager.VisualStylesEnabled) ?
e.BackColor : SystemColors.MenuBar);
}
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderBorder"]/*' />
/// <devdoc>
/// Draw the border around the ToolStrip. This should be done as the last step.
/// </devdoc>
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
ToolStrip toolStrip = e.ToolStrip;
Graphics g = e.Graphics;
Rectangle bounds = e.ToolStrip.ClientRectangle;
if (toolStrip is StatusStrip) {
RenderStatusStripBorder(e);
}
else if (toolStrip is ToolStripDropDown) {
ToolStripDropDown toolStripDropDown = toolStrip as ToolStripDropDown;
// Paint the border for the window depending on whether or not we have a drop shadow effect.
if (toolStripDropDown.DropShadowEnabled && ToolStripManager.VisualStylesEnabled) {
bounds.Width -= 1;
bounds.Height -= 1;
e.Graphics.DrawRectangle(new Pen(SystemColors.ControlDark), bounds);
}
else {
ControlPaint.DrawBorder3D(e.Graphics, bounds, Border3DStyle.Raised);
}
}
else {
if (ToolStripManager.VisualStylesEnabled) {
e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0,bounds.Bottom-1,bounds.Width, bounds.Bottom-1);
e.Graphics.DrawLine(SystemPens.InactiveBorder, 0,bounds.Bottom-2,bounds.Width,bounds.Bottom-2);
}
else {
e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0,bounds.Bottom-1,bounds.Width, bounds.Bottom-1);
e.Graphics.DrawLine(SystemPens.ButtonShadow, 0,bounds.Bottom-2,bounds.Width,bounds.Bottom-2);
}
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderGrip"]/*' />
/// <devdoc>
/// Draw the grip. ToolStrip users should override this if they want to draw differently.
/// </devdoc>
protected override void OnRenderGrip(ToolStripGripRenderEventArgs e) {
Graphics g = e.Graphics;
Rectangle bounds = new Rectangle(Point.Empty, e.GripBounds.Size);
bool verticalGrip = e.GripDisplayStyle == ToolStripGripDisplayStyle.Vertical;
if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Gripper.Normal)) {
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
if (verticalGrip) {
vsRenderer.SetParameters(VisualStyleElement.Rebar.Gripper.Normal);
bounds.Height = ((bounds.Height -2/*number of pixels for border*/) / 4) * 4; // make sure height is an even interval of 4.
bounds.Y = Math.Max(0,(e.GripBounds.Height - bounds.Height -2/*number of pixels for border*/) / 2);
}
else {
vsRenderer.SetParameters(VisualStyleElement.Rebar.GripperVertical.Normal);
}
vsRenderer.DrawBackground(g, bounds);
}
else {
// do some fixup so that we dont paint from end to end.
Color backColor = e.ToolStrip.BackColor;
FillBackground(g, bounds, backColor);
if (verticalGrip) {
if (bounds.Height >= 4) {
bounds.Inflate(0,-2); // scoot down 2PX and start drawing
}
bounds.Width = 3;
}
else {
if (bounds.Width >= 4) {
bounds.Inflate(-2,0); // scoot over 2PX and start drawing
}
bounds.Height = 3;
}
RenderSmall3DBorderInternal(g, bounds, ToolBarState.Hot, (e.ToolStrip.RightToLeft == RightToLeft.Yes));
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderItem"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected override void OnRenderItemBackground(ToolStripItemRenderEventArgs e) {
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderImageMargin"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) {
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderButton"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) {
RenderItemInternal(e);
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderDropDownButton"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected override void OnRenderDropDownButtonBackground(ToolStripItemRenderEventArgs e) {
RenderItemInternal(e);
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderOverflowButton"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected override void OnRenderOverflowButtonBackground(ToolStripItemRenderEventArgs e) {
ToolStripItem item = e.Item;
Graphics g = e.Graphics;
if (ToolStripManager.VisualStylesEnabled && VisualStyleRenderer.IsElementDefined(VisualStyleElement.Rebar.Chevron.Normal)) {
VisualStyleElement chevronElement = VisualStyleElement.Rebar.Chevron.Normal;
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
vsRenderer.SetParameters(chevronElement.ClassName, chevronElement.Part, GetItemState(item));
vsRenderer.DrawBackground(g, new Rectangle(Point.Empty, item.Size));
}
else {
RenderItemInternal(e);
Color arrowColor = item.Enabled ? SystemColors.ControlText : SystemColors.ControlDark;
DrawArrow(new ToolStripArrowRenderEventArgs(g, item, new Rectangle(Point.Empty, item.Size), arrowColor, ArrowDirection.Down));
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderLabel"]/*' />
/// <devdoc>
/// Draw the button background
/// </devdoc>
protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) {
RenderLabelInternal(e);
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderMenuItem"]/*' />
/// <devdoc>
/// Draw the items background
/// </devdoc>
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
ToolStripMenuItem item = e.Item as ToolStripMenuItem;
Graphics g = e.Graphics;
if (item is MdiControlStrip.SystemMenuItem) {
return; // no highlights are painted behind a system menu item
}
//
if (item != null) {
Rectangle bounds = new Rectangle(Point.Empty, item.Size);
if (item.IsTopLevel && !ToolStripManager.VisualStylesEnabled) {
// CLASSIC MODE (3D edges)
// Draw box highlight for toplevel items in downlevel platforms
if (item.BackgroundImage != null) {
ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, item.ContentRectangle, item.ContentRectangle);
}
else if (item.RawBackColor != Color.Empty) {
FillBackground(g, item.ContentRectangle, item.BackColor);
}
// Toplevel menu items do 3D borders.
ToolBarState state = GetToolBarState(item);
RenderSmall3DBorderInternal(g, bounds, state, (item.RightToLeft == RightToLeft.Yes));
}
else {
// XP++ MODE (no 3D edges)
// Draw blue filled highlight for toplevel items in themed platforms
// or items parented to a drop down
Rectangle fillRect = new Rectangle(Point.Empty, item.Size);
if (item.IsOnDropDown) {
// VSWhidbey 518568: scoot in by 2 pixels when selected
fillRect.X += 2;
fillRect.Width -= 3; //its already 1 away from the right edge
}
if (item.Selected || item.Pressed) {
g.FillRectangle(SystemBrushes.Highlight, fillRect);
}
else {
if (item.BackgroundImage != null) {
ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, item.ContentRectangle, fillRect);
}
else if (!ToolStripManager.VisualStylesEnabled && (item.RawBackColor != Color.Empty)) {
FillBackground(g, fillRect, item.BackColor);
}
}
}
}
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderSeparator"]/*' />
/// <devdoc>
/// Draws a toolbar separator. ToolStrip users should override this function to change the
/// drawing of all separators.
/// </devdoc>
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) {
RenderSeparatorInternal(e.Graphics, e.Item, new Rectangle(Point.Empty, e.Item.Size), e.Vertical);
}
/// <include file='doc\WinBarRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderToolStripStatusLabel"]/*' />
protected override void OnRenderToolStripStatusLabelBackground(ToolStripItemRenderEventArgs e) {
RenderLabelInternal(e);
ToolStripStatusLabel item = e.Item as ToolStripStatusLabel;
ControlPaint.DrawBorder3D(e.Graphics, new Rectangle(0,0,item.Width-1, item.Height-1), item.BorderStyle, (Border3DSide)item.BorderSides);
}
/// <include file='doc\ToolStripRenderer.uex' path='docs/doc[@for="ToolStripRenderer.OnRenderSplitButton"]/*' />
/// <devdoc>
/// Draw the item's background.
/// </devdoc>
protected override void OnRenderSplitButtonBackground(ToolStripItemRenderEventArgs e) {
ToolStripSplitButton splitButton = e.Item as ToolStripSplitButton;
Graphics g = e.Graphics;
bool rightToLeft = (splitButton.RightToLeft == RightToLeft.Yes);
Color arrowColor = splitButton.Enabled ? SystemColors.ControlText : SystemColors.ControlDark;
// in right to left - we need to swap the parts so we dont draw v][ toolStripSplitButton
VisualStyleElement splitButtonDropDownPart = (rightToLeft) ? VisualStyleElement.ToolBar.SplitButton.Normal : VisualStyleElement.ToolBar.SplitButtonDropDown.Normal;
VisualStyleElement splitButtonPart = (rightToLeft) ? VisualStyleElement.ToolBar.DropDownButton.Normal : VisualStyleElement.ToolBar.SplitButton.Normal;
Rectangle bounds = new Rectangle(Point.Empty, splitButton.Size);
if (ToolStripManager.VisualStylesEnabled
&& VisualStyleRenderer.IsElementDefined(splitButtonDropDownPart)
&& VisualStyleRenderer.IsElementDefined(splitButtonPart)) {
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
// Draw the SplitButton Button portion of it.
vsRenderer.SetParameters(splitButtonPart.ClassName, splitButtonPart.Part, GetSplitButtonItemState(splitButton));
// the lovely Windows theming for split button comes in three pieces:
// SplitButtonDropDown: [ v |
// Separator: |
// SplitButton: | ]
// this is great except if you want to swap the button in RTL. In this case we need
// to use the DropDownButton instead of the SplitButtonDropDown and paint the arrow ourselves.
Rectangle splitButtonBounds = splitButton.ButtonBounds;
if (rightToLeft) {
// scoot to the left so we dont draw double shadow like so: ][
splitButtonBounds.Inflate(2,0);
}
// Draw the button portion of it.
vsRenderer.DrawBackground(g, splitButtonBounds);
// Draw the SplitButton DropDownButton portion of it.
vsRenderer.SetParameters(splitButtonDropDownPart.ClassName, splitButtonDropDownPart.Part, GetSplitButtonDropDownItemState(splitButton));
// Draw the drop down button portion
vsRenderer.DrawBackground(g, splitButton.DropDownButtonBounds);
// fill in the background image
Rectangle fillRect = splitButton.ContentRectangle;
if (splitButton.BackgroundImage != null) {
ControlPaint.DrawBackgroundImage(g, splitButton.BackgroundImage, splitButton.BackColor, splitButton.BackgroundImageLayout, fillRect, fillRect);
}
// draw the separator over it.
RenderSeparatorInternal(g,splitButton, splitButton.SplitterBounds, true);
// and of course, now if we're in RTL we now need to paint the arrow
// because we're no longer using a part that has it built in.
if (rightToLeft || splitButton.BackgroundImage != null) {
DrawArrow(new ToolStripArrowRenderEventArgs(g, splitButton, splitButton.DropDownButtonBounds, arrowColor, ArrowDirection.Down));
}
}
else {
// Draw the split button button
Rectangle splitButtonButtonRect = splitButton.ButtonBounds;
if (splitButton.BackgroundImage != null) {
// fill in the background image
Rectangle fillRect = (splitButton.Selected) ? splitButton.ContentRectangle :bounds;
if (splitButton.BackgroundImage != null) {
ControlPaint.DrawBackgroundImage(g, splitButton.BackgroundImage, splitButton.BackColor, splitButton.BackgroundImageLayout, bounds, fillRect);
}
}
else {
FillBackground(g,splitButtonButtonRect, splitButton.BackColor);
}
ToolBarState state = GetSplitButtonToolBarState(splitButton, false);
RenderSmall3DBorderInternal(g, splitButtonButtonRect, state, rightToLeft);
// draw the split button drop down
Rectangle dropDownRect = splitButton.DropDownButtonBounds;
// fill the color in the dropdown button
if (splitButton.BackgroundImage == null) {
FillBackground(g, dropDownRect, splitButton.BackColor);
}
state = GetSplitButtonToolBarState(splitButton, true);
if ((state == ToolBarState.Pressed) || (state == ToolBarState.Hot)) {
RenderSmall3DBorderInternal(g, dropDownRect, state, rightToLeft);
}
DrawArrow(new ToolStripArrowRenderEventArgs(g, splitButton, dropDownRect, arrowColor, ArrowDirection.Down));
}
}
/// <devdoc>
/// This exists mainly so that buttons, labels and items, etc can share the same implementation.
/// If OnRenderButton called OnRenderItem we would never be able to change the implementation
/// as it would be a breaking change. If in v1, the user overrode OnRenderItem to draw green triangles
/// and in v2 we decided to add a feature to button that would require us to no longer call OnRenderItem -
/// the user's version of OnRenderItem would not get called when he upgraded his framework. Hence
/// everyone should just call this private shared method. Users need to override each item they want
/// to change the look and feel of.
/// </devdoc>
private void RenderItemInternal(ToolStripItemRenderEventArgs e) {
ToolStripItem item = e.Item;
Graphics g = e.Graphics;
ToolBarState state = GetToolBarState(item);
VisualStyleElement toolBarElement = VisualStyleElement.ToolBar.Button.Normal;
if (ToolStripManager.VisualStylesEnabled
&& (VisualStyleRenderer.IsElementDefined(toolBarElement))) {
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
vsRenderer.SetParameters(toolBarElement.ClassName, toolBarElement.Part, (int)state);
vsRenderer.DrawBackground(g, new Rectangle(Point.Empty, item.Size));
}
else {
RenderSmall3DBorderInternal(g, new Rectangle(Point.Empty, item.Size), state, (item.RightToLeft == RightToLeft.Yes));
}
Rectangle fillRect = item.ContentRectangle;
if (item.BackgroundImage != null) {
ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, fillRect, fillRect);
}
else {
ToolStrip parent = item.GetCurrentParent();
if ((parent != null) && (state != ToolBarState.Checked) && (item.BackColor != parent.BackColor)) {
FillBackground(g, fillRect, item.BackColor);
}
}
}
/// <devdoc>
/// </devdoc>
private void RenderSeparatorInternal(Graphics g, ToolStripItem item, Rectangle bounds, bool vertical) {
VisualStyleElement separator = (vertical) ? VisualStyleElement.ToolBar.SeparatorHorizontal.Normal : VisualStyleElement.ToolBar.SeparatorVertical.Normal;
if (ToolStripManager.VisualStylesEnabled
&& (VisualStyleRenderer.IsElementDefined(separator))){
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
vsRenderer.SetParameters(separator.ClassName, separator.Part, GetItemState(item));
vsRenderer.DrawBackground(g, bounds);
}
else {
Color foreColor = item.ForeColor;
Color backColor = item.BackColor;
Pen foreColorPen = SystemPens.ControlDark;
bool disposeForeColorPen = GetPen(foreColor, ref foreColorPen);
try {
if (vertical) {
if (bounds.Height >= 4) {
bounds.Inflate(0,-2); // scoot down 2PX and start drawing
}
bool rightToLeft = (item.RightToLeft == RightToLeft.Yes);
Pen leftPen = (rightToLeft) ? SystemPens.ButtonHighlight : foreColorPen;
Pen rightPen = (rightToLeft) ? foreColorPen : SystemPens.ButtonHighlight;
// Draw dark line
int startX = bounds.Width / 2;
g.DrawLine(leftPen, startX, bounds.Top, startX, bounds.Bottom);
// Draw highlight one pixel to the right
startX++;
g.DrawLine(rightPen, startX, bounds.Top, startX, bounds.Bottom);
}
else {
//
// horizontal separator
if (bounds.Width >= 4) {
bounds.Inflate(-2,0); // scoot over 2PX and start drawing
}
// Draw dark line
int startY = bounds.Height / 2;
g.DrawLine(foreColorPen, bounds.Left, startY, bounds.Right, startY);
// Draw highlight one pixel to the right
startY++;
g.DrawLine(SystemPens.ButtonHighlight, bounds.Left, startY, bounds.Right, startY);
}
}
finally {
if (disposeForeColorPen && foreColorPen != null) {
foreColorPen.Dispose();
}
}
}
}
private void RenderSmall3DBorderInternal (Graphics g, Rectangle bounds, ToolBarState state, bool rightToLeft) {
if ((state == ToolBarState.Hot) ||(state == ToolBarState.Pressed) || (state == ToolBarState.Checked)) {
Pen leftPen, topPen, rightPen,bottomPen;
topPen = (state == ToolBarState.Hot) ? SystemPens.ButtonHighlight : SystemPens.ButtonShadow;
bottomPen = (state == ToolBarState.Hot)? SystemPens.ButtonShadow : SystemPens.ButtonHighlight;
leftPen = (rightToLeft) ? bottomPen : topPen;
rightPen = (rightToLeft) ? topPen : bottomPen;
g.DrawLine(topPen, bounds.Left, bounds.Top, bounds.Right -1, bounds.Top);
g.DrawLine(leftPen, bounds.Left, bounds.Top, bounds.Left, bounds.Bottom-1);
g.DrawLine(rightPen, bounds.Right-1, bounds.Top, bounds.Right -1, bounds.Bottom-1);
g.DrawLine(bottomPen, bounds.Left, bounds.Bottom-1, bounds.Right -1, bounds.Bottom -1);
}
}
private void RenderStatusStripBorder(ToolStripRenderEventArgs e) {
if (!Application.RenderWithVisualStyles) {
e.Graphics.DrawLine(SystemPens.ButtonHighlight, 0,0,e.ToolStrip.Width, 0);
}
}
private static void RenderStatusStripBackground(ToolStripRenderEventArgs e) {
if (Application.RenderWithVisualStyles) {
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
vsRenderer.SetParameters(VisualStyleElement.Status.Bar.Normal);
vsRenderer.DrawBackground(e.Graphics,new Rectangle(0,0,e.ToolStrip.Width-1, e.ToolStrip.Height-1));
}
else {
if (!SystemInformation.InLockedTerminalSession()) { // see ddb#191714
e.Graphics.Clear(e.BackColor);
}
}
}
private static void RenderLabelInternal(ToolStripItemRenderEventArgs e) {
// dont call RenderItemInternal, as we NEVER want to paint hot.
ToolStripItem item = e.Item;
Graphics g = e.Graphics;
Rectangle fillRect = item.ContentRectangle;
if (item.BackgroundImage != null) {
ControlPaint.DrawBackgroundImage(g, item.BackgroundImage, item.BackColor, item.BackgroundImageLayout, fillRect, fillRect);
}
else {
VisualStyleRenderer vsRenderer = VisualStyleRenderer;
if (vsRenderer == null || (item.BackColor != SystemColors.Control)) {
FillBackground(g, fillRect, item.BackColor);
}
}
}
}
}
| |
//
// ListView_Rendering.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-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 Gdk;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Canvas;
namespace Hyena.Data.Gui
{
public delegate int ListViewRowHeightHandler (Widget widget);
public partial class ListView<T> : ListViewBase
{
private CellContext cell_context;
private Pango.Layout pango_layout;
public override Pango.Layout PangoLayout {
get {
if (pango_layout == null && Window != null && IsRealized) {
using (var cr = Gdk.CairoHelper.Create (Window)) {
pango_layout = CairoExtensions.CreateLayout (this, cr);
cell_context.FontDescription = pango_layout.FontDescription;
cell_context.Layout = pango_layout;
}
}
return pango_layout;
}
}
public override Pango.FontDescription FontDescription {
get { return cell_context != null ? cell_context.FontDescription : null; }
}
private List<int> selected_rows = new List<int> ();
private Theme theme;
protected Theme Theme {
get { return theme; }
}
public bool DoNotRenderNullModel { get; set; }
protected override void OnStyleUpdated ()
{
base.OnStyleUpdated ();
// FIXME: legacy list foo
if (ViewLayout == null) {
OnInvalidateMeasure ();
}
theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this);
if (pango_layout != null) {
cell_context.FontDescription.Dispose ();
pango_layout.Dispose ();
pango_layout = null;
cell_context.Layout = null;
cell_context.FontDescription = null;
}
cell_context = new CellContext ();
cell_context.Theme = theme;
cell_context.Widget = this;
SetDirection ();
}
private void SetDirection ()
{
var dir = Direction;
if (dir == Gtk.TextDirection.None) {
dir = Gtk.Widget.DefaultDirection;
}
if (cell_context != null) {
cell_context.IsRtl = dir == Gtk.TextDirection.Rtl;
}
}
protected override bool OnDrawn (Cairo.Context cr)
{
if (DoNotRenderNullModel && Model == null) {
return true;
}
cell_context.Layout = PangoLayout;
cell_context.Context = cr;
// FIXME: legacy list foo
if (ViewLayout == null) {
if (OnMeasure ()) {
QueueResize ();
}
}
// TreeView style
StyleContext.Save ();
StyleContext.AddClass ("view");
StyleContext.RenderBackground (cr, 0, 0, Allocation.Width, Allocation.Height);
StyleContext.RenderFrame (cr, 0, 0, Allocation.Width, Allocation.Height);
// FIXME: ViewLayout will never be null in the future but we'll need
// to deterministically render a header somehow...
if (header_visible && ViewLayout == null && column_controller != null) {
PaintHeader (cr);
}
if (Model != null) {
// FIXME: ViewLayout will never be null in
// the future, PaintList will go away
if (ViewLayout == null) {
PaintList (cr, Allocation);
} else {
PaintView (cr, new Rect (0.0, 0.0, Allocation.Width, Allocation.Height));
}
}
PaintDraggingColumn (cr);
StyleContext.Restore ();
return true;
}
#region Header Rendering
private void PaintHeader (Cairo.Context cr)
{
Rectangle clip = header_rendering_alloc;
clip.Height += Theme.BorderWidth;
clip.Intersect (new Gdk.Rectangle (0, 0, Allocation.Width, Allocation.Height));
cr.Rectangle (clip.X, clip.Y, clip.Width, clip.Height);
cr.Clip ();
Rectangle cell_area = new Rectangle ();
cell_area.Y = header_rendering_alloc.Y;
cell_area.Height = header_rendering_alloc.Height;
cell_context.Clip = clip;
cell_context.Opaque = true;
cell_context.TextAsForeground = true;
for (int ci = 0; ci < column_cache.Length; ci++) {
if (pressed_column_is_dragging && pressed_column_index == ci) {
continue;
}
cell_area.X = column_cache[ci].X1 + Theme.TotalBorderWidth + header_rendering_alloc.X - HadjustmentValue;
cell_area.Width = column_cache[ci].Width;
PaintHeaderCell (cr, cell_area, ci, false);
}
if (pressed_column_is_dragging && pressed_column_index >= 0) {
cell_area.X = pressed_column_x_drag - HadjustmentValue;
cell_area.Width = column_cache[pressed_column_index].Width;
PaintHeaderCell (cr, cell_area, pressed_column_index, true);
}
cr.ResetClip ();
}
private void PaintHeaderCell (Cairo.Context cr, Rectangle area, int ci, bool dragging)
{
if (ci < 0 || column_cache.Length <= ci)
return;
var column_flags = new RegionFlags ();
if (ci == sort_column_index) {
column_flags |= RegionFlags.Sorted;
}
if (ci == 0) {
column_flags |= RegionFlags.First;
}
if (ci == (column_cache.Length - 1)) {
column_flags |= RegionFlags.Last;
}
// First column should be odd, but ci starts at 0
if ((ci + 1) % 2 == 0) {
column_flags |= RegionFlags.Even;
} else {
column_flags |= RegionFlags.Odd;
}
StyleContext.Save ();
// RegionFlags.Last is not applied, see https://bugzilla.gnome.org/show_bug.cgi?id=731463
StyleContext.AddRegion ("column-header", column_flags);
StyleContext.AddClass ("button");
if (dragging) {
// This is not applied in Adwaita, see https://bugzilla.gnome.org/show_bug.cgi?id=731663
StyleContext.AddClass ("dnd");
}
StyleContext.RenderFrame (cr, area.X, area.Y, area.Width, area.Height);
if (ci == ActiveColumn && HasFocus && HeaderFocused) {
var border = StyleContext.GetBorder (StyleContext.State);
var f_x = area.X + border.Left;
var f_y = area.Y + border.Top;
var f_width = area.Width - border.Left - border.Right;
var f_height = area.Height - border.Top - border.Bottom;
StyleContext.RenderFocus (cr, f_x, f_y, f_width, f_height);
}
ColumnCell cell = column_cache[ci].Column.HeaderCell;
if (cell != null) {
cr.Save ();
cr.Translate (area.X, area.Y);
cell_context.Area = area;
cell_context.Selected = false;
cell.Render (cell_context, area.Width, area.Height);
cr.Restore ();
}
StyleContext.Restore ();
}
#endregion
#region List Rendering
private void PaintList (Cairo.Context cr, Rectangle clip)
{
if (ChildSize.Height <= 0) {
return;
}
clip.Intersect (list_rendering_alloc);
cr.Rectangle (clip.X, clip.Y, clip.Width, clip.Height);
cr.Clip ();
cell_context.Clip = clip;
cell_context.TextAsForeground = false;
int vadjustment_value = VadjustmentValue;
int first_row = vadjustment_value / ChildSize.Height;
int last_row = Math.Min (model.Count, first_row + RowsInView);
int offset = list_rendering_alloc.Y - vadjustment_value % ChildSize.Height;
Rectangle selected_focus_alloc = Rectangle.Zero;
Rectangle single_list_alloc = new Rectangle ();
single_list_alloc.X = list_rendering_alloc.X - HadjustmentValue;
single_list_alloc.Y = offset;
single_list_alloc.Width = list_rendering_alloc.Width + HadjustmentValue;
single_list_alloc.Height = ChildSize.Height;
int selection_height = 0;
int selection_y = 0;
selected_rows.Clear ();
for (int ri = first_row; ri < last_row; ri++) {
if (Selection != null && Selection.Contains (ri)) {
if (selection_height == 0) {
selection_y = single_list_alloc.Y;
}
selection_height += single_list_alloc.Height;
selected_rows.Add (ri);
if (Selection.FocusedIndex == ri) {
selected_focus_alloc = single_list_alloc;
}
} else {
StyleContext.Save ();
StyleContext.AddClass ("cell");
if (rules_hint) { // TODO: check also gtk_widget_style_get(widget,"allow-rules",&allow_rules,NULL);
StyleContext.AddRegion ("row", ri % 2 != 0 ? RegionFlags.Odd : RegionFlags.Even);
}
StyleContext.Restore ();
PaintReorderLine (cr, ri, single_list_alloc);
if (Selection != null && Selection.FocusedIndex == ri && !Selection.Contains (ri) && HasFocus) {
CairoCorners corners = CairoCorners.All;
if (Selection.Contains (ri - 1)) {
corners &= ~(CairoCorners.TopLeft | CairoCorners.TopRight);
}
if (Selection.Contains (ri + 1)) {
corners &= ~(CairoCorners.BottomLeft | CairoCorners.BottomRight);
}
if (HasFocus && !HeaderFocused) // Cursor out of selection.
Theme.DrawRowCursor (cr, single_list_alloc.X, single_list_alloc.Y,
single_list_alloc.Width, single_list_alloc.Height,
CairoExtensions.ColorShade (CairoExtensions.GdkRGBAToCairoColor (StyleContext.GetBackgroundColor (StateFlags.Selected)), 0.85));
}
if (selection_height > 0) {
PaintRowSelection (cr, list_rendering_alloc.X, selection_y, list_rendering_alloc.Width, selection_height);
selection_height = 0;
}
PaintRow (cr, ri, single_list_alloc, false);
}
single_list_alloc.Y += single_list_alloc.Height;
}
// In case the user is dragging to the end of the list
PaintReorderLine (cr, last_row, single_list_alloc);
if (selection_height > 0) {
PaintRowSelection (cr, list_rendering_alloc.X, selection_y, list_rendering_alloc.Width, selection_height);
}
if (Selection != null && Selection.Count > 1 &&
!selected_focus_alloc.Equals (Rectangle.Zero) &&
HasFocus && !HeaderFocused) { // Cursor inside selection.
// Use entry to get text color
StyleContext.Save ();
StyleContext.AddClass ("entry");
Cairo.Color text_color = CairoExtensions.GdkRGBAToCairoColor (StyleContext.GetColor (StateFlags.Selected));
StyleContext.Restore ();
Theme.DrawRowCursor (cr, selected_focus_alloc.X, selected_focus_alloc.Y,
selected_focus_alloc.Width, selected_focus_alloc.Height, text_color);
}
foreach (int ri in selected_rows) {
single_list_alloc.Y = offset + ((ri - first_row) * single_list_alloc.Height);
PaintRow (cr, ri, single_list_alloc, true);
}
cr.ResetClip ();
}
private void PaintRowSelection (Cairo.Context cr, int x, int y, int width, int height)
{
StyleContext.Save ();
StyleContext.AddClass ("cell");
StyleContext.State |= StateFlags.Selected;
if (HasFocus && !HeaderFocused) {
StyleContext.State |= StateFlags.Focused;
}
StyleContext.RenderBackground (cr, x, y, width, height);
StyleContext.RenderFrame (cr, x, y, width, height);
StyleContext.Restore ();
}
private void PaintReorderLine (Cairo.Context cr, int row_index, Rectangle single_list_alloc)
{
if (row_index == drag_reorder_row_index && IsReorderable) {
cr.Save ();
cr.LineWidth = 1.0;
cr.Antialias = Cairo.Antialias.None;
cr.MoveTo (single_list_alloc.Left, single_list_alloc.Top);
cr.LineTo (single_list_alloc.Right, single_list_alloc.Top);
StyleContext.Save ();
StyleContext.AddClass ("entry");
cr.SetSourceColor (CairoExtensions.GdkRGBAToCairoColor (StyleContext.GetColor (StateFlags.Normal)));
StyleContext.Restore ();
cr.Stroke ();
cr.Restore ();
}
}
private void PaintRow (Cairo.Context cr, int row_index, Rectangle area, bool selected)
{
if (column_cache == null) {
return;
}
object item = model[row_index];
bool opaque = IsRowOpaque (item);
bool bold = IsRowBold (item);
Rectangle cell_area = new Rectangle ();
cell_area.Height = ChildSize.Height;
cell_area.Y = area.Y;
cell_context.ViewRowIndex = cell_context.ModelRowIndex = row_index;
for (int ci = 0; ci < column_cache.Length; ci++) {
cell_context.ViewColumnIndex = ci;
if (pressed_column_is_dragging && pressed_column_index == ci) {
continue;
}
cell_area.Width = column_cache[ci].Width;
cell_area.X = column_cache[ci].X1 + area.X;
PaintCell (cr, item, ci, row_index, cell_area, opaque, bold, selected, false);
}
if (pressed_column_is_dragging && pressed_column_index >= 0) {
cell_area.Width = column_cache[pressed_column_index].Width;
cell_area.X = pressed_column_x_drag + list_rendering_alloc.X -
list_interaction_alloc.X - HadjustmentValue;
PaintCell (cr, item, pressed_column_index, row_index, cell_area, opaque, bold, selected, true);
}
}
private void PaintCell (Cairo.Context cr, object item, int column_index, int row_index, Rectangle area, bool opaque, bool bold,
bool selected, bool dragging)
{
ColumnCell cell = column_cache[column_index].Column.GetCell (0);
cell.Bind (item);
cell.Manager = manager;
ColumnCellDataProvider (cell, item);
ITextCell text_cell = cell as ITextCell;
if (text_cell != null) {
text_cell.FontWeight = bold ? Pango.Weight.Bold : Pango.Weight.Normal;
}
if (dragging) {
StyleContext.Save ();
StyleContext.AddClass ("entry");
Cairo.Color fill_color = CairoExtensions.GdkRGBAToCairoColor (StyleContext.GetBackgroundColor (StateFlags.Normal));
StyleContext.Restore ();
fill_color.A = 0.5;
cr.SetSourceColor (fill_color);
cr.Rectangle (area.X, area.Y, area.Width, area.Height);
cr.Fill ();
}
cr.Save ();
cr.Translate (area.X, area.Y);
cell_context.Area = area;
cell_context.Opaque = opaque;
cell_context.Selected = dragging ? false : selected;
cell.Render (cell_context, area.Width, area.Height);
cr.Restore ();
AccessibleCellRedrawn (column_index, row_index);
}
private void PaintDraggingColumn (Cairo.Context cr)
{
if (!pressed_column_is_dragging || pressed_column_index < 0) {
return;
}
CachedColumn column = column_cache[pressed_column_index];
int x = pressed_column_x_drag + 1 - HadjustmentValue;
StyleContext.Save ();
StyleContext.AddClass ("entry");
Cairo.Color fill_color = CairoExtensions.GdkRGBAToCairoColor (StyleContext.GetBackgroundColor (StateFlags.Normal));
Cairo.Color stroke_color = CairoExtensions.ColorShade (fill_color, 0.0);
fill_color.A = 0.45;
stroke_color.A = 0.3;
StyleContext.Restore ();
cr.Rectangle (x, header_rendering_alloc.Bottom + 1, column.Width - 2,
list_rendering_alloc.Bottom - header_rendering_alloc.Bottom - 1);
cr.SetSourceColor (fill_color);
cr.Fill ();
cr.MoveTo (x - 0.5, header_rendering_alloc.Bottom + 0.5);
cr.LineTo (x - 0.5, list_rendering_alloc.Bottom + 0.5);
cr.LineTo (x + column.Width - 1.5, list_rendering_alloc.Bottom + 0.5);
cr.LineTo (x + column.Width - 1.5, header_rendering_alloc.Bottom + 0.5);
cr.SetSourceColor (stroke_color);
cr.LineWidth = 1.0;
cr.Stroke ();
}
#endregion
#region View Layout Rendering
private void PaintView (Cairo.Context cr, Rect clip)
{
clip.Intersect ((Rect)list_rendering_alloc);
cr.Rectangle ((Cairo.Rectangle)clip);
cr.Clip ();
cell_context.Clip = (Gdk.Rectangle)clip;
cell_context.TextAsForeground = false;
selected_rows.Clear ();
for (int layout_index = 0; layout_index < ViewLayout.ChildCount; layout_index++) {
var layout_child = ViewLayout[layout_index];
var child_allocation = layout_child.Allocation;
if (!child_allocation.IntersectsWith (clip) || ViewLayout.GetModelIndex (layout_child) >= Model.Count) {
layout_child.Visible = false;
continue;
}
layout_child.Visible = true;
if (Selection != null && Selection.Contains (ViewLayout.GetModelIndex (layout_child))) {
selected_rows.Add (ViewLayout.GetModelIndex (layout_child));
PaintRowSelection (cr, (int)child_allocation.X, (int)child_allocation.Y,
(int)child_allocation.Width, (int)child_allocation.Height);
cell_context.Selected = true;
} else {
cell_context.Selected = false;
}
layout_child.Render (cell_context);
}
cr.ResetClip ();
}
#endregion
protected void InvalidateList ()
{
if (IsRealized) {
QueueDirtyRegion (list_rendering_alloc);
}
}
private void InvalidateHeader ()
{
if (IsRealized) {
QueueDirtyRegion (header_rendering_alloc);
}
}
protected void QueueDirtyRegion ()
{
QueueDirtyRegion (list_rendering_alloc);
}
protected virtual void ColumnCellDataProvider (ColumnCell cell, object boundItem)
{
}
private bool rules_hint = false;
public bool RulesHint {
get { return rules_hint; }
set {
rules_hint = value;
InvalidateList ();
}
}
// FIXME: Obsolete all this measure stuff on the view since it's in the layout
#region Measuring
private Gdk.Size child_size = Gdk.Size.Empty;
public Gdk.Size ChildSize {
get {
return ViewLayout != null
? new Gdk.Size ((int)ViewLayout.ChildSize.Width, (int)ViewLayout.ChildSize.Height)
: child_size;
}
}
private bool measure_pending;
protected virtual void OnInvalidateMeasure ()
{
measure_pending = true;
if (IsMapped && IsRealized) {
QueueDirtyRegion ();
}
}
protected virtual Gdk.Size OnMeasureChild ()
{
return ViewLayout != null
? new Gdk.Size ((int)ViewLayout.ChildSize.Width, (int)ViewLayout.ChildSize.Height)
: new Gdk.Size (0, ColumnCellText.ComputeRowHeight (this));
}
private bool OnMeasure ()
{
if (!measure_pending) {
return false;
}
measure_pending = false;
header_height = 0;
var old_child_size = child_size;
child_size = OnMeasureChild ();
UpdateAdjustments ();
return old_child_size != child_size;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <disclaimer>
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
// </disclaimer>
//------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Microsoft.Research.Joins;
using System.Diagnostics;
// producerconsumer microbenchmark
namespace ProducerConsumer {
using PAYLOAD = String;
public static class Constants {
public static PAYLOAD payload = "666";
}
public interface Buffer {
void put(PAYLOAD s);
PAYLOAD @get();
}
namespace Classic {
using Microsoft.Research.Joins.Classic;
public class CPB : Buffer {
public void put(PAYLOAD s) {
Put(s);
}
public PAYLOAD get() {
return Get();
}
Asynchronous.Channel<PAYLOAD> Put;
Synchronous<PAYLOAD>.Channel Get;
public CPB() {
Join j = Join.Create();
j.Initialize(out Put);
j.Initialize(out Get);
j.When(Get).And(Put).Do(delegate(PAYLOAD s) { return s; });
}
}
}
public class PB : Buffer {
public void put(PAYLOAD s) {
Put(s);
}
public PAYLOAD @get() {
return Get();
}
Asynchronous.Channel<PAYLOAD> Put;
Synchronous<PAYLOAD>.Channel Get;
public PB() {
Join j = Microsoft.Research.Joins.Join.Create<Join.LockBased>();
j.Initialize(out Put);
j.Initialize(out Get);
j.When(Get).And(Put).Do(delegate(PAYLOAD s) { return s; });
}
}
public class PaperB : Buffer {
public void put(PAYLOAD s) {
Put(s);
}
public PAYLOAD @get() {
return Get();
}
Asynchronous.Channel<PAYLOAD> Put;
Synchronous<PAYLOAD>.Channel Get;
public PaperB() {
Join j = Join.Create<Join.ScalableNonOpt>(2);
j.Initialize(out Put);
j.Initialize(out Get);
//Console.WriteLine(s);
j.When(Get).And(Put).Do(delegate(PAYLOAD s) { return s; });
}
}
public class PaperFPB : Buffer {
public void put(PAYLOAD s) {
Put(s);
}
public PAYLOAD @get() {
return Get();
}
Asynchronous.Channel<PAYLOAD> Put;
Synchronous<PAYLOAD>.Channel Get;
public PaperFPB() {
Join j = Join.Create<Join.Scalable>(2);
j.Initialize(out Put);
j.Initialize(out Get);
//Console.WriteLine(s);
j.When(Get).And(Put).Do(delegate(PAYLOAD s) { return s; });
}
}
// Monitor-based
public class MB : Buffer {
private Queue<PAYLOAD> q = new Queue<PAYLOAD>();
public void put(PAYLOAD s) {
Monitor.Enter(this);
q.Enqueue(s);
Monitor.Pulse(this);
Monitor.Exit(this);
}
public PAYLOAD @get() {
Monitor.Enter(this);
while (q.Count == 0)
Monitor.Wait(this);
PAYLOAD s = (q.Dequeue());
Monitor.Exit(this);
return s;
}
}
// Simple lock-based
public class LB : Buffer {
private Queue<PAYLOAD> q = new Queue<PAYLOAD>();
public void put(PAYLOAD s) {
lock (this) {
q.Enqueue(s);
}
}
public PAYLOAD @get() {
while (true)
lock (this) {
if (q.Count > 0) {
return q.Dequeue();
}
//Thread.Yield();
}
}
}
// lock free buffer using MS ConcurrentQueue (probably incorrect).
public class CQB : Buffer {
private ConcurrentQueue<PAYLOAD> q = new ConcurrentQueue<PAYLOAD>();
public void put(PAYLOAD s) {
q.Enqueue(s);
}
public PAYLOAD @get() {
PAYLOAD s = default(PAYLOAD);
while (!q.TryDequeue(out s)) {
//Thread.Sleep(1);
}
return s;
}
}
// lock free buffer using MS ConcurrentBag
public class CBB : Buffer {
private ConcurrentBag<PAYLOAD> q = new ConcurrentBag<PAYLOAD>();
public void put(PAYLOAD s) {
q.Add(s);
}
public PAYLOAD @get() {
PAYLOAD s = default(PAYLOAD);
while (!q.TryTake(out s)) {
}
;
return s;
}
}
// lock free buffer using MS ConcurrentStack
public class CSB : Buffer {
private ConcurrentStack<PAYLOAD> q = new ConcurrentStack<PAYLOAD>();
public void put(PAYLOAD s) {
q.Push(s);
}
public PAYLOAD @get() {
PAYLOAD s = default(PAYLOAD);
while (!q.TryPop(out s)) {
}
;
return s;
}
}
// lock free buffer using MS BlockingCollection
public class CBC : Buffer {
private BlockingCollection<PAYLOAD> q = new BlockingCollection<PAYLOAD>();
public void put(PAYLOAD s) {
q.Add(s);
}
public PAYLOAD @get() {
return q.Take();
}
}
public class pctest {
static Buffer b;
static int n = 1;
static int maxThreadPairs = System.Environment.ProcessorCount;
static int total = 100000;
static int burstsize = 1;
static int trials = 3;
static int prodSpins = 0;
static int consSpins = 0;
static Asynchronous.Channel<int> producer, consumer;
static Asynchronous.Channel done;
static Synchronous.Channel wait;
static long DoTrial(Buffer newbuf) {
GC.Collect();
b = newbuf;
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < n; i++) {
producer(i);
consumer(i);
}
for (int i = 0; i < n; i++) {
wait();
wait();
}
sw.Stop();
return sw.ElapsedMilliseconds;
}
static void DoTest(string name, Buffer newbuf) {
Console.Error.WriteLine(name);
var series = new Dictionary<int, long>();
Reporting.data.Add(name, series);
for (n = 1; n <= maxThreadPairs; n++) {
var threads = n * 2;
Reporting.AddX(threads);
long time = 0;
var trialTimes = new System.Collections.Generic.List<long>();
for (int j = 0; j < trials; j++) {
var ttime = DoTrial(newbuf);
trialTimes.Add(ttime);
time += ttime;
}
var mean = time / trials;
Console.Error.Write(" ");
Console.Error.Write("{0:000}", n * 2);
Console.Error.Write(" threads MEAN: ");
Console.Error.Write("{0:00000}", time);
series.Add(threads, time);
Console.Error.Write(" SDV: ");
long sqDifSum = 0;
foreach (var t in trialTimes)
sqDifSum += (t - mean) * (t - mean);
Console.Error.WriteLine("{0:00000}", TimeSpan.FromTicks((long)Math.Sqrt(sqDifSum / trials)).TotalMilliseconds);
}
}
static void Main(string[] args) {
if (!(args.Length == 2 && Int32.TryParse(args[0], out prodSpins) && Int32.TryParse(args[1], out consSpins))) {
prodSpins = 0;
consSpins = 0;
};
Join j = Join.Create<Join.Scalable>();
j.Initialize(out producer);
j.Initialize(out consumer);
j.Initialize(out done);
j.Initialize(out wait);
j.When(producer).Do(p => {
var rand = new Random(0);
Thread.CurrentThread.Name = "Producer " + p;
int sent = 0;
var pSpins = pctest.prodSpins;
while (sent < total / n) {
for (int i = 0; i < burstsize; i++)
b.put(Constants.payload);
sent += burstsize;
Thread.SpinWait(rand.Next(pSpins));
}
done();
});
j.When(consumer).Do(c => {
var rand = new Random(0);
Thread.CurrentThread.Name = "Consumer " + c;
var cSpins = pctest.consSpins;
for (int i = 0; i < total / n; i++) {
PAYLOAD s = b.@get();
//if (i%100==0) Console.WriteLine(i);
Thread.SpinWait(rand.Next(cSpins));
}
done();
});
j.When(wait).And(done).Do(delegate { });
/*
Console.WriteLine("monitor-based buffer");
DoTest(new MB());
Console.WriteLine("simple lock-based buffer");
DoTest(new LB());
*/
DoTest("LB-Joins",new Classic.CPB());
DoTest("S-Joins", new PaperB());
DoTest("S-Joins-opt", new PaperFPB());
DoTest("ConcQ", new CQB());
DoTest("BlockCol", new CBC());
DoTest("LB-Joins-mod", new PB());
/*
Console.WriteLine("concurrent stack");
DoTest(new CSB());
Console.WriteLine("concurrent bag");
DoTest(new CBB());
Console.WriteLine("LFJoin");
DoTest(new LFB());
Console.WriteLine("SJoin");
DoTest(new SB());
*/
//Console.WriteLine("LBSJoin");
//DoTest(new PBS());
//Console.WriteLine("LBJoin");
//DoTest(new PB());
//Console.WriteLine("spinlock joins");
//DoTest(new SPB());
//Console.WriteLine("Comparison");
//Compare(new LFB(), new SB());
Reporting.ReportData();
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Timers;
using System.Windows.Forms;
using Aurora.Framework;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework.Serialization;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using Timer = System.Timers.Timer;
namespace Aurora.Modules.Startup.FileBasedSimulationData
{
/// <summary>
/// FileBased DataStore, do not store anything in any databases, instead save .abackup files for it
/// </summary>
public class FileBasedSimulationData : ISimulationDataStore
{
protected Timer m_backupSaveTimer;
protected string m_fileName = "";
protected List<ISceneEntity> m_groups = new List<ISceneEntity>();
protected bool m_hasShownFileBasedWarning;
protected bool m_keepOldSave = true;
protected string m_loadAppendedFileName = "";
protected string m_loadDirectory = "";
protected bool m_loaded;
protected string m_oldSaveDirectory = "Backups";
protected bool m_oldSaveHasBeenSaved;
protected byte[] m_oldstylerevertTerrain;
protected byte[] m_oldstyleterrain;
//For backwards compat
//For backwards compat
protected List<LandData> m_parcels = new List<LandData>();
protected bool m_requiresSave = true;
protected bool m_displayNotSavingNotice = true;
protected byte[] m_revertTerrain;
protected byte[] m_revertWater;
protected string m_saveAppendedFileName = "";
protected bool m_saveBackupChanges = true;
protected bool m_saveBackups;
protected bool m_saveChanges = true;
protected string m_saveDirectory = "";
protected Timer m_saveTimer;
protected IScene m_scene;
protected short[] m_shortrevertTerrain;
protected short[] m_shortterrain;
protected byte[] m_terrain;
protected int m_timeBetweenBackupSaves = 1440; //One day
protected int m_timeBetweenSaves = 5;
protected byte[] m_water;
#region ISimulationDataStore Members
public bool MapTileNeedsGenerated
{
get;
set;
}
public virtual string Name
{
get { return "FileBasedDatabase"; }
}
public bool SaveBackups
{
get { return m_saveBackups; }
set { m_saveBackups = value; }
}
public virtual ISimulationDataStore Copy()
{
return new FileBasedSimulationData();
}
public virtual void Initialise()
{
}
public virtual List<ISceneEntity> LoadObjects(IScene scene)
{
if (!m_loaded)
{
m_loaded = true;
ReadConfig(scene, scene.Config.Configs["FileBasedSimulationData"]);
ReadBackup(scene);
}
return m_groups;
}
public virtual short[] LoadTerrain(IScene scene, bool RevertMap, int RegionSizeX, int RegionSizeY)
{
if (!m_loaded)
{
m_loaded = true;
ReadConfig(scene, scene.Config.Configs["FileBasedSimulationData"]);
ReadBackup(scene);
}
ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
if (RevertMap)
{
ITerrainChannel channel = new TerrainChannel(false, scene);
if (m_revertTerrain == null)
{
if (m_shortrevertTerrain != null) //OpenSim style
terrainModule.TerrainRevertMap = new TerrainChannel(m_shortrevertTerrain, scene);
else if (m_oldstylerevertTerrain != null)
{
MemoryStream ms = new MemoryStream(m_oldstylerevertTerrain);
if (terrainModule != null)
terrainModule.LoadRevertMapFromStream(".r32", ms, 0, 0);
}
}
else
//New style
terrainModule.TerrainRevertMap = ReadFromData(m_revertTerrain, scene);
//Make sure the size is right!
if (terrainModule.TerrainRevertMap != null &&
terrainModule.TerrainRevertMap.Height != scene.RegionInfo.RegionSizeX)
terrainModule.TerrainRevertMap = null;
m_revertTerrain = null;
m_oldstylerevertTerrain = null;
m_shortrevertTerrain = null;
return null;
}
else
{
if (m_terrain == null)
{
if (m_shortterrain != null) //OpenSim style
terrainModule.TerrainMap = new TerrainChannel(m_shortterrain, scene);
else if (m_oldstyleterrain != null)
{
//Old style
ITerrainChannel channel = new TerrainChannel(false, scene);
MemoryStream ms = new MemoryStream(m_oldstyleterrain);
if (terrainModule != null)
terrainModule.LoadFromStream(".r32", ms, 0, 0);
}
}
else
//New style
terrainModule.TerrainMap = ReadFromData(m_terrain, scene);
//Make sure the size is right!
if (terrainModule.TerrainMap != null &&
terrainModule.TerrainMap.Height != scene.RegionInfo.RegionSizeX)
terrainModule.TerrainMap = null;
m_terrain = null;
m_oldstyleterrain = null;
m_shortterrain = null;
return null;
}
}
public virtual short[] LoadWater(IScene scene, bool RevertMap, int RegionSizeX, int RegionSizeY)
{
if (!m_loaded)
{
m_loaded = true;
ReadConfig(scene, scene.Config.Configs["FileBasedSimulationData"]);
ReadBackup(scene);
}
ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>();
if (RevertMap)
{
if (m_revertWater == null)
return null;
terrainModule.TerrainWaterRevertMap = ReadFromData(m_revertWater, scene);
//Make sure the size is right!
if (terrainModule.TerrainWaterRevertMap.Height != scene.RegionInfo.RegionSizeX)
terrainModule.TerrainWaterRevertMap = null;
m_revertWater = null;
return null;
}
else
{
if (m_water == null)
return null;
terrainModule.TerrainWaterMap = ReadFromData(m_water, scene);
//Make sure the size is right!
if (terrainModule.TerrainWaterMap.Height != scene.RegionInfo.RegionSizeX)
terrainModule.TerrainWaterMap = null;
m_water = null;
return null;
}
}
public virtual void Shutdown()
{
//The sim is shutting down, we need to save one last backup
try
{
if (!m_saveChanges || !m_saveBackups)
return;
SaveBackup(m_saveDirectory, false);
}
catch (Exception ex)
{
MainConsole.Instance.Error("[FileBasedSimulationData]: Failed to save backup, exception occured " + ex);
}
}
public virtual void Tainted()
{
m_requiresSave = true;
}
public virtual void RemoveRegion(UUID regionUUID)
{
//Remove the file so that the region is gone
File.Delete(m_loadDirectory + m_fileName);
}
public virtual void RenameBackupFiles(string oldRegionName, string newRegionName, IConfigSource configSource)
{
if (File.Exists(m_saveDirectory + oldRegionName + m_saveAppendedFileName + ".abackup"))
File.Move(m_saveDirectory + oldRegionName + m_saveAppendedFileName + ".abackup",
m_saveDirectory + newRegionName + m_saveAppendedFileName + ".abackup");
}
/// <summary>
/// Around for legacy things
/// </summary>
/// <param name = "regionUUID"></param>
/// <returns></returns>
public virtual List<LandData> LoadLandObjects(UUID regionUUID)
{
if (!m_loaded)
{
m_loaded = true;
ReadConfig(m_scene, m_scene.Config.Configs["FileBasedSimulationData"]);
ReadBackup(m_scene);
}
return m_parcels;
}
#endregion
public object RegionInfoChanged(string funcName, object param)
{
RegionInfo oldRegion = (RegionInfo)((object[])param)[0];
RegionInfo newRegion = (RegionInfo)((object[])param)[1];
RenameBackupFiles(oldRegion.RegionName, newRegion.RegionName, m_scene.Config);
return null;
}
/// <summary>
/// Read the config for the data loader
/// </summary>
/// <param name = "scene"></param>
/// <param name = "config"></param>
protected virtual void ReadConfig(IScene scene, IConfig config)
{
scene.RequestModuleInterface<ISimulationBase>().EventManager.RegisterEventHandler("RegionInfoChanged", RegionInfoChanged);
if (config != null)
{
m_loadAppendedFileName = config.GetString("AppendedLoadFileName", m_loadAppendedFileName);
m_saveAppendedFileName = config.GetString("AppendedSaveFileName", m_saveAppendedFileName);
m_saveChanges = config.GetBoolean("SaveChanges", m_saveChanges);
m_timeBetweenSaves = config.GetInt("TimeBetweenSaves", m_timeBetweenSaves);
m_keepOldSave = config.GetBoolean("SavePreviousBackup", m_keepOldSave);
m_oldSaveDirectory = config.GetString("PreviousBackupDirectory", m_oldSaveDirectory);
m_loadDirectory = config.GetString("LoadBackupDirectory", m_loadDirectory);
m_saveDirectory = config.GetString("SaveBackupDirectory", m_saveDirectory);
m_saveBackupChanges = config.GetBoolean("SaveTimedPreviousBackup", m_keepOldSave);
m_timeBetweenBackupSaves = config.GetInt("TimeBetweenBackupSaves", m_timeBetweenBackupSaves);
}
if (m_saveChanges && m_timeBetweenSaves != 0)
{
m_saveTimer = new Timer(m_timeBetweenSaves*60*1000);
m_saveTimer.Elapsed += m_saveTimer_Elapsed;
m_saveTimer.Start();
}
if (m_saveChanges && m_timeBetweenBackupSaves != 0)
{
m_backupSaveTimer = new Timer(m_timeBetweenBackupSaves*60*1000);
m_backupSaveTimer.Elapsed += m_backupSaveTimer_Elapsed;
m_backupSaveTimer.Start();
}
scene.AuroraEventManager.RegisterEventHandler("Backup", AuroraEventManager_OnGenericEvent);
m_scene = scene;
m_fileName = scene.RegionInfo.RegionName + m_loadAppendedFileName + ".abackup";
}
/// <summary>
/// Look for the backup event, and if it is there, trigger the backup of the sim
/// </summary>
/// <param name = "FunctionName"></param>
/// <param name = "parameters"></param>
/// <returns></returns>
private object AuroraEventManager_OnGenericEvent(string FunctionName, object parameters)
{
if (FunctionName == "Backup")
{
m_saveTimer.Stop();
try
{
SaveBackup(m_saveDirectory, false);
m_requiresSave = false;
}
catch (Exception ex)
{
MainConsole.Instance.Error("[FileBasedSimulationData]: Failed to save backup, exception occured " + ex);
}
m_saveTimer.Start(); //Restart it as we just did a backup
}
return null;
}
/// <summary>
/// Save a backup on the timer event
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void m_saveTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (m_requiresSave)
{
m_displayNotSavingNotice = true;
m_requiresSave = false;
m_saveTimer.Stop();
try
{
if (m_saveChanges && m_saveBackups)
SaveBackup(m_saveDirectory, m_keepOldSave && !m_oldSaveHasBeenSaved);
}
catch (Exception ex)
{
MainConsole.Instance.Error("[FileBasedSimulationData]: Failed to save backup, exception occured " + ex);
}
m_saveTimer.Start(); //Restart it as we just did a backup
}
else if (m_displayNotSavingNotice)
{
m_displayNotSavingNotice = false;
MainConsole.Instance.Info("[FileBasedSimulationData]: Not saving backup, not required");
}
}
/// <summary>
/// Save a backup into the oldSaveDirectory on the timer event
/// </summary>
/// <param name = "sender"></param>
/// <param name = "e"></param>
private void m_backupSaveTimer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
SaveBackup(m_oldSaveDirectory, true);
}
catch (Exception ex)
{
MainConsole.Instance.Error("[FileBasedSimulationData]: Failed to save backup, exception occured " + ex);
}
}
/// <summary>
/// Save a backup of the sim
/// </summary>
/// <param name = "appendedFilePath">The file path where the backup will be saved</param>
protected virtual void SaveBackup(string appendedFilePath, bool saveAssets)
{
if (appendedFilePath == "/")
appendedFilePath = "";
IBackupModule backupModule = m_scene.RequestModuleInterface<IBackupModule>();
if (backupModule != null && backupModule.LoadingPrims) //Something is changing lots of prims
{
MainConsole.Instance.Info("[Backup]: Not saving backup because the backup module is loading prims");
return;
}
//Save any script state saves that might be around
IScriptModule[] engines = m_scene.RequestModuleInterfaces<IScriptModule>();
try
{
if (engines != null)
{
#if (!ISWIN)
foreach (IScriptModule engine in engines)
{
if (engine != null)
{
engine.SaveStateSaves();
}
}
#else
foreach (IScriptModule engine in engines.Where(engine => engine != null))
{
engine.SaveStateSaves();
}
#endif
}
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
}
MainConsole.Instance.Info("[FileBasedSimulationData]: Saving backup for region " + m_scene.RegionInfo.RegionName);
string fileName = appendedFilePath + m_scene.RegionInfo.RegionName + m_saveAppendedFileName + ".abackup";
if (File.Exists(fileName))
{
//Do new style saving here!
GZipStream m_saveStream = new GZipStream(new FileStream(fileName + ".tmp", FileMode.Create),
CompressionMode.Compress);
TarArchiveWriter writer = new TarArchiveWriter(m_saveStream);
GZipStream m_loadStream = new GZipStream(new FileStream(fileName, FileMode.Open),
CompressionMode.Decompress);
TarArchiveReader reader = new TarArchiveReader(m_loadStream);
writer.WriteDir("parcels");
IParcelManagementModule module = m_scene.RequestModuleInterface<IParcelManagementModule>();
if (module != null)
{
List<ILandObject> landObject = module.AllParcels();
foreach (ILandObject parcel in landObject)
{
OSDMap parcelMap = parcel.LandData.ToOSD();
var binary = OSDParser.SerializeLLSDBinary(parcelMap);
writer.WriteFile("parcels/" + parcel.LandData.GlobalID.ToString(),
binary);
binary = null;
parcelMap = null;
}
}
writer.WriteDir("newstyleterrain");
writer.WriteDir("newstylerevertterrain");
writer.WriteDir("newstylewater");
writer.WriteDir("newstylerevertwater");
ITerrainModule tModule = m_scene.RequestModuleInterface<ITerrainModule>();
if (tModule != null)
{
try
{
byte[] sdata = WriteTerrainToStream(tModule.TerrainMap);
writer.WriteFile("newstyleterrain/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain", sdata);
sdata = null;
sdata = WriteTerrainToStream(tModule.TerrainRevertMap);
writer.WriteFile(
"newstylerevertterrain/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain", sdata);
sdata = null;
if (tModule.TerrainWaterMap != null)
{
sdata = WriteTerrainToStream(tModule.TerrainWaterMap);
writer.WriteFile("newstylewater/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain",
sdata);
sdata = null;
sdata = WriteTerrainToStream(tModule.TerrainWaterRevertMap);
writer.WriteFile(
"newstylerevertwater/" + m_scene.RegionInfo.RegionID.ToString() + ".terrain", sdata);
sdata = null;
}
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
}
}
IDictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>();
UuidGatherer assetGatherer = new UuidGatherer(m_scene.AssetService);
ISceneEntity[] saveentities = m_scene.Entities.GetEntities();
List<UUID> entitiesToSave = new List<UUID>();
foreach (ISceneEntity entity in saveentities)
{
try
{
if (entity.IsAttachment ||
((entity.RootChild.Flags & PrimFlags.Temporary) == PrimFlags.Temporary)
|| ((entity.RootChild.Flags & PrimFlags.TemporaryOnRez) == PrimFlags.TemporaryOnRez))
continue;
if (entity.HasGroupChanged)
{
entity.HasGroupChanged = false;
//Write all entities
byte[] xml = ((ISceneObject) entity).ToBinaryXml2();
writer.WriteFile("entities/" + entity.UUID.ToString(), xml);
xml = null;
}
else
entitiesToSave.Add(entity.UUID);
if (saveAssets)
assetGatherer.GatherAssetUuids(entity, assets, m_scene);
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
entitiesToSave.Add(entity.UUID);
}
}
byte[] data;
string filePath;
TarArchiveReader.TarEntryType entryType;
//Load the archive data that we need
try
{
while ((data = reader.ReadEntry(out filePath, out entryType)) != null)
{
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
continue;
if (filePath.StartsWith("entities/"))
{
UUID entityID = UUID.Parse(filePath.Remove(0, 9));
if (entitiesToSave.Contains(entityID))
{
writer.WriteFile(filePath, data);
entitiesToSave.Remove(entityID);
}
}
data = null;
}
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
}
if (entitiesToSave.Count > 0)
{
MainConsole.Instance.Fatal(entitiesToSave.Count + " PRIMS WERE NOT GOING TO BE SAVED! FORCE SAVING NOW! ");
foreach (ISceneEntity entity in saveentities)
{
if (entitiesToSave.Contains(entity.UUID))
{
if (entity.IsAttachment ||
((entity.RootChild.Flags & PrimFlags.Temporary) == PrimFlags.Temporary)
|| ((entity.RootChild.Flags & PrimFlags.TemporaryOnRez) == PrimFlags.TemporaryOnRez))
continue;
//Write all entities
byte[] xml = ((ISceneObject) entity).ToBinaryXml2();
writer.WriteFile("entities/" + entity.UUID.ToString(), xml);
xml = null;
}
}
}
if (saveAssets)
{
foreach (UUID assetID in new List<UUID>(assets.Keys))
{
try
{
WriteAsset(assetID.ToString(), m_scene.AssetService.Get(assetID.ToString()), writer);
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
}
}
}
reader.Close();
writer.Close();
m_loadStream.Close();
m_saveStream.Close();
GC.Collect();
if (m_keepOldSave && !m_oldSaveHasBeenSaved)
{
//Havn't moved it yet, so make sure the directory exists, then move it
m_oldSaveHasBeenSaved = true;
if (!Directory.Exists(m_oldSaveDirectory))
Directory.CreateDirectory(m_oldSaveDirectory);
File.Copy(fileName + ".tmp",
Path.Combine(m_oldSaveDirectory,
m_scene.RegionInfo.RegionName + SerializeDateTime() + m_saveAppendedFileName +
".abackup"));
}
//Just remove the file
File.Delete(fileName);
}
else
{
//Add the .temp since we might need to make a backup and so that if something goes wrong, we don't corrupt the main backup
GZipStream m_saveStream = new GZipStream(new FileStream(fileName + ".tmp", FileMode.Create),
CompressionMode.Compress);
TarArchiveWriter writer = new TarArchiveWriter(m_saveStream);
IAuroraBackupArchiver archiver = m_scene.RequestModuleInterface<IAuroraBackupArchiver>();
//Turn off prompting so that we don't ask the user questions every time we need to save the backup
archiver.AllowPrompting = false;
archiver.SaveRegionBackup(writer, m_scene);
archiver.AllowPrompting = true;
m_saveStream.Close();
writer.Close();
GC.Collect();
}
File.Move(fileName + ".tmp", fileName);
ISceneEntity[] entities = m_scene.Entities.GetEntities();
try
{
#if (!ISWIN)
foreach (ISceneEntity entity in entities)
{
if (entity.HasGroupChanged)
{
entity.HasGroupChanged = false;
}
}
#else
foreach (ISceneEntity entity in entities.Where(entity => entity.HasGroupChanged))
{
entity.HasGroupChanged = false;
}
#endif
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[Backup]: Exception caught: {0}", ex);
}
//Now make it the full file again
MapTileNeedsGenerated = true;
MainConsole.Instance.Info("[FileBasedSimulationData]: Saved Backup for region " + m_scene.RegionInfo.RegionName);
}
private void WriteAsset(string id, AssetBase asset, TarArchiveWriter writer)
{
if (asset != null)
writer.WriteFile("assets/" + asset.ID, OSDParser.SerializeJsonString(asset.ToOSD()));
else
MainConsole.Instance.WarnFormat("[FileBasedSimulationData]: Could not find asset {0} to save.", id);
}
private byte[] WriteTerrainToStream(ITerrainChannel tModule)
{
int tMapSize = tModule.Height*tModule.Height;
byte[] sdata = new byte[tMapSize*2];
Buffer.BlockCopy(tModule.GetSerialised(tModule.Scene), 0, sdata, 0, sdata.Length);
return sdata;
}
protected virtual string SerializeDateTime()
{
return String.Format("--{0:yyyy-MM-dd-HH-mm}", DateTime.Now);
//return "--" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute;
}
protected virtual void ReadBackup(IScene scene)
{
MainConsole.Instance.Debug("[FileBasedSimulationData]: Reading file for " + scene.RegionInfo.RegionName);
List<uint> foundLocalIDs = new List<uint>();
GZipStream m_loadStream;
try
{
m_loadStream =
new GZipStream(
ArchiveHelpers.GetStream(((m_loadDirectory == "" || m_loadDirectory == "/")
? m_fileName
: Path.Combine(m_loadDirectory, m_fileName))),
CompressionMode.Decompress);
}
catch
{
if (CheckForOldDataBase())
SaveBackup(m_saveDirectory, false);
return;
}
TarArchiveReader reader = new TarArchiveReader(m_loadStream);
byte[] data;
string filePath;
TarArchiveReader.TarEntryType entryType;
//Load the archive data that we need
while ((data = reader.ReadEntry(out filePath, out entryType)) != null)
{
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType)
continue;
if (filePath.StartsWith("parcels/"))
{
//Only use if we are not merging
LandData parcel = new LandData();
OSD parcelData = OSDParser.DeserializeLLSDBinary(data);
parcel.FromOSD((OSDMap) parcelData);
m_parcels.Add(parcel);
}
else if (filePath.StartsWith("terrain/"))
{
m_oldstyleterrain = data;
}
else if (filePath.StartsWith("revertterrain/"))
{
m_oldstylerevertTerrain = data;
}
else if (filePath.StartsWith("newstyleterrain/"))
{
m_terrain = data;
}
else if (filePath.StartsWith("newstylerevertterrain/"))
{
m_revertTerrain = data;
}
else if (filePath.StartsWith("newstylewater/"))
{
m_water = data;
}
else if (filePath.StartsWith("newstylerevertwater/"))
{
m_revertWater = data;
}
else if (filePath.StartsWith("entities/"))
{
MemoryStream ms = new MemoryStream(data);
SceneObjectGroup sceneObject = SceneObjectSerializer.FromXml2Format(ref ms, scene);
ms.Close();
ms = null;
data = null;
foreach (ISceneChildEntity part in sceneObject.ChildrenEntities())
{
if (!foundLocalIDs.Contains(part.LocalId))
foundLocalIDs.Add(part.LocalId);
else
part.LocalId = 0; //Reset it! Only use it once!
}
m_groups.Add(sceneObject);
}
data = null;
}
m_loadStream.Close();
m_loadStream = null;
foundLocalIDs.Clear();
GC.Collect();
}
/// <summary>
/// Checks whether an older style database exists
/// </summary>
/// <returns>Whether an older style database exists</returns>
protected virtual bool CheckForOldDataBase()
{
string connString = "";
string name = "";
// Try reading the [DatabaseService] section, if it exists
IConfig dbConfig = m_scene.Config.Configs["DatabaseService"];
if (dbConfig != null)
connString = dbConfig.GetString("ConnectionString", String.Empty);
// Try reading the [SimulationDataStore] section
IConfig simConfig = m_scene.Config.Configs["SimulationDataStore"];
if (simConfig != null)
{
name = simConfig.GetString("LegacyDatabaseLoaderName", "FileBasedDatabase");
connString = simConfig.GetString("ConnectionString", connString);
}
ILegacySimulationDataStore[] stores =
AuroraModuleLoader.PickupModules<ILegacySimulationDataStore>().ToArray();
#if (!ISWIN)
ILegacySimulationDataStore simStore = null;
foreach (ILegacySimulationDataStore store in stores)
{
if (store.Name == name)
{
simStore = store;
break;
}
}
#else
ILegacySimulationDataStore simStore = stores.FirstOrDefault(store => store.Name == name);
#endif
if (simStore == null)
return false;
try
{
if (!m_hasShownFileBasedWarning)
{
m_hasShownFileBasedWarning = true;
IConfig startupConfig = m_scene.Config.Configs["Startup"];
if (startupConfig == null || startupConfig.GetBoolean("NoGUI", false))
DoNoGUIWarning();
else if(!m_scene.RegionInfo.NewRegion)
MessageBox.Show(
@"Your sim has been updated to use the FileBased Simulation Service.
Your sim is now saved in a .abackup file in the bin/ directory with the same name as your region.
More configuration options and info can be found in the Configuration/Data/FileBased.ini file.",
"WARNING");
}
}
catch
{
DoNoGUIWarning();
}
simStore.Initialise(connString);
IParcelServiceConnector conn = DataManager.DataManager.RequestPlugin<IParcelServiceConnector>();
m_parcels = simStore.LoadLandObjects(m_scene.RegionInfo.RegionID);
m_parcels.AddRange(conn.LoadLandObjects(m_scene.RegionInfo.RegionID));
m_groups = simStore.LoadObjects(m_scene.RegionInfo.RegionID, m_scene);
if (m_groups.Count != 0 || m_parcels.Count != 0)
{
try
{
m_shortterrain = simStore.LoadTerrain(m_scene, false, m_scene.RegionInfo.RegionSizeX,
m_scene.RegionInfo.RegionSizeY);
m_shortrevertTerrain = simStore.LoadTerrain(m_scene, true, m_scene.RegionInfo.RegionSizeX,
m_scene.RegionInfo.RegionSizeY);
//Remove these so that we don't get stuck loading them later
conn.RemoveAllLandObjects(m_scene.RegionInfo.RegionID);
simStore.RemoveAllLandObjects(m_scene.RegionInfo.RegionID);
}
catch
{ }
return true;
}
return false;
}
private void DoNoGUIWarning()
{
//Some people don't have winforms, which is fine
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("Your sim has been updated to use the FileBased Simulation Service.");
MainConsole.Instance.Error(
"Your sim is now saved in a .abackup file in the bin/ directory with the same name as your region.");
MainConsole.Instance.Error("More configuration options and info can be found in the Configuration/Data/FileBased.ini file.");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
MainConsole.Instance.Error("---------------------");
}
private ITerrainChannel ReadFromData(byte[] data, IScene scene)
{
short[] sdata = new short[data.Length/2];
Buffer.BlockCopy(data, 0, sdata, 0, data.Length);
return new TerrainChannel(sdata, scene);
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Diagnostics;
using System.Windows.Input;
using AppStudio.Uwp.Actions;
using AppStudio.Uwp.Cache;
using AppStudio.Uwp.Commands;
using AppStudio.Uwp.DataSync;
using AppStudio.Uwp.Navigation;
using AppStudio.DataProviders;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml.Controls;
using DotNetSpainConference.Config;
namespace DotNetSpainConference.ViewModels
{
public class ListViewModel : PageViewModelBase, INavigable
{
private ObservableCollection<ItemViewModel> _items = new ObservableCollection<ItemViewModel>();
private bool _hasMoreItems;
private bool _hasItems;
private int _visibleItems;
private Func<bool, Func<ItemViewModel, bool>, Task<DateTime?>> LoadDataInternal;
private ListViewModel()
{
}
public static ListViewModel CreateNew<TSchema>(SectionConfigBase<TSchema> sectionConfig, int visibleItems = 0) where TSchema : SchemaBase
{
var vm = new ListViewModel
{
SectionName = sectionConfig.Name,
Title = sectionConfig.ListPage.Title,
NavigationInfo = sectionConfig.ListPage.ListNavigationInfo,
PageTitle = sectionConfig.ListPage.PageTitle,
_visibleItems = visibleItems,
HasLocalData = !sectionConfig.NeedsNetwork
};
var settings = new CacheSettings
{
Key = sectionConfig.Name,
Expiration = vm.CacheExpiration,
NeedsNetwork = sectionConfig.NeedsNetwork,
UseStorage = sectionConfig.NeedsNetwork,
};
//we save a reference to the load delegate in order to avoid export TSchema outside the view model
vm.LoadDataInternal = (refresh, filterFunc) => AppCache.LoadItemsAsync<TSchema>(settings, sectionConfig.LoadDataAsyncFunc, (content) => vm.ParseItems(sectionConfig.ListPage, content, filterFunc), refresh);
if (sectionConfig.NeedsNetwork)
{
vm.Actions.Add(new ActionInfo
{
Command = vm.Refresh,
Style = ActionKnownStyles.Refresh,
Name = "RefreshButton",
ActionType = ActionType.Primary
});
}
return vm;
}
public async Task LoadDataAsync(bool forceRefresh = false)
{
try
{
HasLoadDataErrors = false;
IsBusy = true;
LastUpdated = await LoadDataInternal(forceRefresh, null);
}
catch (Exception ex)
{
Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackException(ex);
HasLoadDataErrors = true;
Debug.WriteLine(ex.ToString());
}
finally
{
IsBusy = false;
}
}
public async Task SearchDataAsync(string searchTerm)
{
if (!string.IsNullOrEmpty(searchTerm))
{
try
{
HasLoadDataErrors = false;
IsBusy = true;
LastUpdated = await LoadDataInternal(true, i => i.ContainsString(searchTerm));
}
catch (Exception ex)
{
Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackException(ex);
HasLoadDataErrors = true;
Debug.WriteLine(ex.ToString());
}
finally
{
IsBusy = false;
}
}
}
public async Task FilterDataAsync(List<string> itemsId)
{
if (itemsId != null && itemsId.Any())
{
try
{
HasLoadDataErrors = false;
IsBusy = true;
LastUpdated = await LoadDataInternal(true, i => itemsId.Contains(i.Id));
}
catch (Exception ex)
{
Microsoft.ApplicationInsights.TelemetryClient telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
telemetry.TrackException(ex);
HasLoadDataErrors = true;
Debug.WriteLine(ex.ToString());
}
finally
{
IsBusy = false;
}
}
}
internal void CleanItems()
{
this.Items.Clear();
this.HasItems = false;
}
public RelayCommand<ItemViewModel> ItemClickCommand
{
get
{
return new RelayCommand<ItemViewModel>(
(item) =>
{
NavigationService.NavigateTo(item);
});
}
}
public RelayCommand<INavigable> SectionHeaderClickCommand
{
get
{
return new RelayCommand<INavigable>(
(item) =>
{
NavigationService.NavigateTo(item);
});
}
}
public NavigationInfo NavigationInfo { get; set; }
public string PageTitle { get; set; }
public ObservableCollection<ItemViewModel> Items
{
get { return _items; }
private set { SetProperty(ref _items, value); }
}
public bool HasMoreItems
{
get { return _hasMoreItems; }
private set { SetProperty(ref _hasMoreItems, value); }
}
public bool HasItems
{
get { return _hasItems; }
private set { SetProperty(ref _hasItems, value); }
}
public ICommand Refresh
{
get
{
return new RelayCommand(async () =>
{
await LoadDataAsync(true);
});
}
}
public void ShareContent(DataRequest dataRequest, bool supportsHtml = true)
{
if (Items != null && Items.Count > 0)
{
ShareContent(dataRequest, Items[0], supportsHtml);
}
}
private void ParseItems<TSchema>(ListPageConfig<TSchema> listConfig, CachedContent<TSchema> content, Func<ItemViewModel, bool> filterFunc) where TSchema : SchemaBase
{
var parsedItems = new List<ItemViewModel>();
foreach (var item in GetVisibleItems(content, _visibleItems))
{
var parsedItem = new ItemViewModel
{
Id = item._id,
NavigationInfo = listConfig.DetailNavigation(item)
};
listConfig.LayoutBindings(parsedItem, item);
if (filterFunc == null)
{
parsedItems.Add(parsedItem);
}
else if (filterFunc(parsedItem))
{
parsedItems.Add(parsedItem);
}
}
Items.Sync(parsedItems);
HasItems = Items.Count > 0;
HasMoreItems = content.Items.Count() > Items.Count;
}
private IEnumerable<TSchema> GetVisibleItems<TSchema>(CachedContent<TSchema> content, int visibleItems) where TSchema : SchemaBase
{
if (visibleItems == 0)
{
return content.Items;
}
else
{
return content.Items
.Take(visibleItems);
}
}
}
}
| |
//
// Styles.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin 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 MonoDevelop.Components;
namespace Pinta.Docking
{
public static class Styles
{
public static readonly Cairo.Color BaseBackgroundColor = new Cairo.Color (1, 1, 1);
public static readonly Cairo.Color BaseForegroundColor = new Cairo.Color (0, 0, 0);
// General
public static readonly Gdk.Color ThinSplitterColor = new Gdk.Color (166, 166, 166);
// Document tab bar
public static readonly Cairo.Color TabBarBackgroundColor = CairoExtensions.ParseColor ("c2c2c2");
public static readonly Cairo.Color TabBarActiveTextColor = new Cairo.Color (0, 0, 0);
public static readonly Cairo.Color TabBarActiveGradientStartColor = Shift (TabBarBackgroundColor, 0.92);
public static readonly Cairo.Color TabBarActiveGradientEndColor = TabBarBackgroundColor;
public static readonly Cairo.Color TabBarGradientStartColor = Shift (TabBarBackgroundColor, 1.02);
public static readonly Cairo.Color TabBarGradientEndColor = TabBarBackgroundColor;
public static readonly Cairo.Color TabBarGradientShadowColor = Shift (TabBarBackgroundColor, 0.8);
public static readonly Cairo.Color TabBarHoverActiveTextColor = TabBarActiveTextColor;
public static readonly Cairo.Color TabBarInactiveTextColor = Blend (new Cairo.Color (0, 0, 0), TabBarGradientStartColor, 0.4);
public static readonly Cairo.Color TabBarHoverInactiveTextColor = new Cairo.Color (0, 0, 0);
public static readonly Cairo.Color BreadcrumbGradientStartColor = CairoExtensions.ParseColor ("FFFFFF");
public static readonly Cairo.Color BreadcrumbBackgroundColor = Shift (BreadcrumbGradientStartColor, .95);
public static readonly Cairo.Color BreadcrumbGradientEndColor = Shift (BreadcrumbGradientStartColor, 0.9);
public static readonly Cairo.Color BreadcrumbBorderColor = Shift (BreadcrumbBackgroundColor, 0.6);
public static readonly Cairo.Color BreadcrumbInnerBorderColor = WithAlpha (BaseBackgroundColor, 0.1d);
public static readonly Gdk.Color BreadcrumbTextColor = Shift (BaseForegroundColor, 0.8).ToGdkColor ();
public static readonly Cairo.Color BreadcrumbButtonBorderColor = Shift (BaseBackgroundColor, 0.8);
public static readonly Cairo.Color BreadcrumbButtonFillColor = WithAlpha (BaseBackgroundColor, 0.1d);
public static readonly Cairo.Color BreadcrumbBottomBorderColor = Shift (BreadcrumbBackgroundColor, 0.7d);
public static readonly bool BreadcrumbInvertedIcons = false;
public static readonly bool BreadcrumbGreyscaleIcons = false;
// Dock pads
public static readonly Cairo.Color DockTabBarGradientTop = new Cairo.Color (248d / 255d, 248d / 255d, 248d / 255d);
public static readonly Cairo.Color DockTabBarGradientStart = new Cairo.Color (242d / 255d, 242d / 255d, 242d / 255d);
public static readonly Cairo.Color DockTabBarGradientEnd = new Cairo.Color (230d / 255d, 230d / 255d, 230d / 255d);
public static readonly Cairo.Color DockTabBarShadowGradientStart = new Cairo.Color (154d / 255d, 154d / 255d, 154d / 255d, 1);
public static readonly Cairo.Color DockTabBarShadowGradientEnd = new Cairo.Color (154d / 255d, 154d / 255d, 154d / 255d, 0);
public static readonly Gdk.Color PadBackground = new Gdk.Color (240, 240, 240);
public static readonly Gdk.Color InactivePadBackground = ReduceLight (PadBackground, 0.9);
public static readonly Gdk.Color PadLabelColor = new Gdk.Color (92, 99, 102);
public static readonly Gdk.Color DockFrameBackground = new Gdk.Color (157, 162, 166);
public static readonly Gdk.Color DockSeparatorColor = ThinSplitterColor;
public static readonly Gdk.Color BrowserPadBackground = new Gdk.Color (225, 228, 232);
public static readonly Gdk.Color InactiveBrowserPadBackground = new Gdk.Color (240, 240, 240);
public static readonly Cairo.Color DockBarBackground1 = PadBackground.ToCairoColor ();
public static readonly Cairo.Color DockBarBackground2 = Shift (PadBackground.ToCairoColor (), 0.95);
public static readonly Cairo.Color DockBarSeparatorColorDark = new Cairo.Color (0, 0, 0, 0.2);
public static readonly Cairo.Color DockBarSeparatorColorLight = new Cairo.Color (1, 1, 1, 0.3);
public static readonly Cairo.Color DockBarPrelightColor = CairoExtensions.ParseColor ("ffffff");
// Status area
public static readonly Cairo.Color WidgetBorderColor = CairoExtensions.ParseColor ("8c8c8c");
public static readonly Cairo.Color StatusBarBorderColor = CairoExtensions.ParseColor ("919191");
public static readonly Cairo.Color StatusBarFill1Color = CairoExtensions.ParseColor ("f5fafc");
public static readonly Cairo.Color StatusBarFill2Color = CairoExtensions.ParseColor ("e9f1f3");
public static readonly Cairo.Color StatusBarFill3Color = CairoExtensions.ParseColor ("d8e7ea");
public static readonly Cairo.Color StatusBarFill4Color = CairoExtensions.ParseColor ("d1e3e7");
public static readonly Cairo.Color StatusBarErrorColor = CairoExtensions.ParseColor ("FF6363");
public static readonly Cairo.Color StatusBarInnerColor = new Cairo.Color (0,0,0, 0.08);
public static readonly Cairo.Color StatusBarShadowColor1 = new Cairo.Color (0,0,0, 0.06);
public static readonly Cairo.Color StatusBarShadowColor2 = new Cairo.Color (0,0,0, 0.02);
public static readonly Cairo.Color StatusBarTextColor = CairoExtensions.ParseColor ("555555");
public static readonly Cairo.Color StatusBarProgressBackgroundColor = new Cairo.Color (0, 0, 0, 0.1);
public static readonly Cairo.Color StatusBarProgressOutlineColor = new Cairo.Color (0, 0, 0, 0.1);
public static readonly Pango.FontDescription StatusFont = Pango.FontDescription.FromString ("Normal");
public static int StatusFontPixelHeight { get { return (int)(11 * PixelScale); } }
public static int ProgressBarHeight { get { return (int)(18 * PixelScale); } }
public static int ProgressBarInnerPadding { get { return (int)(4 * PixelScale); } }
public static int ProgressBarOuterPadding { get { return (int)(4 * PixelScale); } }
static readonly double PixelScale = GtkWorkarounds.GetPixelScale ();
// Toolbar
public static readonly Cairo.Color ToolbarBottomBorderColor = new Cairo.Color (0.5, 0.5, 0.5);
public static readonly Cairo.Color ToolbarBottomGlowColor = new Cairo.Color (1, 1, 1, 0.2);
// Code Completion
public static readonly int TooltipInfoSpacing = 1;
// Popover Windows
public static class PopoverWindow
{
public static readonly int PagerTriangleSize = 6;
public static readonly int PagerHeight = 16;
public static readonly Cairo.Color DefaultBackgroundColor = CairoExtensions.ParseColor ("fff3cf");
public static readonly Cairo.Color ErrorBackgroundColor = CairoExtensions.ParseColor ("E27267");
public static readonly Cairo.Color WarningBackgroundColor = CairoExtensions.ParseColor ("efd46c");
public static readonly Cairo.Color InformationBackgroundColor = CairoExtensions.ParseColor ("709DC9");
public static readonly Cairo.Color DefaultBorderColor = CairoExtensions.ParseColor ("ffeeba");
public static readonly Cairo.Color ErrorBorderColor = CairoExtensions.ParseColor ("c97968");
public static readonly Cairo.Color WarningBorderColor = CairoExtensions.ParseColor ("e8c12c");
public static readonly Cairo.Color InformationBorderColor = CairoExtensions.ParseColor ("6688bc");
public static readonly Cairo.Color DefaultTextColor = CairoExtensions.ParseColor ("665a36");
public static readonly Cairo.Color ErrorTextColor = CairoExtensions.ParseColor ("ffffff");
public static readonly Cairo.Color WarningTextColor = CairoExtensions.ParseColor ("563b00");
public static readonly Cairo.Color InformationTextColor = CairoExtensions.ParseColor ("ffffff");
public static class ParamaterWindows
{
public static readonly Cairo.Color GradientStartColor = CairoExtensions.ParseColor ("fffee6");
public static readonly Cairo.Color GradientEndColor = CairoExtensions.ParseColor ("fffcd1");
}
}
// Helper methods
internal static Cairo.Color Shift (Cairo.Color color, double factor)
{
return new Cairo.Color (color.R * factor, color.G * factor, color.B * factor, color.A);
}
internal static Cairo.Color WithAlpha (Cairo.Color c, double alpha)
{
return new Cairo.Color (c.R, c.G, c.B, alpha);
}
internal static Cairo.Color Blend (Cairo.Color color, Cairo.Color targetColor, double factor)
{
return new Cairo.Color (color.R + ((targetColor.R - color.R) * factor),
color.G + ((targetColor.G - color.G) * factor),
color.B + ((targetColor.B - color.B) * factor),
color.A
);
}
internal static Cairo.Color MidColor (double factor)
{
return Blend (BaseBackgroundColor, BaseForegroundColor, factor);
}
internal static Cairo.Color ReduceLight (Cairo.Color color, double factor)
{
var c = color.ToXwtColor ();
c.Light *= factor;
return c.ToCairoColor ();
}
internal static Cairo.Color IncreaseLight (Cairo.Color color, double factor)
{
var c = color.ToXwtColor ();
c.Light += (1 - c.Light) * factor;
return c.ToCairoColor ();
}
internal static Gdk.Color ReduceLight (Gdk.Color color, double factor)
{
return ReduceLight (color.ToCairoColor (), factor).ToGdkColor ();
}
internal static Gdk.Color IncreaseLight (Gdk.Color color, double factor)
{
return IncreaseLight (color.ToCairoColor (), factor).ToGdkColor ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using Qwack.Core.Basic;
using Qwack.Core.Instruments;
using Qwack.Core.Models;
using Qwack.Models.Models;
using Qwack.Models.Risk.Mutators;
namespace Qwack.Models.Risk
{
public class VaRCalculator
{
private readonly IAssetFxModel _model;
private readonly Portfolio _portfolio;
private readonly ILogger _logger;
private readonly Dictionary<string, VaRSpotScenarios> _spotTypeBumps = new();
private readonly Dictionary<string, VaRSpotScenarios> _spotFxTypeBumps = new();
private readonly Dictionary<string, VaRCurveScenarios> _curveTypeBumps = new();
private readonly Dictionary<string, VaRCurveScenarios> _surfaceTypeBumps = new();
private readonly Dictionary<DateTime, IAssetFxModel> _bumpedModels = new();
public VaRCalculator(IAssetFxModel model, Portfolio portfolio, ILogger logger)
{
_model = model;
_portfolio = portfolio;
_logger = logger;
}
public void AddSpotRelativeScenarioBumps(string assetId, Dictionary<DateTime, double> bumps)
{
_logger?.LogInformation($"Adding relative/spot bumps for {assetId}");
_spotTypeBumps[assetId] = new VaRSpotScenarios
{
IsRelativeBump = true,
AssetId = assetId,
Bumps = bumps,
};
}
public void AddSpotAbsoluteScenarioBumps(string assetId, Dictionary<DateTime, double> bumps)
{
_logger?.LogInformation($"Adding absolute/spot bumps for {assetId}");
_spotTypeBumps[assetId] = new VaRSpotScenarios
{
IsRelativeBump = false,
AssetId = assetId,
Bumps = bumps,
};
}
public void AddSpotFxRelativeScenarioBumps(string ccy, Dictionary<DateTime, double> bumps)
{
_logger?.LogInformation($"Adding relative/spot bumps for fx ccy {ccy}");
_spotFxTypeBumps[ccy] = new VaRSpotScenarios
{
IsRelativeBump = true,
AssetId = ccy,
Bumps = bumps,
};
}
public void AddSpotFxAbsoluteScenarioBumps(string ccy, Dictionary<DateTime, double> bumps)
{
_logger?.LogInformation($"Adding absolute/spot bumps for fx ccy {ccy}");
_spotFxTypeBumps[ccy] = new VaRSpotScenarios
{
IsRelativeBump = false,
AssetId = ccy,
Bumps = bumps,
};
}
public void AddCurveRelativeScenarioBumps(string assetId, Dictionary<DateTime, double[]> bumps)
{
_logger?.LogInformation($"Adding relative/curve bumps for {assetId}");
_curveTypeBumps[assetId] = new VaRCurveScenarios
{
IsRelativeBump = true,
AssetId = assetId,
Bumps = bumps,
};
}
public void AddCurveAbsoluteScenarioBumps(string assetId, Dictionary<DateTime, double[]> bumps)
{
_logger?.LogInformation($"Adding absolute/curve bumps for {assetId}");
_curveTypeBumps[assetId] = new VaRCurveScenarios
{
IsRelativeBump = false,
AssetId = assetId,
Bumps = bumps,
};
}
public void AddSurfaceAtmRelativeScenarioBumps(string assetId, Dictionary<DateTime, double[]> bumps)
{
_logger?.LogInformation($"Adding relative/surface atm bumps for {assetId}");
_surfaceTypeBumps[assetId] = new VaRCurveScenarios
{
IsRelativeBump = true,
AssetId = assetId,
Bumps = bumps,
};
}
public void AddSurfaceAtmAbsoluteScenarioBumps(string assetId, Dictionary<DateTime, double[]> bumps)
{
_logger?.LogInformation($"Adding absolute/surface atm bumps for {assetId}");
_surfaceTypeBumps[assetId] = new VaRCurveScenarios
{
IsRelativeBump = false,
AssetId = assetId,
Bumps = bumps,
};
}
public void CalculateModels()
{
var allAssetIds = _portfolio.AssetIds();
var allDates = _spotTypeBumps.First().Value.Bumps.Keys.ToList();
foreach(var kv in _spotTypeBumps)
{
allDates = allDates.Intersect(kv.Value.Bumps.Keys).ToList();
}
foreach (var kv in _curveTypeBumps)
{
allDates = allDates.Intersect(kv.Value.Bumps.Keys).ToList();
}
_logger?.LogInformation($"Total of {allDates.Count} dates");
foreach (var d in allDates)
{
_logger?.LogInformation($"Computing scenarios for {d}");
var m = _model.Clone();
foreach (var assetId in allAssetIds)
{
if (_spotTypeBumps.TryGetValue(assetId, out var spotBumpRecord))
{
if (spotBumpRecord.IsRelativeBump)
m = RelativeShiftMutator.AssetCurveShift(assetId, spotBumpRecord.Bumps[d], m);
else
m = FlatShiftMutator.AssetCurveShift(assetId, spotBumpRecord.Bumps[d], m);
}
else if (_curveTypeBumps.TryGetValue(assetId, out var curveBumpRecord))
{
if (curveBumpRecord.IsRelativeBump)
m = CurveShiftMutator.AssetCurveShiftRelative(assetId, curveBumpRecord.Bumps[d], m);
else
m = CurveShiftMutator.AssetCurveShiftAbsolute(assetId, curveBumpRecord.Bumps[d], m);
}
else
{
_logger?.LogWarning($"No shift data available for {assetId} / {d}");
}
if (_surfaceTypeBumps.TryGetValue(assetId, out var surfaceBumpRecord))
{
if (surfaceBumpRecord.IsRelativeBump)
m = SurfaceShiftMutator.AssetSurfaceShiftRelative(assetId, surfaceBumpRecord.Bumps[d], m);
else
m = SurfaceShiftMutator.AssetSurfaceShiftAbsolute(assetId, surfaceBumpRecord.Bumps[d], m);
}
}
foreach(var ccy in m.FundingModel.FxMatrix.SpotRates.Keys)
{
if (_spotFxTypeBumps.TryGetValue(ccy, out var spotBumpRecord))
{
if (spotBumpRecord.IsRelativeBump)
m = RelativeShiftMutator.SpotFxShift(ccy, spotBumpRecord.Bumps[d], m);
//else
// m = FlatShiftMutator.AssetCurveShift(assetId, spotBumpRecord.Bumps[d], m);
}
}
_bumpedModels[d] = m;
}
}
public (double VaR, DateTime ScenarioDate) CalculateVaR(double ci, Currency ccy)
{
var basePv = _portfolio.PV(_model, ccy).SumOfAllRows;
var results = new Dictionary<DateTime, double>();
foreach (var kv in _bumpedModels)
{
var scenarioPv = _portfolio.PV(kv.Value, ccy).SumOfAllRows;
results[kv.Key] = scenarioPv - basePv;
}
var sortedResults = results.OrderBy(kv=>kv.Value).ToList();
var ixCi = (int)System.Math.Floor(sortedResults.Count() * (1.0 - ci));
var ciResult = sortedResults[System.Math.Min(System.Math.Max(ixCi,0), sortedResults.Count-1)];
return (ciResult.Value, ciResult.Key);
}
internal class VaRSpotScenarios
{
public bool IsRelativeBump { get; set; }
public string AssetId { get; set; }
public Dictionary<DateTime, double> Bumps { get; set; }
}
internal class VaRCurveScenarios
{
public bool IsRelativeBump { get; set; }
public string AssetId { get; set; }
public Dictionary<DateTime, double[]> Bumps { get; set; }
}
}
}
| |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.MappingModel;
using FluentNHibernate.Utils;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.Inspection
{
[TestFixture, Category("Inspection DSL")]
public class VersionInspectorMapsToVersionMapping
{
private VersionMapping mapping;
private IVersionInspector inspector;
[SetUp]
public void CreateDsl()
{
mapping = new VersionMapping();
inspector = new VersionInspector(mapping);
}
[Test]
public void AccessMapped()
{
mapping.Access = "field";
inspector.Access.ShouldEqual(Access.Field);
}
[Test]
public void AccessIsSet()
{
mapping.Access = "field";
inspector.IsSet(Prop(x => x.Access))
.ShouldBeTrue();
}
[Test]
public void AccessIsNotSet()
{
inspector.IsSet(Prop(x => x.Access))
.ShouldBeFalse();
}
[Test]
public void ColumnCollectionHasSameCountAsMapping()
{
mapping.AddColumn(new ColumnMapping());
inspector.Columns.Count().ShouldEqual(1);
}
[Test]
public void ColumnsCollectionOfInspectors()
{
mapping.AddColumn(new ColumnMapping());
inspector.Columns.First().ShouldBeOfType<IColumnInspector>();
}
[Test]
public void ColumnsCollectionIsEmpty()
{
inspector.Columns.IsEmpty().ShouldBeTrue();
}
[Test]
public void GeneratedMapped()
{
mapping.Generated = "insert";
inspector.Generated.ShouldEqual(Generated.Insert);
}
[Test]
public void GeneratedIsSet()
{
mapping.Generated = "insert";
inspector.IsSet(Prop(x => x.Generated))
.ShouldBeTrue();
}
[Test]
public void GeneratedIsNotSet()
{
inspector.IsSet(Prop(x => x.Generated))
.ShouldBeFalse();
}
[Test]
public void NameMapped()
{
mapping.Name = "name";
inspector.Name.ShouldEqual("name");
}
[Test]
public void NameIsSet()
{
mapping.Name = "name";
inspector.IsSet(Prop(x => x.Name))
.ShouldBeTrue();
}
[Test]
public void NameIsNotSet()
{
inspector.IsSet(Prop(x => x.Name))
.ShouldBeFalse();
}
[Test]
public void TypeMapped()
{
mapping.Type = new TypeReference(typeof(string));
inspector.Type.ShouldEqual(new TypeReference(typeof(string)));
}
[Test]
public void TypeIsSet()
{
mapping.Type = new TypeReference(typeof(string));
inspector.IsSet(Prop(x => x.Type))
.ShouldBeTrue();
}
[Test]
public void TypeIsNotSet()
{
inspector.IsSet(Prop(x => x.Type))
.ShouldBeFalse();
}
[Test]
public void UnsavedValueMapped()
{
mapping.UnsavedValue = "test";
inspector.UnsavedValue.ShouldEqual("test");
}
[Test]
public void UnsavedValueIsSet()
{
mapping.UnsavedValue = "test";
inspector.IsSet(Prop(x => x.UnsavedValue))
.ShouldBeTrue();
}
[Test]
public void UnsavedValueIsNotSet()
{
inspector.IsSet(Prop(x => x.UnsavedValue))
.ShouldBeFalse();
}
[Test]
public void LengthMapped()
{
mapping.AddColumn(new ColumnMapping { Length = 100 });
inspector.Length.ShouldEqual(100);
}
[Test]
public void LengthIsSet()
{
mapping.AddColumn(new ColumnMapping { Length = 100 });
inspector.IsSet(Prop(x => x.Length))
.ShouldBeTrue();
}
[Test]
public void LengthIsNotSet()
{
inspector.IsSet(Prop(x => x.Length))
.ShouldBeFalse();
}
[Test]
public void PrecisionIsSet()
{
mapping.AddColumn(new ColumnMapping { Precision = 10 });
inspector.IsSet(Prop(x => x.Precision))
.ShouldBeTrue();
}
[Test]
public void PrecisionIsNotSet()
{
inspector.IsSet(Prop(x => x.Precision))
.ShouldBeFalse();
}
[Test]
public void ScaleMapped()
{
mapping.AddColumn(new ColumnMapping { Scale = 10 });
inspector.Scale.ShouldEqual(10);
}
[Test]
public void ScaleIsSet()
{
mapping.AddColumn(new ColumnMapping { Scale = 10 });
inspector.IsSet(Prop(x => x.Scale))
.ShouldBeTrue();
}
[Test]
public void ScaleIsNotSet()
{
inspector.IsSet(Prop(x => x.Scale))
.ShouldBeFalse();
}
[Test]
public void NullableMapped()
{
mapping.AddColumn(new ColumnMapping { NotNull = false });
inspector.Nullable.ShouldEqual(true);
}
[Test]
public void NullableIsSet()
{
mapping.AddColumn(new ColumnMapping { NotNull = false });
inspector.IsSet(Prop(x => x.Nullable))
.ShouldBeTrue();
}
[Test]
public void NullableIsNotSet()
{
inspector.IsSet(Prop(x => x.Nullable))
.ShouldBeFalse();
}
[Test]
public void UniqueMapped()
{
mapping.AddColumn(new ColumnMapping { Unique = true });
inspector.Unique.ShouldEqual(true);
}
[Test]
public void UniqueIsSet()
{
mapping.AddColumn(new ColumnMapping { Unique = true });
inspector.IsSet(Prop(x => x.Unique))
.ShouldBeTrue();
}
[Test]
public void UniqueIsNotSet()
{
inspector.IsSet(Prop(x => x.Unique))
.ShouldBeFalse();
}
[Test]
public void UniqueKeyMapped()
{
mapping.AddColumn(new ColumnMapping { UniqueKey = "key" });
inspector.UniqueKey.ShouldEqual("key");
}
[Test]
public void UniqueKeyIsSet()
{
mapping.AddColumn(new ColumnMapping { UniqueKey = "key" });
inspector.IsSet(Prop(x => x.UniqueKey))
.ShouldBeTrue();
}
[Test]
public void UniqueKeyIsNotSet()
{
inspector.IsSet(Prop(x => x.UniqueKey))
.ShouldBeFalse();
}
[Test]
public void SqlTypeMapped()
{
mapping.AddColumn(new ColumnMapping { SqlType = "sql" });
inspector.SqlType.ShouldEqual("sql");
}
[Test]
public void SqlTypeIsSet()
{
mapping.AddColumn(new ColumnMapping { SqlType = "sql" });
inspector.IsSet(Prop(x => x.SqlType))
.ShouldBeTrue();
}
[Test]
public void SqlTypeIsNotSet()
{
inspector.IsSet(Prop(x => x.SqlType))
.ShouldBeFalse();
}
[Test]
public void IndexMapped()
{
mapping.AddColumn(new ColumnMapping { Index = "index" });
inspector.Index.ShouldEqual("index");
}
[Test]
public void IndexIsSet()
{
mapping.AddColumn(new ColumnMapping { Index = "index" });
inspector.IsSet(Prop(x => x.Index))
.ShouldBeTrue();
}
[Test]
public void IndexIsNotSet()
{
inspector.IsSet(Prop(x => x.Index))
.ShouldBeFalse();
}
[Test]
public void CheckMapped()
{
mapping.AddColumn(new ColumnMapping { Check = "key" });
inspector.Check.ShouldEqual("key");
}
[Test]
public void CheckIsSet()
{
mapping.AddColumn(new ColumnMapping { Check = "key" });
inspector.IsSet(Prop(x => x.Check))
.ShouldBeTrue();
}
[Test]
public void CheckIsNotSet()
{
inspector.IsSet(Prop(x => x.Check))
.ShouldBeFalse();
}
[Test]
public void DefaultMapped()
{
mapping.AddColumn(new ColumnMapping { Default = "key" });
inspector.Default.ShouldEqual("key");
}
[Test]
public void DefaultIsSet()
{
mapping.AddColumn(new ColumnMapping { Default = "key" });
inspector.IsSet(Prop(x => x.Default))
.ShouldBeTrue();
}
[Test]
public void DefaultIsNotSet()
{
inspector.IsSet(Prop(x => x.Default))
.ShouldBeFalse();
}
#region Helpers
private PropertyInfo Prop(Expression<Func<IVersionInspector, object>> propertyExpression)
{
return ReflectionHelper.GetProperty(propertyExpression);
}
#endregion
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using FluentCassandra.Thrift.Collections;
using FluentCassandra.Thrift.Protocol;
using FluentCassandra.Thrift.Transport;
namespace FluentCassandra.Thrift.Server
{
/// <summary>
/// Server that uses C# threads (as opposed to the ThreadPool) when handling requests
/// </summary>
public class TThreadedServer : TServer
{
private const int DEFAULT_MAX_THREADS = 100;
private volatile bool stop = false;
private readonly int maxThreads;
private Queue<TTransport> clientQueue;
private THashSet<Thread> clientThreads;
private object clientLock;
private Thread workerThread;
public TThreadedServer(TProcessor processor, TServerTransport serverTransport)
: this(processor, serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadedServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate)
: this(processor, serverTransport,
new TTransportFactory(), new TTransportFactory(),
new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(),
DEFAULT_MAX_THREADS, logDelegate)
{
}
public TThreadedServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory transportFactory,
TProtocolFactory protocolFactory)
: this(processor, serverTransport,
transportFactory, transportFactory,
protocolFactory, protocolFactory,
DEFAULT_MAX_THREADS, DefaultLogDelegate)
{
}
public TThreadedServer(TProcessor processor,
TServerTransport serverTransport,
TTransportFactory inputTransportFactory,
TTransportFactory outputTransportFactory,
TProtocolFactory inputProtocolFactory,
TProtocolFactory outputProtocolFactory,
int maxThreads, LogDelegate logDel)
: base(processor, serverTransport, inputTransportFactory, outputTransportFactory,
inputProtocolFactory, outputProtocolFactory, logDel)
{
this.maxThreads = maxThreads;
clientQueue = new Queue<TTransport>();
clientLock = new object();
clientThreads = new THashSet<Thread>();
}
/// <summary>
/// Use new Thread for each new client connection. block until numConnections < maxThreads
/// </summary>
public override void Serve()
{
try
{
//start worker thread
workerThread = new Thread(new ThreadStart(Execute));
workerThread.Start();
serverTransport.Listen();
}
catch (TTransportException ttx)
{
logDelegate("Error, could not listen on ServerTransport: " + ttx);
return;
}
while (!stop)
{
int failureCount = 0;
try
{
TTransport client = serverTransport.Accept();
lock (clientLock)
{
clientQueue.Enqueue(client);
Monitor.Pulse(clientLock);
}
}
catch (TTransportException ttx)
{
if (stop)
{
logDelegate("TThreadPoolServer was shutting down, caught " + ttx);
}
else
{
++failureCount;
logDelegate(ttx.ToString());
}
}
}
if (stop)
{
try
{
serverTransport.Close();
}
catch (TTransportException ttx)
{
logDelegate("TServeTransport failed on close: " + ttx.Message);
}
stop = false;
}
}
/// <summary>
/// Loops on processing a client forever
/// threadContext will be a TTransport instance
/// </summary>
/// <param name="threadContext"></param>
private void Execute()
{
while (!stop)
{
TTransport client;
Thread t;
lock (clientLock)
{
//don't dequeue if too many connections
while (clientThreads.Count >= maxThreads)
{
Monitor.Wait(clientLock);
}
while (clientQueue.Count == 0)
{
Monitor.Wait(clientLock);
}
client = clientQueue.Dequeue();
t = new Thread(new ParameterizedThreadStart(ClientWorker));
clientThreads.Add(t);
}
//start processing requests from client on new thread
t.Start(client);
}
}
private void ClientWorker(Object context)
{
TTransport client = (TTransport)context;
TTransport inputTransport = null;
TTransport outputTransport = null;
TProtocol inputProtocol = null;
TProtocol outputProtocol = null;
try
{
using (inputTransport = inputTransportFactory.GetTransport(client))
{
using (outputTransport = outputTransportFactory.GetTransport(client))
{
inputProtocol = inputProtocolFactory.GetProtocol(inputTransport);
outputProtocol = outputProtocolFactory.GetProtocol(outputTransport);
while (processor.Process(inputProtocol, outputProtocol))
{
//keep processing requests until client disconnects
}
}
}
}
catch (TTransportException)
{
}
catch (Exception x)
{
logDelegate("Error: " + x);
}
lock (clientLock)
{
clientThreads.Remove(Thread.CurrentThread);
Monitor.Pulse(clientLock);
}
return;
}
public override void Stop()
{
stop = true;
serverTransport.Close();
//clean up all the threads myself
workerThread.Abort();
foreach (Thread t in clientThreads)
{
t.Abort();
}
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlTypes;
public partial class Backoffice_Controls_EditRuangRI : System.Web.UI.UserControl
{
public int NoKe = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
private void ModeEditForm()
{
pnlList.Visible = false;
pnlEdit.Visible = true;
pnlView.Visible = false;
lblError.Text = "";
lblWarning.Text = "";
}
private void ModePindahForm()
{
pnlList.Visible = false;
pnlEdit.Visible = true;
pnlView.Visible = true;
lblError.Text = "";
lblWarning.Text = "";
}
private void ModeListForm()
{
pnlList.Visible = true;
pnlEdit.Visible = false;
pnlView.Visible = false;
}
private void ModeViewForm()
{
lblWarning.Text = "";
GV.EditIndex = -1;
pnlList.Visible = false;
pnlEdit.Visible = false;
pnlView.Visible = true;
}
protected void GV_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GV.PageIndex = e.NewPageIndex;
GV.SelectedIndex = -1;
BindDataGrid();
}
protected void GV_Sorting(object sender, GridViewSortEventArgs e)
{
String strSortBy = GV.Attributes["SortField"];
String strSortAscending = GV.Attributes["SortAscending"];
// Sets the new sorting field
GV.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
GV.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
GV.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
GV.SelectedIndex = -1;
BindDataGrid();
}
protected void GV_RowEditing(object sender, GridViewEditEventArgs e)
{
lblTitleEditForm.Text = "Pulang/Keluar Ruang Inap";
GV.SelectedIndex = e.NewEditIndex;
string key = GV.DataKeys[e.NewEditIndex].Value.ToString();
FillFormEdit(key);
ModeEditForm();
}
protected void GV_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
txtTempatInapId.Text = GV.DataKeys[e.NewSelectedIndex].Value.ToString();
PindahTempatInap(txtTempatInapId.Text);
lblTitleEditForm.Text = "Ruang Inap Baru";
ModePindahForm();
}
protected void btnEditDetil_Click(object sender, EventArgs e)
{
FillFormEdit(txtTempatInapId.Text);
lblTitleEditForm.Text = "Edit Data Ruang Inap";
ModeEditForm();
}
protected void GV_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int i = e.RowIndex;
DeleteData(GV.DataKeys[i].Value.ToString());
}
protected void btnCancel_Click(object sender, EventArgs e)
{
ModeListForm();
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveData();
}
protected void btnBack_Click(object sender, EventArgs e)
{
ModeListForm();
}
protected void btnDeleteDetil_Click(object sender, EventArgs e)
{
DeleteData(lblTempatInapId.Text);
}
public void BindDataGrid()
{
DataView dv = GetData();
dv.Sort = GV.Attributes["SortField"];
if (GV.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
int intRowCount = dv.Count;
int intPageSaze = GV.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (GV.PageIndex >= intPageCount)
GV.PageIndex = intPageCount - 1;
}
else
{
GV.PageIndex = 0;
}
NoKe = GV.PageSize * GV.PageIndex;
GV.DataSource = dv;
GV.DataBind();
ModeListForm();
}
//===================================================================
// POLULATE DATA REFERENSI
//===================================================================
public void GetListKelas(string KelasId)
{
SIMRS.DataAccess.RS_Kelas myObj = new SIMRS.DataAccess.RS_Kelas();
if (KelasId != "")
myObj.Id = int.Parse(KelasId);
DataTable dt = myObj.GetListAvaliableEdit();
cmbKelas.Items.Clear();
int i = 0;
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = "";
cmbKelas.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelas.Items.Add("");
cmbKelas.Items[i].Text = dr["KelasNama"].ToString();
cmbKelas.Items[i].Value = dr["KelasId"].ToString();
if (dr["KelasId"].ToString() == KelasId)
{
cmbKelas.SelectedIndex = i;
}
i++;
}
}
public void GetListRuang(string RuangId)
{
int KelasId = 0;
if (cmbKelas.SelectedIndex > 0)
KelasId = int.Parse(cmbKelas.SelectedItem.Value);
SIMRS.DataAccess.RS_Ruang myObj = new SIMRS.DataAccess.RS_Ruang();
if (RuangId != "")
myObj.Id = int.Parse(RuangId);
DataTable dt = myObj.GetListAvaliableEditByKelasId(KelasId);
cmbRuang.Items.Clear();
int i = 0;
cmbRuang.Items.Add("");
cmbRuang.Items[i].Text = "";
cmbRuang.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbRuang.Items.Add("");
cmbRuang.Items[i].Text = dr["RuangNama"].ToString();
cmbRuang.Items[i].Value = dr["RuangId"].ToString();
if (dr["RuangId"].ToString() == RuangId)
{
cmbRuang.SelectedIndex = i;
}
i++;
}
}
public void GetListNomorRuang(string RuangRawatId)
{
SIMRS.DataAccess.RS_RuangRawat myObj = new SIMRS.DataAccess.RS_RuangRawat();
if (cmbKelas.SelectedIndex > 0)
myObj.KelasId = int.Parse(cmbKelas.SelectedItem.Value);
if (cmbRuang.SelectedIndex > 0)
myObj.RuangId = int.Parse(cmbRuang.SelectedItem.Value);
if (RuangRawatId != "")
myObj.RuangRawatId = int.Parse(RuangRawatId);
DataTable dt = myObj.GetListAvaliableNomorRuangEdit();
cmbNomorRuang.Items.Clear();
int i = 0;
cmbNomorRuang.Items.Add("");
cmbNomorRuang.Items[i].Text = "";
cmbNomorRuang.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbNomorRuang.Items.Add("");
cmbNomorRuang.Items[i].Text = dr["NomorRuang"].ToString();
cmbNomorRuang.Items[i].Value = dr["RuangRawatId"].ToString();
if (dr["RuangRawatId"].ToString() == RuangRawatId)
{
cmbNomorRuang.SelectedIndex = i;
}
i++;
}
}
public void GetListNomorTempat(string TempatTidurId)
{
SIMRS.DataAccess.RS_TempatTidur myObj = new SIMRS.DataAccess.RS_TempatTidur();
if (cmbNomorRuang.SelectedIndex > 0)
myObj.RuangRawatId = int.Parse(cmbNomorRuang.SelectedItem.Value);
if (TempatTidurId != "")
myObj.TempatTidurId = int.Parse(TempatTidurId);
DataTable dt = myObj.GetListAvaliableEditByRawatId();
cmbNomorTempat.Items.Clear();
int i = 0;
cmbNomorTempat.Items.Add("");
cmbNomorTempat.Items[i].Text = "";
cmbNomorTempat.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbNomorTempat.Items.Add("");
cmbNomorTempat.Items[i].Text = dr["NomorTempat"].ToString();
cmbNomorTempat.Items[i].Value = dr["TempatTidurId"].ToString();
if (dr["TempatTidurId"].ToString() == TempatTidurId)
{
cmbNomorTempat.SelectedIndex = i;
}
i++;
}
}
//===================================================================
public void SetDataRawatInap(string RawatInapId, string StatusRawatInap)
{
txtRawatInapId.Text = RawatInapId;
txtStatusRawatInap.Text = StatusRawatInap;
}
public DataView GetData()
{
SIMRS.DataAccess.RS_TempatInap objData = new SIMRS.DataAccess.RS_TempatInap();
objData.RawatInapId = Int64.Parse(txtRawatInapId.Text);
DataTable dt = objData.SelectAllWRawatInapIdLogic();
return dt.DefaultView;
}
private void EmptyFormEdit()
{
txtTempatInapId.Text = "0";
txtTanggalMasuk.Text = "";
txtJamMasuk.Text = "";
txtTanggalKeluar.Text = "";
txtJamKeluar.Text = "";
GetListKelas("");
GetListRuang("");
GetListNomorRuang("");
GetListNomorTempat("");
txtKeterangan.Text = "";
}
private void FillFormEdit(string TempatInapId)
{
SIMRS.DataAccess.RS_TempatInap myObj = new SIMRS.DataAccess.RS_TempatInap();
myObj.TempatInapId = Int64.Parse(TempatInapId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
txtTempatInapId.Text = dr["TempatInapId"].ToString();
txtTanggalMasuk.Text = dr["TanggalMasuk"].ToString() != "" ? ((DateTime)dr["TanggalMasuk"]).ToString("dd/MM/yyyy") : "";
txtJamMasuk.Text = dr["TanggalMasuk"].ToString() != "" ? ((DateTime)dr["TanggalMasuk"]).ToString("HH:mm") : "";
txtTanggalKeluar.Text = dr["TanggalKeluar"].ToString() != "" ? ((DateTime)dr["TanggalKeluar"]).ToString("dd/MM/yyyy") : "";
txtJamKeluar.Text = dr["TanggalKeluar"].ToString() != "" ? ((DateTime)dr["TanggalKeluar"]).ToString("HH:mm") : "";
txtJamInap.Text = dr["JamInap"].ToString();
GetListKelas(dr["KelasId"].ToString());
GetListRuang(dr["RuangId"].ToString());
GetListNomorRuang(dr["RuangRawatId"].ToString());
GetListNomorTempat(dr["TempatTidurId"].ToString());
txtKeterangan.Text = dr["Keterangan"].ToString();
}
}
private void PindahTempatInap(string TempatInapId)
{
SIMRS.DataAccess.RS_TempatInap myObj = new SIMRS.DataAccess.RS_TempatInap();
myObj.TempatInapId = Int64.Parse(TempatInapId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
lblTempatInapId.Text = dr["TempatInapId"].ToString();
lblTanggalMasuk.Text = dr["TanggalMasuk"].ToString() != "" ? ((DateTime)dr["TanggalMasuk"]).ToString("dd/MM/yyyy HH:mm") : "";
lblJamMasuk.Text = dr["TanggalMasuk"].ToString() != "" ? ((DateTime)dr["TanggalMasuk"]).ToString("HH:mm") : "";
lblTanggalKeluar.Text = dr["TanggalKeluar"].ToString() != "" ? ((DateTime)dr["TanggalKeluar"]).ToString("dd/MM/yyyy") : "";
lblJamKeluar.Text = dr["TanggalKeluar"].ToString() != "" ? ((DateTime)dr["TanggalKeluar"]).ToString("HH:mm") : "";
lblRuangRawat.Text = dr["KelasNama"].ToString() + " - " + dr["RuangNama"].ToString() + "-" + dr["NomorRuang"].ToString();
lblNomorTempat.Text = dr["NomorTempat"].ToString();
lblKeterangan.Text = dr["Keterangan"].ToString().Replace("\r\n", "<br />");
txtTempatInapId.Text = "0";
txtTanggalMasuk.Text = "";
txtJamMasuk.Text = "";
txtTanggalKeluar.Text = "";
txtJamKeluar.Text = "";
txtJamInap.Text = "";
GetListKelas("");
GetListRuang("");
GetListNomorRuang("");
GetListNomorTempat("");
txtKeterangan.Text = dr["Keterangan"].ToString();
}
}
private void FillFormView(string TempatInapId)
{
SIMRS.DataAccess.RS_TempatInap myObj = new SIMRS.DataAccess.RS_TempatInap();
myObj.TempatInapId = Int64.Parse(TempatInapId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
lblTempatInapId.Text = dr["TempatInapId"].ToString();
lblKeterangan.Text = dr["Keterangan"].ToString().Replace("\r\n","<br />");
}
}
private void SaveData()
{
lblError.Text = "";
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
if (!Page.IsValid)
{
return;
}
int UserId = (int)Session["SIMRS.UserId"];
SIMRS.DataAccess.RS_TempatInap myObj = new SIMRS.DataAccess.RS_TempatInap();
myObj.TempatInapId = Int64.Parse(txtTempatInapId.Text);
if (myObj.TempatInapId > 0)
myObj.SelectOne();
if (cmbNomorRuang.SelectedIndex > 0)
myObj.RuangRawatId = int.Parse(cmbNomorRuang.SelectedItem.Value);
if (cmbNomorTempat.SelectedIndex > 0)
myObj.TempatTidurId = int.Parse(cmbNomorTempat.SelectedItem.Value);
DateTime TanggalMasuk = DateTime.Parse(txtTanggalMasuk.Text);
TanggalMasuk = TanggalMasuk.AddHours(double.Parse(txtJamMasuk.Text.Substring(0, 2)));
TanggalMasuk = TanggalMasuk.AddMinutes(double.Parse(txtJamMasuk.Text.Substring(3, 2)));
myObj.TanggalMasuk = TanggalMasuk;
myObj.RawatInapId = Int64.Parse(txtRawatInapId.Text);
myObj.Keterangan = txtKeterangan.Text;
if (myObj.TempatInapId == 0)
{
//Kondisi Insert Data
myObj.TempatInapIdOld = Int64.Parse(lblTempatInapId.Text);
myObj.CreatedBy = UserId;
myObj.CreatedDate = DateTime.Now;
myObj.Pindah();
lblWarning.Text = Resources.GetString("", "WarSuccessSave");
Response.Redirect("RIRuangView.aspx?RawatInapId=" + txtRawatInapId.Text);
}
else
{
//Kondisi Update Data
if (txtTanggalKeluar.Text != "")
{
DateTime TanggalKeluar = DateTime.Parse(txtTanggalKeluar.Text);
if (txtJamKeluar.Text != "")
{
TanggalKeluar = TanggalKeluar.AddHours(double.Parse(txtJamKeluar.Text.Substring(0, 2)));
TanggalKeluar = TanggalKeluar.AddMinutes(double.Parse(txtJamKeluar.Text.Substring(3, 2)));
}
myObj.TanggalKeluar = TanggalKeluar;
}
else
{
lblError.Text = "Tanggal Keluar Harus diisi !";
return;
}
myObj.ModifiedBy = UserId;
myObj.ModifiedDate = DateTime.Now;
myObj.Pulang();
lblWarning.Text = Resources.GetString("", "WarSuccessSave");
Response.Redirect("RIRuangView.aspx?RawatInapId=" + txtRawatInapId.Text);
}
BindDataGrid();
ModeListForm();
}
private void DeleteData(string TempatInapId)
{
SIMRS.DataAccess.RS_TempatInap myObj = new SIMRS.DataAccess.RS_TempatInap();
myObj.TempatInapId = int.Parse(TempatInapId);
myObj.SelectOne();
try
{
myObj.Delete();
GV.SelectedIndex = -1;
BindDataGrid();
lblWarning.Text = Resources.GetString("", "WarSuccessDelete");
ModeListForm();
Response.Redirect("RIRuangView.aspx?RawatInapId=" + txtRawatInapId.Text);
}
catch
{
lblWarning.Text = Resources.GetString("", "WarAlreadyUsed");
}
}
protected void txtTanggalMasuk_TextChanged(object sender, EventArgs e)
{
if (MEVTanggalMasuk.IsValid)
{
lblTanggalKeluar.Text = txtTanggalMasuk.Text;
}
}
protected void txtJamMasuk_TextChanged(object sender, EventArgs e)
{
if (MEVJamMasuk.IsValid)
{
lblJamKeluar.Text = txtJamMasuk.Text;
}
}
protected void cmbKelas_SelectedIndexChanged(object sender, EventArgs e)
{
GetListRuang("");
}
protected void cmbRuang_SelectedIndexChanged(object sender, EventArgs e)
{
GetListNomorRuang("");
}
protected void cmbNomorRuang_SelectedIndexChanged(object sender, EventArgs e)
{
GetListNomorTempat("");
}
public bool GetLinkDelete(string FlagTerakhir, string i)
{
if (FlagTerakhir == "True" && i != "1" && txtStatusRawatInap.Text == "0")
return true;
else
return false;
}
public bool GetLinkPulang(string FlagTerakhir)
{
if (FlagTerakhir == "True" && txtStatusRawatInap.Text == "0")
return true;
else
return false;
}
public bool GetLinkPindah(string FlagTerakhir)
{
if (FlagTerakhir == "True" && txtStatusRawatInap.Text == "0")
return true;
else
return false;
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudioTools.Project {
/// <summary>
/// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default.
/// Set this attribute to false on Properties that should not be visible for Automation.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class AutomationBrowsableAttribute : System.Attribute {
public AutomationBrowsableAttribute(bool browsable) {
this.browsable = browsable;
}
public bool Browsable {
get {
return this.browsable;
}
}
private bool browsable;
}
/// <summary>
/// This attribute is used to mark properties that shouldn't be serialized. Marking properties with this will
/// result in them not being serialized and not being bold in the properties pane.
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
internal sealed class AlwaysSerializedAttribute : Attribute {
public AlwaysSerializedAttribute() { }
}
/// <summary>
/// To create your own localizable node properties, subclass this and add public properties
/// decorated with your own localized display name, category and description attributes.
/// </summary>
[ComVisible(true)]
public class NodeProperties : LocalizableProperties,
ISpecifyPropertyPages,
IVsGetCfgProvider,
IVsSpecifyProjectDesignerPages,
IVsBrowseObject {
#region fields
private HierarchyNode node;
#endregion
#region properties
[Browsable(false)]
[AutomationBrowsable(true)]
public object Node {
get { return this.node; }
}
internal HierarchyNode HierarchyNode {
get { return this.node; }
}
/// <summary>
/// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned.
/// </summary>
[Browsable(false)]
[AutomationBrowsable(false)]
public virtual string Name {
get { return this.node.Caption; }
}
#endregion
#region ctors
internal NodeProperties(HierarchyNode node) {
Utilities.ArgumentNotNull("node", node);
this.node = node;
}
#endregion
#region ISpecifyPropertyPages methods
public virtual void GetPages(CAUUID[] pages) {
this.GetCommonPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns></returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages) {
this.GetCommonPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsGetCfgProvider methods
public virtual int GetCfgProvider(out IVsCfgProvider p) {
p = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsBrowseObject methods
/// <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(node);
hier = node.ProjectMgr.GetOuterInterface<IVsHierarchy>();
itemid = this.node.ID;
return VSConstants.S_OK;
}
#endregion
#region overridden methods
/// <summary>
/// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base
/// </summary>
/// <returns>Caption of Hierarchy node instance</returns>
public override string GetComponentName() {
string caption = this.HierarchyNode.Caption;
if (string.IsNullOrEmpty(caption)) {
return base.GetComponentName();
} else {
return caption;
}
}
#endregion
#region helper methods
protected string GetProperty(string name, string def) {
string a = this.HierarchyNode.ItemNode.GetMetadata(name);
return (a == null) ? def : a;
}
protected void SetProperty(string name, string value) {
this.HierarchyNode.ItemNode.SetMetadata(name, value);
}
/// <summary>
/// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support
/// configuration independent properties.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCommonPropertyPages(CAUUID[] pages) {
// We do not check whether the supportsProjectDesigner is set to false 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), "pages");
}
// Only the project should show the property page the rest should show the project properties.
if (this.node != null && (this.node is ProjectNode)) {
// Retrieve 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 = HierarchyNode.ProjectMgr.GetOuterInterface<IVsHierarchy>();
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant));
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);
}
} else {
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
}
#endregion
#region ExtenderSupport
[Browsable(false)]
public virtual string ExtenderCATID {
get {
Guid catid = this.HierarchyNode.ProjectMgr.GetCATIDForType(this.GetType());
if (Guid.Empty.CompareTo(catid) == 0) {
return null;
}
return catid.ToString("B");
}
}
[Browsable(false)]
public object ExtenderNames() {
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders));
Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object");
return extenderService.GetExtenderNames(this.ExtenderCATID, this);
}
public object Extender(string extenderName) {
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders));
Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object");
return extenderService.GetExtender(this.ExtenderCATID, extenderName, this);
}
#endregion
}
[ComVisible(true)]
public class FileNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
[AlwaysSerialized]
public virtual string FileName {
get {
return this.HierarchyNode.Caption;
}
set {
this.HierarchyNode.SetEditLabel(value);
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath {
get {
return this.HierarchyNode.Url;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string URL {
get {
return this.HierarchyNode.Url;
}
}
[Browsable(false)]
public string Extension {
get {
return Path.GetExtension(this.HierarchyNode.Caption);
}
}
[Browsable(false)]
public bool IsLinkFile {
get {
return HierarchyNode.IsLinkFile;
}
}
#endregion
#endregion
#region ctors
internal FileNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
public override string GetClassName() {
return SR.GetString(SR.FileProperties);
}
}
[ComVisible(true)]
public class ExcludedFileNodeProperties : FileNodeProperties {
internal ExcludedFileNodeProperties(HierarchyNode node)
: base(node) {
}
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
[TypeConverter(typeof(BuildActionTypeConverter))]
public prjBuildAction BuildAction {
get {
return prjBuildAction.prjBuildActionNone;
}
}
}
[ComVisible(true)]
public class IncludedFileNodeProperties : FileNodeProperties {
internal IncludedFileNodeProperties(HierarchyNode node)
: base(node) {
}
/// <summary>
/// Specifies the build action as a string so the user can configure it to any value.
/// </summary>
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
[AlwaysSerialized]
[TypeConverter(typeof(BuildActionStringConverter))]
public string ItemType {
get {
return HierarchyNode.ItemNode.ItemTypeName;
}
set {
HierarchyNode.ItemNode.ItemTypeName = value;
}
}
/// <summary>
/// Specifies the build action as a projBuildAction so that automation can get the
/// expected enum value.
/// </summary>
[Browsable(false)]
public prjBuildAction BuildAction {
get {
var res = BuildActionTypeConverter.Instance.ConvertFromString(HierarchyNode.ItemNode.ItemTypeName);
if (res is prjBuildAction) {
return (prjBuildAction)res;
}
return prjBuildAction.prjBuildActionContent;
}
set {
this.HierarchyNode.ItemNode.ItemTypeName = BuildActionTypeConverter.Instance.ConvertToString(value);
}
}
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.Publish)]
[SRDescriptionAttribute(SR.PublishDescription)]
public bool Publish {
get {
var publish = this.HierarchyNode.ItemNode.GetMetadata("Publish");
if (String.IsNullOrEmpty(publish)) {
if (this.HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) {
return true;
}
return false;
}
return Convert.ToBoolean(publish);
}
set {
this.HierarchyNode.ItemNode.SetMetadata("Publish", value.ToString());
}
}
[Browsable(false)]
public bool ShouldSerializePublish() {
// If compile, default should be true, else the default is false.
if (HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) {
return !Publish;
}
return Publish;
}
[Browsable(false)]
public void ResetPublish() {
// If compile, default should be true, else the default is false.
if (HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) {
Publish = true;
}
Publish = false;
}
[Browsable(false)]
public string SourceControlStatus {
get {
// remove STATEICON_ and return rest of enum
return HierarchyNode.StateIconIndex.ToString().Substring(10);
}
}
[Browsable(false)]
public string SubType {
get {
return this.HierarchyNode.ItemNode.GetMetadata("SubType");
}
set {
this.HierarchyNode.ItemNode.SetMetadata("SubType", value.ToString());
}
}
}
[ComVisible(true)]
public class LinkFileNodeProperties : FileNodeProperties {
internal LinkFileNodeProperties(HierarchyNode node)
: base(node) {
}
/// <summary>
/// Specifies the build action as a string so the user can configure it to any value.
/// </summary>
[SRCategoryAttribute(SR.Advanced)]
[SRDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
[AlwaysSerialized]
[TypeConverter(typeof(BuildActionStringConverter))]
public string ItemType {
get {
return HierarchyNode.ItemNode.ItemTypeName;
}
set {
HierarchyNode.ItemNode.ItemTypeName = value;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
[ReadOnly(true)]
public override string FileName {
get {
return this.HierarchyNode.Caption;
}
set {
throw new InvalidOperationException();
}
}
}
[ComVisible(true)]
public class DependentFileNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
public virtual string FileName {
get {
return this.HierarchyNode.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath {
get {
return this.HierarchyNode.Url;
}
}
#endregion
#region ctors
internal DependentFileNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
public override string GetClassName() {
return SR.GetString(SR.FileProperties);
}
}
class BuildActionTypeConverter : StringConverter {
internal static readonly BuildActionTypeConverter Instance = new BuildActionTypeConverter();
public BuildActionTypeConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == typeof(string)) {
switch ((prjBuildAction)value) {
case prjBuildAction.prjBuildActionCompile:
return ProjectFileConstants.Compile;
case prjBuildAction.prjBuildActionContent:
return ProjectFileConstants.Content;
case prjBuildAction.prjBuildActionNone:
return ProjectFileConstants.None;
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
if (value is string) {
string strVal = (string)value;
if (strVal.Equals(ProjectFileConstants.Compile, StringComparison.OrdinalIgnoreCase)) {
return prjBuildAction.prjBuildActionCompile;
} else if (strVal.Equals(ProjectFileConstants.Content, StringComparison.OrdinalIgnoreCase)) {
return prjBuildAction.prjBuildActionContent;
} else if (strVal.Equals(ProjectFileConstants.None, StringComparison.OrdinalIgnoreCase)) {
return prjBuildAction.prjBuildActionNone;
}
}
return base.ConvertFrom(context, culture, value);
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
return new StandardValuesCollection(new[] { prjBuildAction.prjBuildActionNone, prjBuildAction.prjBuildActionCompile, prjBuildAction.prjBuildActionContent });
}
}
/// <summary>
/// This type converter doesn't really do any conversions, but allows us to provide
/// a list of standard values for the build action.
/// </summary>
class BuildActionStringConverter : StringConverter {
internal static readonly BuildActionStringConverter Instance = new BuildActionStringConverter();
public BuildActionStringConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
return value;
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
return value;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
FileNodeProperties nodeProps = context.Instance as FileNodeProperties;
IEnumerable<string> itemNames;
if (nodeProps != null) {
itemNames = nodeProps.HierarchyNode.ProjectMgr.GetAvailableItemNames();
} else {
itemNames = new[] { ProjectFileConstants.None, ProjectFileConstants.Compile, ProjectFileConstants.Content };
}
return new StandardValuesCollection(itemNames.ToArray());
}
}
[ComVisible(true)]
public class ProjectNodeProperties : NodeProperties, EnvDTE80.IInternalExtenderProvider {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.ProjectFolder)]
[SRDescriptionAttribute(SR.ProjectFolderDescription)]
[AutomationBrowsable(false)]
public string ProjectFolder {
get {
return this.Node.ProjectMgr.ProjectFolder;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.ProjectFile)]
[SRDescriptionAttribute(SR.ProjectFileDescription)]
[AutomationBrowsable(false)]
public string ProjectFile {
get {
return this.Node.ProjectMgr.ProjectFile;
}
set {
this.Node.ProjectMgr.ProjectFile = value;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string Guid {
get {
return this.Node.ProjectMgr.ProjectIDGuid.ToString();
}
}
[Browsable(false)]
public string FileName {
get {
return this.Node.ProjectMgr.ProjectFile;
}
set {
this.Node.ProjectMgr.ProjectFile = value;
}
}
[Browsable(false)]
public string FullPath {
get {
return CommonUtils.NormalizeDirectoryPath(this.Node.ProjectMgr.ProjectFolder);
}
}
#endregion
#endregion
#region ctors
internal ProjectNodeProperties(ProjectNode node)
: base(node) {
}
internal new ProjectNode Node {
get {
return (ProjectNode)base.Node;
}
}
#endregion
#region overridden methods
/// <summary>
/// ICustomTypeDescriptor.GetEditor
/// To enable the "Property Pages" button on the properties browser
/// the browse object (project properties) need to be unmanaged
/// or it needs to provide an editor of type ComponentEditor.
/// </summary>
/// <param name="editorBaseType">Type of the editor</param>
/// <returns>Editor</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "The service provider is used by the PropertiesEditorLauncher")]
public override object GetEditor(Type editorBaseType) {
// Override the scenario where we are asked for a ComponentEditor
// as this is how the Properties Browser calls us
if (editorBaseType == typeof(ComponentEditor)) {
IOleServiceProvider sp;
ErrorHandler.ThrowOnFailure(Node.ProjectMgr.GetSite(out sp));
return new PropertiesEditorLauncher(new ServiceProvider(sp));
}
return base.GetEditor(editorBaseType);
}
public override int GetCfgProvider(out IVsCfgProvider p) {
if (this.Node != null && this.Node.ProjectMgr != null) {
return this.Node.ProjectMgr.GetCfgProvider(out p);
}
return base.GetCfgProvider(out p);
}
public override string GetClassName() {
return SR.GetString(SR.ProjectProperties);
}
#endregion
#region IInternalExtenderProvider Members
bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject) {
EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>();
if (outerHierarchy != null) {
return outerHierarchy.CanExtend(extenderCATID, extenderName, extendeeObject);
}
return false;
}
object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie) {
EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>();
if (outerHierarchy != null) {
return outerHierarchy.GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie);
}
return null;
}
object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject) {
return null;
}
#endregion
}
[ComVisible(true)]
public class FolderNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FolderName)]
[SRDescriptionAttribute(SR.FolderNameDescription)]
public string FolderName {
get {
return this.HierarchyNode.Caption;
}
set {
HierarchyNode.ProjectMgr.Site.GetUIThread().Invoke(() => {
this.HierarchyNode.SetEditLabel(value);
this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption);
});
}
}
#region properties - used for automation only
[Browsable(false)]
[AutomationBrowsable(true)]
public string FileName {
get {
return this.HierarchyNode.Caption;
}
set {
HierarchyNode.ProjectMgr.Site.GetUIThread().Invoke(() => {
this.HierarchyNode.SetEditLabel(value);
this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption);
});
}
}
[Browsable(true)]
[AutomationBrowsable(true)]
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath {
get {
return CommonUtils.NormalizeDirectoryPath(this.HierarchyNode.GetMkDocument());
}
}
#endregion
#endregion
#region ctors
internal FolderNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
public override string GetClassName() {
return SR.GetString(SR.FolderProperties);
}
}
[CLSCompliant(false), ComVisible(true)]
public class ReferenceNodeProperties : NodeProperties {
#region properties
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.RefName)]
[SRDescriptionAttribute(SR.RefNameDescription)]
[Browsable(true)]
[AutomationBrowsable(true)]
public override string Name {
get {
return this.HierarchyNode.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.CopyToLocal)]
[SRDescriptionAttribute(SR.CopyToLocalDescription)]
public bool CopyToLocal {
get {
string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False");
if (copyLocal == null || copyLocal.Length == 0)
return true;
return bool.Parse(copyLocal);
}
set {
this.SetProperty(ProjectFileConstants.Private, value.ToString());
}
}
[SRCategoryAttribute(SR.Misc)]
[SRDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public virtual string FullPath {
get {
return this.HierarchyNode.Url;
}
}
#endregion
#region ctors
internal ReferenceNodeProperties(HierarchyNode node)
: base(node) {
}
#endregion
#region overridden methods
public override string GetClassName() {
return SR.GetString(SR.ReferenceProperties);
}
#endregion
}
[ComVisible(true)]
public class ProjectReferencesProperties : ReferenceNodeProperties {
#region ctors
internal ProjectReferencesProperties(ProjectReferenceNode node)
: base(node) {
}
#endregion
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// 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.Text;
using Alachisoft.ContentOptimization.Diagnostics.Logging;
using Alachisoft.NCache.ContentOptimization.Configurations;
using System.IO;
using Alachisoft.NCache.ContentOptimization.Util;
using System.Diagnostics;
namespace Alachisoft.NCache.ContentOptimization.Diagnostics
{
class FileBasedTraceProvider : ITraceProvider,IDisposable
{
private TextWriter writer;
private object _sync_mutex = new object();
static FileBasedTraceProvider s_trace;
static FileBasedTraceProvider()
{
s_trace = new FileBasedTraceProvider();
if (ConfigurationProvider.Settings.EnableTrace)
{
string filename = "contentoptimization." + Process.GetCurrentProcess().Id;
s_trace.Initialize(filename, "ContentOptimizationLogs");
}
}
public static FileBasedTraceProvider Current { get { return s_trace; } }
#region ITraceProvider Members
public void WriteTrace(TraceSeverity level, string categoryName, string message)
{
if (ConfigurationProvider.Settings.EnableTrace)
{
WriteLogEntry(GetServerityCompatibleString(level), message);
}
}
#endregion
public void WriteTrace(TraceSeverity level,string message)
{
if (ConfigurationProvider.Settings.EnableTrace)
{
WriteLogEntry(GetServerityCompatibleString(level), message);
}
}
private string GetServerityCompatibleString(TraceSeverity serverity)
{
string servertiyString = "";
switch (serverity)
{
case TraceSeverity.InformationEvent:
case TraceSeverity.Medium:
case TraceSeverity.Monitorable:
case TraceSeverity.Verbose:
servertiyString = "information";
break;
case TraceSeverity.WarningEvent:
servertiyString = "warning";
break;
case TraceSeverity.CriticalEvent:
servertiyString = "critical";
break;
case TraceSeverity.Exception:
case TraceSeverity.Unexpected:
servertiyString = "error";
break;
default:
servertiyString = "unspecified";
break;
}
return servertiyString;
}
/// <summary>
/// True if writer is not instantiated, false otherwise
/// </summary>
public bool IsWriterNull
{
get
{
if (writer == null) return true;
else return false;
}
}
/// <summary>
/// Creates logs in installation folder
/// </summary>
/// <param name="fileName">name of file</param>
/// <param name="directory">directory in which the logs are to be made</param>
public void Initialize(string fileName, string directory)
{
Initialize(fileName, null, directory);
}
/// <summary>
/// Creates logs in provided folder
/// </summary>
/// <param name="fileName">name of file</param>
/// <param name="filepath">path where logs are to be created</param>
/// <param name="directory">directory in which the logs are to be made</param>
public void Initialize(string fileName, string filepath, string directory)
{
lock (_sync_mutex)
{
string filename = fileName + "." +
Environment.MachineName.ToLower() + "." +
DateTime.Now.ToString("dd-MM-yy HH-mm-ss") + @".logs.txt";
if (filepath == null || filepath == string.Empty)
{
if (!DirectoryUtil.SearchGlobalDirectory("log-files", false, out filepath))
{
try
{
DirectoryUtil.SearchLocalDirectory("log-files", true, out filepath);
}
catch (Exception ex)
{
throw new Exception("Unable to initialize the log file", ex);
}
}
}
try
{
filepath = Path.Combine(filepath, directory);
if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath);
filepath = Path.Combine(filepath, filename);
writer = TextWriter.Synchronized(new StreamWriter(filepath, false));
}
catch (Exception)
{
throw;
}
}
}
/// <summary>
/// Write to log file
/// </summary>
/// <param name="module">module</param>
/// <param name="logText">text</param>
public void WriteLogEntry(string severity, string logText)
{
if (writer != null)
{
int space2 = 40;
string line = null;
severity = "[" + severity + "]";
line = System.DateTime.Now.ToString("dd-MM-yy HH:mm:ss:ffff") + ": " + severity.PadRight(space2, ' ')+ logText;
lock (_sync_mutex)
{
writer.WriteLine(line);
writer.Flush();
}
}
}
/// <summary>
/// Close writer
/// </summary>
public void Close()
{
lock (_sync_mutex)
{
if (writer != null)
{
lock (writer)
{
writer.Close();
writer = null;
}
}
}
}
#region IDisposable Members
public void Dispose()
{
Close();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
public static partial class SkipUrlEncodingOperationsExtensions
{
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetMethodPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetPathPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// An unencoded path parameter with value 'path1/path2/path3'. Possible
/// values for this parameter include: 'path1/path2/path3'
/// </param>
public static void GetSwaggerPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// An unencoded path parameter with value 'path1/path2/path3'. Possible
/// values for this parameter include: 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetMethodQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
public static void GetMethodQueryNull(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryNullAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryNullAsync( this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryNullWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetPathQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// An unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'. Possible values for this parameter
/// include: 'value1&q2=value2&q3=value3'
/// </param>
public static void GetSwaggerQueryValid(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// An unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'. Possible values for this parameter
/// include: 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;
using Moq;
using NUnit.Framework;
namespace Azure.Identity.Tests
{
public class TokenCacheTests : ClientTestBase
{
public TokenCacheTests(bool isAsync) : base(isAsync)
{ }
internal TokenCache cache;
public Mock<ITokenCacheSerializer> mockSerializer;
public Mock<ITokenCacheSerializer> mockSerializer2;
public Mock<ITokenCache> mockMSALCache;
internal Mock<MsalCacheHelperWrapper> mockWrapper;
public static Random random = new Random();
public byte[] bytes = new byte[] { 1, 0 };
public byte[] updatedBytes = new byte[] { 0, 2 };
public byte[] mergedBytes = new byte[] { 1, 2 };
public Func<TokenCacheNotificationArgs, Task> main_OnBeforeCacheAccessAsync = null;
public Func<TokenCacheNotificationArgs, Task> main_OnAfterCacheAccessAsync = null;
public TokenCacheCallback merge_OnBeforeCacheAccessAsync = null;
public TokenCacheCallback merge_OnAfterCacheAccessAsync = null;
private const int TestBufferSize = 512;
private static Random rand = new Random();
[SetUp]
public void Setup()
{
mockSerializer = new Mock<ITokenCacheSerializer>();
mockSerializer2 = new Mock<ITokenCacheSerializer>();
mockMSALCache = new Mock<ITokenCache>();
mockWrapper = new Mock<MsalCacheHelperWrapper>();
mockWrapper.Setup(m => m.InitializeAsync(It.IsAny<StorageCreationProperties>(), null))
.Returns(Task.CompletedTask);
cache = new TokenCache(new TokenCachePersistenceOptions(), mockWrapper.Object);
}
[TearDown]
public void Cleanup()
{
TokenCache.ResetWrapperCache();
}
public static IEnumerable<object[]> PersistentCacheOptions()
{
yield return new object[] { new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = true, Name = "foo" }, true, "foo" };
yield return new object[] { new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = false, Name = "bar" }, false, "bar" };
yield return new object[] { new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = false }, false, Constants.DefaultMsalTokenCacheName };
yield return new object[] { new TokenCachePersistenceOptions { Name = "fizz" }, false, "fizz" };
yield return new object[] { new TokenCachePersistenceOptions(), false, Constants.DefaultMsalTokenCacheName };
}
[Test]
[TestCaseSource(nameof(PersistentCacheOptions))]
public void CtorAllowsAllPermutations(TokenCachePersistenceOptions options, bool expectedAllowUnencryptedStorage, string expectedName)
{
cache = new TokenCache(options);
}
[Test]
public async Task NoPersistance_RegisterCacheInitializesEvents()
{
cache = new TokenCache(new InMemoryTokenCacheOptions(bytes));
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
}
[Test]
public async Task NoPersistance_RegisterCacheInitializesEventsOnlyOnce()
{
cache = new TokenCache(new InMemoryTokenCacheOptions(bytes));
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
}
[Test]
[NonParallelizable]
public async Task RegisterCacheInitializesCacheWithName()
{
string cacheName = Guid.NewGuid().ToString();
cache = new TokenCache(new TokenCachePersistenceOptions() { Name = cacheName }, mockWrapper.Object);
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockWrapper.Verify(m => m.InitializeAsync(
It.Is<StorageCreationProperties>(p =>
p.CacheFileName == cacheName &&
p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService &&
p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection),
null));
mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.AtLeastOnce);
}
[Test]
[NonParallelizable]
public async Task RegisterCacheInitializesCache()
{
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockWrapper.Verify(m => m.InitializeAsync(
It.Is<StorageCreationProperties>(p =>
p.CacheFileName == Constants.DefaultMsalTokenCacheName &&
p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService &&
p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection),
null));
mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.AtLeastOnce);
}
[Test]
[NonParallelizable]
public async Task RegisterCacheInitializesCacheOnlyOnce()
{
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockWrapper.Verify(m => m.InitializeAsync(
It.Is<StorageCreationProperties>(p =>
p.CacheFileName == Constants.DefaultMsalTokenCacheName &&
p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService &&
p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection),
null), Times.Once);
mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.Exactly(2));
}
[Test]
[NonParallelizable]
public void RegisterCacheInitializesCacheAndIsThreadSafe()
{
ManualResetEventSlim resetEvent2 = new ManualResetEventSlim();
ManualResetEventSlim resetEvent1 = new ManualResetEventSlim();
//The fist call to InitializeAsync will block. The second one will complete immediately.
mockWrapper.SetupSequence(m => m.InitializeAsync(It.IsAny<StorageCreationProperties>(), null))
.Returns(() =>
{
resetEvent1.Wait(1);
resetEvent1.Set();
resetEvent2.Wait();
return Task.CompletedTask;
})
.Returns(Task.CompletedTask);
var cache2 = new TokenCache(new TokenCachePersistenceOptions(), mockWrapper.Object);
var task1 = Task.Run(() => cache.RegisterCache(IsAsync, mockMSALCache.Object, default));
var task2 = Task.Run(() => cache2.RegisterCache(IsAsync, mockMSALCache.Object, default));
//Ensure the two tasks are running before we release the first call to InitializeAsync.
resetEvent1.Wait();
resetEvent2.Set();
Task.WaitAll(task1, task2);
mockWrapper.Verify(m => m.InitializeAsync(
It.Is<StorageCreationProperties>(p =>
p.CacheFileName == Constants.DefaultMsalTokenCacheName &&
p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService &&
p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection),
null));
mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.Exactly(2));
}
[Test]
[NonParallelizable]
public void RegisterCacheThrowsIfEncryptionIsUnavailableAndAllowUnencryptedStorageIsFalse()
{
mockWrapper.Setup(m => m.VerifyPersistence()).Throws<MsalCachePersistenceException>();
Assert.ThrowsAsync<MsalCachePersistenceException>(() => cache.RegisterCache(IsAsync, mockMSALCache.Object, default));
}
[Test]
[NonParallelizable]
public async Task RegisterCacheInitializesCacheIfEncryptionIsUnavailableAndAllowUnencryptedStorageIsTrue()
{
mockWrapper.SetupSequence(m => m.VerifyPersistence())
.Throws<MsalCachePersistenceException>()
.Pass();
cache = new TokenCache(new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = true }, mockWrapper.Object);
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockWrapper.Verify(m => m.InitializeAsync(
It.Is<StorageCreationProperties>(p =>
p.CacheFileName == Constants.DefaultMsalTokenCacheName &&
p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService &&
p.UseLinuxUnencryptedFallback),
null));
mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.AtLeastOnce);
}
[Test]
public async Task Persistance_RegisterCacheDoesNotInitializesEvents()
{
var options = System.Environment.OSVersion.Platform switch
{
// Linux tests will fail without UnsafeAllowUnencryptedStorage = true.
PlatformID.Unix => new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = true },
_ => new TokenCachePersistenceOptions()
};
cache = new TokenCache(options);
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Never);
mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Never);
}
[Test]
public async Task InMemory_RegisterCacheInitializesEvents()
{
cache = new TokenCache(new InMemoryTokenCacheOptions(bytes));
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
}
[Test]
public async Task InMemory_RegisterCacheInitializesEventsOnlyOnce()
{
cache = new TokenCache(new InMemoryTokenCacheOptions(bytes));
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once);
}
[Test]
public async Task RegisteredEventsAreCalledOnFirstUpdate()
{
cache = new TokenCache(new InMemoryTokenCacheOptions(bytes));
TokenCacheNotificationArgs mockArgs = GetMockArgs(mockSerializer, true);
bool updatedCalled = false;
mockMSALCache
.Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess);
mockMSALCache
.Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess);
mockSerializer.Setup(m => m.SerializeMsalV3()).Returns(bytes);
cache.TokenCacheUpdatedAsync += (args) =>
{
updatedCalled = true;
return Task.CompletedTask;
};
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
await main_OnBeforeCacheAccessAsync.Invoke(mockArgs);
await main_OnAfterCacheAccessAsync.Invoke(mockArgs);
mockSerializer.Verify(m => m.DeserializeMsalV3(cache.Data, true), Times.Once);
mockSerializer.Verify(m => m.SerializeMsalV3(), Times.Once);
Assert.That(updatedCalled);
Assert.That(cache.Data, Is.EqualTo(bytes));
}
[Test]
public async Task MergeOccursOnSecondUpdate()
{
var mockPublicClient = new Mock<IPublicClientApplication>();
var mergeMSALCache = new Mock<ITokenCache>();
TokenCacheNotificationArgs mockArgs1 = GetMockArgs(mockSerializer, true);
TokenCacheNotificationArgs mockArgs2 = GetMockArgs(mockSerializer2, true);
mockMSALCache
.Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess);
mockMSALCache
.Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess);
mergeMSALCache
.Setup(m => m.SetBeforeAccess(It.IsAny<TokenCacheCallback>()))
.Callback<TokenCacheCallback>(beforeAccess =>
{
merge_OnBeforeCacheAccessAsync = beforeAccess;
});
mergeMSALCache
.Setup(m => m.SetAfterAccess(It.IsAny<TokenCacheCallback>()))
.Callback<TokenCacheCallback>(afterAccess => merge_OnAfterCacheAccessAsync = afterAccess);
mockSerializer
.SetupSequence(m => m.SerializeMsalV3())
.Returns(bytes)
.Returns(mergedBytes);
mockSerializer2
.SetupSequence(m => m.SerializeMsalV3())
.Returns(updatedBytes);
mockPublicClient
.SetupGet(m => m.UserTokenCache).Returns(mergeMSALCache.Object);
mockPublicClient
.Setup(m => m.GetAccountsAsync())
.ReturnsAsync(() => new List<IAccount>())
.Callback(() =>
{
merge_OnBeforeCacheAccessAsync(mockArgs1);
var list = merge_OnBeforeCacheAccessAsync.GetInvocationList();
if (merge_OnAfterCacheAccessAsync != null)
merge_OnAfterCacheAccessAsync(mockArgs1);
});
cache = new TokenCache(new InMemoryTokenCacheOptions(bytes), default, publicApplicationFactory: new Func<IPublicClientApplication>(() => mockPublicClient.Object));
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
await cache.RegisterCache(IsAsync, mergeMSALCache.Object, default);
// Read the cache from consumer 1.
await main_OnBeforeCacheAccessAsync.Invoke(mockArgs1);
// Read and write the cache from consumer 2.
await main_OnBeforeCacheAccessAsync.Invoke(mockArgs2);
// Dealy to ensure that the timestamps are different between last read and last updated.
await Task.Delay(100);
await main_OnAfterCacheAccessAsync.Invoke(mockArgs2);
// Consumer 1 now writes, and must update its cache first.
await main_OnAfterCacheAccessAsync.Invoke(mockArgs1);
mockSerializer.Verify(m => m.DeserializeMsalV3(bytes, true), Times.Exactly(1));
mockSerializer.Verify(m => m.SerializeMsalV3(), Times.Exactly(2));
mockSerializer.Verify(m => m.DeserializeMsalV3(bytes, false), Times.Exactly(1));
mockSerializer.Verify(m => m.DeserializeMsalV3(updatedBytes, false), Times.Exactly(1));
mockSerializer2.Verify(m => m.DeserializeMsalV3(bytes, true), Times.Exactly(1));
mockSerializer2.Verify(m => m.SerializeMsalV3(), Times.Exactly(1));
// validate that we ended up with the merged cache.
Assert.That(cache.Data, Is.EqualTo(mergedBytes));
}
[Test]
public async Task Serialize()
{
var evt = new ManualResetEventSlim();
var mockPublicClient = new Mock<IPublicClientApplication>();
TokenCacheNotificationArgs mockArgs = GetMockArgs(mockSerializer, true);
mockSerializer
.SetupSequence(m => m.SerializeMsalV3())
.Returns(updatedBytes);
mockMSALCache
.Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess);
mockMSALCache
.Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess);
var cache = new TokenCache(new InMemoryTokenCacheOptions(bytes, updateHandler), default, publicApplicationFactory: new Func<IPublicClientApplication>(() => mockPublicClient.Object));
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
await main_OnBeforeCacheAccessAsync.Invoke(mockArgs);
await main_OnAfterCacheAccessAsync.Invoke(mockArgs);
Task updateHandler(TokenCacheUpdatedArgs args)
{
Assert.That(args.UnsafeCacheData.ToArray(), Is.EqualTo(updatedBytes));
evt.Set();
return Task.CompletedTask;
};
evt.Wait();
}
[Test]
public async Task UnsafeOptions()
{
var bytes1 = new ReadOnlyMemory<byte>(new byte[] { 1 });
var bytes2 = new ReadOnlyMemory<byte>(new byte[] { 2 });
var bytes3 = new ReadOnlyMemory<byte>(new byte[] { 3 });
var evt = new ManualResetEventSlim();
var mockPublicClient = new Mock<IPublicClientApplication>();
TokenCacheNotificationArgs mockArgs = GetMockArgs(mockSerializer, true);
mockSerializer
.SetupSequence(m => m.SerializeMsalV3())
.Returns(updatedBytes);
mockMSALCache
.Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess);
mockMSALCache
.Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()))
.Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess);
var mockUnsafeOptions = new Mock<UnsafeTokenCacheOptions>();
mockUnsafeOptions
.SetupSequence(m => m.RefreshCacheAsync())
.ReturnsAsync(bytes1)
.ReturnsAsync(bytes2)
.ReturnsAsync(bytes3);
mockUnsafeOptions
.Setup(m => m.TokenCacheUpdatedAsync(It.IsAny<TokenCacheUpdatedArgs>()));
var cache = new TokenCache(mockUnsafeOptions.Object, default, publicApplicationFactory: new Func<IPublicClientApplication>(() => mockPublicClient.Object));
await cache.RegisterCache(IsAsync, mockMSALCache.Object, default);
await main_OnBeforeCacheAccessAsync.Invoke(mockArgs);
await main_OnBeforeCacheAccessAsync.Invoke(mockArgs);
await main_OnBeforeCacheAccessAsync.Invoke(mockArgs);
mockSerializer.Verify(m => m.DeserializeMsalV3(It.Is<byte[]>(b => b.SequenceEqual(bytes1.ToArray())), true));
mockSerializer.Verify(m => m.DeserializeMsalV3(It.Is<byte[]>(b => b.SequenceEqual(bytes2.ToArray())), true));
mockSerializer.Verify(m => m.DeserializeMsalV3(It.Is<byte[]>(b => b.SequenceEqual(bytes3.ToArray())), true));
}
private static TokenCacheNotificationArgs GetMockArgs(Mock<ITokenCacheSerializer> mockSerializer, bool hasStateChanged)
{
TokenCacheNotificationArgs mockArgs = (TokenCacheNotificationArgs)FormatterServices.GetUninitializedObject(typeof(TokenCacheNotificationArgs));
var ctor = typeof(TokenCacheNotificationArgs).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
mockArgs = (TokenCacheNotificationArgs)ctor[0].Invoke(new object[] { mockSerializer.Object, "foo", null, hasStateChanged, true, true, null });
return mockArgs;
}
public class InMemoryTokenCacheOptions : UnsafeTokenCacheOptions
{
private readonly ReadOnlyMemory<byte> _bytes;
private readonly Func<TokenCacheUpdatedArgs, Task> _updated;
public InMemoryTokenCacheOptions(byte[] bytes, Func<TokenCacheUpdatedArgs, Task> updated = null)
{
_bytes = bytes;
_updated = updated;
}
protected internal override Task<ReadOnlyMemory<byte>> RefreshCacheAsync()
{
return Task.FromResult(_bytes);
}
protected internal override Task TokenCacheUpdatedAsync(TokenCacheUpdatedArgs tokenCacheUpdatedArgs)
{
return _updated == null ? Task.CompletedTask : _updated(tokenCacheUpdatedArgs);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace JetBrains.Annotations
{
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
sealed class LocalizationRequiredAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationRequiredAttribute"/> class.
/// </summary>
/// <param name="required"><c>true</c> if a element should be localized; otherwise, <c>false</c>.</param>
internal LocalizationRequiredAttribute(bool required)
{
Required = required;
}
/// <summary>
/// Gets a value indicating whether a element should be localized.
/// <value><c>true</c> if a element should be localized; otherwise, <c>false</c>.</value>
/// </summary>
internal bool Required { get; set; }
/// <summary>
/// Returns whether the value of the given object is equal to the current <see cref="LocalizationRequiredAttribute"/>.
/// </summary>
/// <param name="obj">The object to test the value equality of. </param>
/// <returns>
/// <c>true</c> if the value of the given object is equal to that of the current; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
var attribute = obj as LocalizationRequiredAttribute;
return attribute != null && attribute.Required == Required;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current <see cref="LocalizationRequiredAttribute"/>.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
}
/// <summary>
/// Indicates that marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor.
/// The format string should be in <see cref="string.Format(IFormatProvider,string,object[])"/> -like form
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
sealed class StringFormatMethodAttribute : Attribute
{
readonly string myFormatParameterName;
/// <summary>
/// Initializes new instance of StringFormatMethodAttribute
/// </summary>
/// <param name="formatParameterName">Specifies which parameter of an annotated method should be treated as format-string</param>
internal StringFormatMethodAttribute(string formatParameterName)
{
myFormatParameterName = formatParameterName;
}
/// <summary>
/// Gets format parameter name
/// </summary>
internal string FormatParameterName
{
get { return myFormatParameterName; }
}
}
/// <summary>
/// Indicates that the function argument should be string literal and match one of the parameters of the caller function.
/// For example, <see cref="ArgumentNullException"/> has such parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
sealed class InvokerParameterNameAttribute : Attribute
{
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if one of the conditions is satisfied.
/// To set the condition, mark one of the parameters with <see cref="AssertionConditionAttribute"/> attribute
/// </summary>
/// <seealso cref="AssertionConditionAttribute"/>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
sealed class AssertionMethodAttribute : Attribute
{
}
/// <summary>
/// Indicates the condition parameter of the assertion method.
/// The method itself should be marked by <see cref="AssertionMethodAttribute"/> attribute.
/// The mandatory argument of the attribute is the assertion type.
/// </summary>
/// <seealso cref="AssertionConditionType"/>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
sealed class AssertionConditionAttribute : Attribute
{
readonly AssertionConditionType myConditionType;
/// <summary>
/// Initializes new instance of AssertionConditionAttribute
/// </summary>
/// <param name="conditionType">Specifies condition type</param>
internal AssertionConditionAttribute(AssertionConditionType conditionType)
{
myConditionType = conditionType;
}
/// <summary>
/// Gets condition type
/// </summary>
internal AssertionConditionType ConditionType
{
get { return myConditionType; }
}
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisifes the condition, then the execution continues.
/// Otherwise, execution is assumed to be halted
/// </summary>
enum AssertionConditionType
{
/// <summary>
/// Indicates that the marked parameter should be evaluated to true
/// </summary>
IS_TRUE = 0,
/// <summary>
/// Indicates that the marked parameter should be evaluated to false
/// </summary>
IS_FALSE = 1,
/// <summary>
/// Indicates that the marked parameter should be evaluated to null value
/// </summary>
IS_NULL = 2,
/// <summary>
/// Indicates that the marked parameter should be evaluated to not null value
/// </summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
sealed class TerminatesProgramAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked element could be <c>null</c> sometimes, so the check for <c>null</c> is necessary before its usage
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
sealed class CanBeNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked element could never be <c>null</c>
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
sealed class NotNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked type (or its derivatives) cannot be compared using '==' or '!=' operators.
/// There is only exception to compare with <c>null</c>, it is permitted
/// </summary>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
sealed class CannotApplyEqualityOperatorAttribute : Attribute
{
}
/// <summary>
/// When applied to target attribute, specifies a requirement for any type which is marked with
/// target attribute to implement or inherit specific type or types
/// </summary>
/// <example>
/// <code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// internal class ComponentAttribute : Attribute
/// {}
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// internal class MyComponent : IComponent
/// {}
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof (Attribute))]
sealed class BaseTypeRequiredAttribute : Attribute
{
readonly Type[] myBaseTypes;
/// <summary>
/// Initializes new instance of BaseTypeRequiredAttribute
/// </summary>
/// <param name="baseTypes">Specifies which types are required</param>
internal BaseTypeRequiredAttribute(params Type[] baseTypes)
{
myBaseTypes = baseTypes;
}
/// <summary>
/// Gets enumerations of specified base types
/// </summary>
internal IEnumerable<Type> BaseTypes
{
get { return myBaseTypes; }
}
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
sealed class UsedImplicitlyAttribute : Attribute
{
[UsedImplicitly]
internal UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
internal UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
internal UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
internal UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
[UsedImplicitly]
internal ImplicitUseKindFlags UseKindFlags { get; private set; }
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
internal ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
sealed class MeansImplicitUseAttribute : Attribute
{
[UsedImplicitly]
internal MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
internal MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
internal MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
internal MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
[UsedImplicitly]
internal ImplicitUseKindFlags UseKindFlags { get; private set; }
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
internal ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
enum ImplicitUseKindFlags
{
Default = Access | Assign | Instantiated,
/// <summary>
/// Only entity marked with attribute considered used
/// </summary>
Access = 1,
/// <summary>
/// Indicates implicit assignment to a member
/// </summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type
/// </summary>
Instantiated = 4,
}
/// <summary>
/// Specify what is considered used implicitly when marked with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>
/// Members of entity marked with attribute are considered used
/// </summary>
Members = 2,
/// <summary>
/// Entity marked with attribute and all its members considered used
/// </summary>
WithMembers = Itself | Members
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using OpenADK.Library.Infra;
namespace OpenADK.Library
{
/// <summary> Encapsulates information about a <c>SIF_Message</c>, including its
/// payload type, header fields, and raw XML message content.
///
/// An instance of this class is passed to the <i>MessageInfo</i> parameter of
/// all Adk message handlers like Subscriber.onEvent, Publisher.onQuery, and
/// QueryResults.onQueryResults so that implementations of those methods can
/// access header fields or XML content associated with an incoming message.
/// Callers should cast the <i>MessageInfo</i> object to a SifMessageInfo type
/// in order to call the methods of this class that are specific to the Schools
/// Interoperability Framework.
///
///
/// Note that raw XML content is only retained if the "<c>adk.messaging.keepMessageContent</c>"
/// agent property is enabled. Otherwise, the <c>getMessage</c> method
/// returns a <c>null</c> value. Refer to the AgentProperties class for a
/// description of all agent and zone properties.
///
///
/// To use SifMessageInfo, cast the <i>MessageInfo</i> parameter as shown below.
///
///
/// <c>
/// public void onEvent( Event event, Zone zone, MessageInfo info )<br/>
/// {<br/>
/// SifMessageInfo inf = (SifMessageInfo)info;<br/>
/// String sourceId = inf.getSourceId();<br/>
/// String msgId = inf.getMsgId();<br/>
/// SifVersion version = inf.getSIFVersion();<br/><br/>
/// // Display some information about this SIF_Event...<br/>
/// System.out.println( "SIF_Event message with ID " + msgId + <br/>
/// " received from agent " + sourceId + <br/>
/// " in zone " + zone.getZoneId() + "."<br/>
/// " This is a SIF " + version.toString() + " message." );<br/>
/// <br/>
/// ...<br/>
/// </c>
/// </p>
///
/// </summary>
/// <author> Eric Petersen
/// </author>
/// <version> Adk 1.0
/// </version>
public sealed class SifMessageInfo : IMessageInfo
{
private IDictionary<string, string> fAttr = new Dictionary<string, string>();
private IDictionary fObjects = new ListDictionary();
private SifContext [] fContexts;
private IZone fZone;
private SifMessageType fPayload;
private string fMessage;
private SIF_Header fHeader;
private SifVersion fPayloadVersion;
/// <summary> Called by the Adk to construct a SifMessageInfo instance</summary>
public SifMessageInfo()
{}
/// <summary> Called by the Adk to construct a SifMessageInfo</summary>
/// <param name="msg">The SIF_Message
/// </param>
/// <param name="zone">The associated zone
/// </param>
public SifMessageInfo( SifMessagePayload msg,
IZone zone )
{
fZone = zone;
fPayload = Adk.Dtd.GetElementType( msg.ElementDef.Name );
if ( zone.Properties.KeepMessageContent ) {
try {
StringWriter sw = new StringWriter();
SifWriter writer = new SifWriter( sw );
writer.Write( msg );
writer.Flush();
writer.Close();
sw.Close();
fMessage = sw.ToString();
}
catch {
// Do nothing
}
}
// Set SIF_Header values
fHeader = msg.Header;
IList<SifContext> contexts = msg.SifContexts;
fContexts = new SifContext[ contexts.Count ];
contexts.CopyTo( fContexts, 0 );
// Set information about the message payload
fPayloadVersion = msg.SifVersion;
switch ( fPayload ) {
case SifMessageType.SIF_Request:
{
SIF_Request req = (SIF_Request) msg;
fObjects["SIF_MaxBufferSize"] = req.SIF_MaxBufferSize;
fObjects["SIF_RequestVersions"] = req.parseRequestVersions( fZone.Log );
}
break;
case SifMessageType.SIF_Response:
{
SIF_Response rsp = (SIF_Response) msg;
this.SIFRequestMsgId = rsp.SIF_RequestMsgId;
fObjects["SIF_PacketNumber"] = rsp.SIF_PacketNumber;
SetAttribute( "SIF_MorePackets", rsp.SIF_MorePackets );
}
break;
}
}
/// <summary>Gets or sets the SIF_Header encapsulated by this object.</summary>
/// <value> The SIF_Header instance extracted from the message passed to
/// the constructor or assigned to the Message.
/// </value>
public SIF_Header SIFHeader
{
get { return fHeader; }
set { fHeader = value; }
}
/// <summary> Gets the zone from which the message originated.</summary>
/// <value> The Zone instance from which the message originated
/// </value>
public IZone Zone
{
get { return fZone; }
}
/// <summary>Gets the SIF payload message type.</summary>
/// <value>Returns the int value of a SifMessageType enum value</value>
/// <remarks>The value returned from <c>PayloadType</c> can be safely cast to
/// a <see cref="SifMessageType"/>
/// </remarks>
public int PayloadType
{
get { return (int) fPayload; }
}
/// <summary> Gets the SIF payload message element tag.</summary>
/// <value> The element tag of the message (e.g. "SIF_Request")
/// </value>
public string PayloadTag
{
get { return Adk.Dtd.GetElementTag( (int) fPayload ); }
}
/// <summary> Gets the SIF_Message header timestamp.</summary>
/// <value> The <c>SIF_Header/SIF_Date</c> and <c>SIF_Header/SIF_Time</c>
/// element values as a Date instance, identifying the time and date the
/// message was sent
/// </value>
/// <seealso cref="TimeZone">
/// </seealso>
public DateTime? Timestamp
{
get { return fHeader.SIF_Timestamp; }
}
/// <summary> Gets the value of the <c>SIF_MsgId</c> header element</summary>
/// <value> The value of the <c>SIF_Header/SIF_MsgId</c> element, the
/// unique GUID assigned to the message by its sender
/// </value>
public string MsgId
{
get { return fHeader.SIF_MsgId; }
}
/// <summary> Gets the value of the <c>SIF_SourceId</c> header element</summary>
/// <returns> The value of the <c>SIF_Header/SIF_SourceId</c> element,
/// which identifies the agent that originated the message
/// </returns>
public string SourceId
{
get { return fHeader.SIF_SourceId; }
}
/// <summary> Gets the value of the <c>SIF_DestinationId</c> header element</summary>
/// <returns> The value of the optional <c>SIF_Header/SIF_SourceId</c> element.
/// When present, it identifies the agent to which the message should be routed
/// by the zone integration server.
/// </returns>
public string DestinationId
{
get { return fHeader.SIF_DestinationId; }
}
/// <summary> Gets the value of the optional <c>SIF_Security/SIF_SecureChannel/SIF_AuthenticationLevel</c> header element</summary>
/// <returns> The authentication level or zero if not specified
/// </returns>
public int AuthenticationLevel
{
get
{
try {
return
Int32.Parse
( fHeader.SIF_Security.SIF_SecureChannel.SIF_AuthenticationLevel );
}
catch {
return 0;
}
}
}
/// <summary> Gets the value of the optional <c>SIF_Security/SIF_SecureChannel/SIF_EncryptionLevel</c> header element</summary>
/// <returns> The encryption level or zero if not specified
/// </returns>
public int EncryptionLevel
{
get
{
try {
return Int32.Parse( fHeader.SIF_Security.SIF_SecureChannel.SIF_EncryptionLevel );
}
catch {
return 0;
}
}
}
/// <summary> Gets the content of the raw XML message</summary>
/// <returns> The raw XML message content as it was received by the Adk. If
/// the <c>adk.keepMessageContent</c> agent or zone property has
/// a value of "false" (the default), null is returned.
/// </returns>
public string Message
{
get { return fMessage; }
}
/// <summary> Gets the version of SIF associated with the message. The version is
/// determined by inspecting the <i>xmlns</i> attribute of the SIF_Message
/// envelope.
/// </summary>
/// <returns> A SifVersion object identifying the version of SIF associated
/// with the message
/// </returns>
/// <seealso cref="SifRequestVersion">
/// </seealso>
public SifVersion SifVersion
{
get { return fPayloadVersion; }
}
/// <summary> For SIF_Response messages, gets or sets the SIF_MsgId of the associated SIF_Request.</summary>
/// <value> The value of the <c>SIF_Header/SIF_RequestMsgId</c> element, or
/// null if the message encapsulated by this SifMessageInfo instance is not a
/// SIF_Response message
/// </value>
public string SIFRequestMsgId
{
get { return GetAttribute( "SIF_RequestMsgId" ); }
set { SetAttribute( "SIF_RequestMsgId", value ); }
}
/// <summary> For SIF_Request messages, gets or sets the SIF version responses should conform to.</summary>
/// <value> The value of the <c>SIF_Request/SIF_Version</c> element or
/// null if the message is not a SIF_Request message
/// </value>
public SifVersion[] SIFRequestVersions
{
get { return (SifVersion []) fObjects["SIF_RequestVersions"]; }
set { fObjects["SIF_RequestVersions"] = value; }
}
/// <summary>
/// For SIF_Request messages, gets the latest SIF version
/// that was requested by the requestor and is supported by the ADK
/// </summary>
/// <value>The value of the <code>SIF_Request/SIF_Version</code> element or
/// null if the message is not a SIF_Request message</value>
public SifVersion LatestSIFRequestVersion
{
get { return Adk.GetLatestSupportedVersion( SIFRequestVersions ); }
}
/// <summary>
/// Returns information about the request, including the original request time and
/// user state information
/// </summary>
public IRequestInfo SIFRequestInfo
{
get { return (IRequestInfo) fObjects["SIFRequestInfo"]; }
set { fObjects["SIFRequestInfo"] = value; }
}
/// <summary> For SIF_Request messages, identifies the type of object requested</summary>
/// <value> An ElementDef constant from the SifDtd class
/// </value>
public IElementDef SIFRequestObjectType
{
get { return (IElementDef) fObjects["SIF_RequestObjectType"]; }
set { fObjects["SIF_RequestObjectType"] = value; }
}
/// <summary> For SIF_Response messages, gets the packet number</summary>
/// <returns> The int value of the <c>SIF_Response/SIF_PacketNumber</c>
/// element or null if the message is not a SIF_Response message
/// </returns>
public int? PacketNumber
{
get { return (int?) fObjects["SIF_PacketNumber"]; }
}
/// <summary> For SIF_Response messages, determines if more packets are to be expected</summary>
/// <returns> The string value of the <c>SIF_Response/SIF_MorePackets</c>
/// element or null if the message is not a SIF_Response message or the
/// element is missing.
/// </returns>
public bool MorePackets
{
get
{
string s = GetAttribute( "SIF_MorePackets" );
return s == null ? false : s.ToUpper().Equals( "yes".ToUpper() );
}
}
/// <summary> For SIF_Request messages, gets the maximum packet size of result packets</summary>
/// <returns> The value of the <c>SIF_Request/SIF_MaxBufferSize</c>
/// element or zero if the message is not a SIF_Request message or the
/// buffer size could not be converted to an integer
/// </returns>
public int? MaxBufferSize
{
get { return (int?) fObjects["SIF_MaxBufferSize"]; }
}
public string [] AttributeNames
{
get { return null; }
}
public string GetAttribute( string attr )
{
string attributeValue = null;
fAttr.TryGetValue( attr, out attributeValue );
return attributeValue;
}
public void SetAttribute( string attr,
string val )
{
fAttr[attr] = val;
}
/// <summary>
/// Gets the SIF Contexts that this message applies to
/// </summary>
public SifContext [] SIFContexts
{
get { return fContexts; }
}
public static SifMessageInfo Parse(TextReader reader, bool keepMessage, IZone zone)
{
StringWriter writer = null;
try
{
if ( keepMessage )
{
writer = new StringWriter();
}
// Header info, payload type, and full message if desired
SifMessageInfo inf = new SifMessageInfo();
inf.fZone = zone;
int ch;
int elements = 0;
int bytes = 0;
bool inTag = false;
bool inHeader = false;
bool storValue = false;
bool ack = false, response = false;
// Buffer for retaining message content
char[] buf = keepMessage ? new char[1024] : null;
// Tag buffer size is 16*2, enough for largest SIF10r1 element name
StringBuilder tag = new StringBuilder( 16*2 );
// Value buffer size is 16*3, enough for GUID
StringBuilder value = new StringBuilder( 16*3 );
// SIF 1.0r1 Optimization: as soon as we parse the SIF_Header and
// optionally the SIF_OriginalMsgId and SIF_OriginalSourceId elements
// of a SIF_Ack we're done. So continue for as long as
// required_elements != 3.
//
int required_elements = 0;
while ( reader.Peek() > -1 && required_elements != 3 )
{
ch = reader.Read();
if ( keepMessage )
{
buf[bytes++] = (char) ch;
if ( bytes == buf.Length - 1 )
{
writer.Write( buf, 0, bytes );
bytes = 0;
}
}
if ( ch == '<' )
{
inTag = true;
storValue = false;
}
else if ( ch == ' ' && inTag )
{
inTag = false;
storValue = true; // attributes follow
}
else if ( ch == '>' )
{
if ( storValue )
{
Console.WriteLine( "Attributes: " + value.ToString() );
}
// We now have text of next element
switch ( elements )
{
case 0:
// Ensure first element is <SIF_Message>
if ( !tag.ToString().Equals( "SIF_Message" ) )
{
throw new AdkMessagingException( "Message does not begin with SIF_Message", zone );
}
break;
case 1:
//
// Payload element (e.g. "SIF_Ack", "SIF_Register", etc.)
// Ask the DTD object for a type code for this message, store
// it as the payload type in SIFMessageInfo. If zero, it means
// the element is not recognized as a valid payload type for
// this version of SIF.
//
inf.fPayload = Adk.Dtd.GetElementType( tag.ToString() );
if ( inf.fPayload == 0 )
{
throw new AdkMessagingException(
"<" + tag.ToString() + "> is not a valid payload message", zone );
}
// Is this a SIF_Ack or SIF_Response?
ack = (inf.fPayload == SifMessageType.SIF_Ack);
response = ack ? false : (inf.fPayload == SifMessageType.SIF_Response);
if ( !ack && !response )
required_elements += 2;
else if ( response )
required_elements += 1;
break;
default:
String s = tag.ToString();
if ( inHeader )
{
// End of a header element, or </SIF_Header>...
if ( s[0] == '/' )
{
if ( s.Equals( "/SIF_Header" ) )
{
inHeader = false;
required_elements++;
}
else if ( !(s.StartsWith( "/SIF_Sec" )) )
{
inf.SetAttribute( s.Substring( 1 ), value.ToString() );
}
}
else
storValue = true;
}
else // if ( !inHeader )
{
if ( s.Equals( "SIF_Header" ) )
{
// Begin <SIF_Header>
// TODO: This class maintains SIF_Header information in the fHeader
// variable. This particular parsing mechanism doesn't re-create a SIF_Header
// element. Therefore if the parse method is used, the only way to get these
// properties back out is to use the getAttribute() call.
inHeader = true;
}
else if ( ack )
{
// SIF_Ack / SIF_OriginalSourceId or SIF_OriginalMsgId
if ( s.StartsWith( "SIF_Orig" ) )
storValue = true;
else if ( s.StartsWith( "/SIF_Orig" ) )
{
required_elements++;
inf.SetAttribute( s.Substring( 1 ), value.ToString() );
}
}
else if ( response )
{
// SIF_Response / SIF_RequestMsgId
if ( s.StartsWith( "SIF_Req" ) )
storValue = true;
else if ( s.StartsWith( "/SIF_Req" ) )
{
required_elements++;
inf.SetAttribute( s.Substring( 1 ), value.ToString() );
}
}
}
value.Length = 0;
break;
}
inTag = false;
tag.Length = 0;
elements++;
}
else
{
if ( inTag )
tag.Append( (char) ch );
else if ( storValue )
value.Append( (char) ch );
}
}
if ( writer != null )
{
// Read the remainder of the input stream and copy it to the
// output buffer
if ( bytes > 0 )
writer.Write( buf, 0, bytes );
while ( reader.Peek() > -1 )
{
bytes = reader.Read( buf, 0, buf.Length - 1 );
writer.Write( buf, 0, bytes );
}
// Store message content
writer.Flush();
inf.fMessage = writer.GetStringBuilder().ToString();
}
return inf;
}
finally
{
if ( writer != null )
{
writer.Flush();
writer.Close();
}
}
}
public override string ToString()
{
StringBuilder str = new StringBuilder();
str.Append( "SIFMessageInfo Contents\r\n{\r\n" );
foreach ( KeyValuePair<String, String> entry in fAttr ) {
str.Append( "\t" );
str.Append( entry.Key );
str.Append( '=' );
str.Append( entry.Value );
str.Append( "\r\n" );
}
foreach ( KeyValuePair<String, Object> entry in fObjects ) {
str.Append( "\t" );
str.Append( entry.Key );
str.Append( '=' );
if ( entry.Value.GetType().IsArray ) {
object [] values = entry.Value as object [];
str.Append( "{ " );
foreach ( object val in values ) {
str.Append( val );
str.Append( ',' );
}
str.Append( " }" );
}
else {
str.Append( entry.Value );
}
str.Append( "\r\n" );
}
str.Append( "}" );
return str.ToString();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="StyleSheetDesigner.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.Design.MobileControls
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing.Design;
using System.Globalization;
using System.Text;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.Design.MobileControls.Adapters;
using System.Web.UI.Design.MobileControls.Converters;
using System.Web.UI.Design.MobileControls.Util;
using System.Web.UI.MobileControls;
using System.Windows.Forms;
using Control = System.Web.UI.Control;
using DataBindingCollectionEditor = System.Web.UI.Design.DataBindingCollectionEditor;
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
internal class StyleSheetDesigner : MobileTemplatedControlDesigner, IDeviceSpecificDesigner
{
internal static BooleanSwitch StyleSheetDesignerSwitch =
new BooleanSwitch("StyleSheetDesigner", "Enable StyleSheet designer general purpose traces.");
private IWebFormsDocumentService _iWebFormsDocumentService;
private IRefreshableDeviceSpecificEditor _deviceSpecificEditor;
private DesignerVerbCollection _designerVerbs;
private System.Web.UI.MobileControls.StyleSheet _styleSheet;
private Style _currentStyle, _tmpCurrentStyle;
private bool _isDuplicate;
private MergedUI _mergedUI = null;
private ArrayList _cycledStyles = null;
private const int _templateWidth = 300;
private static bool _requiresDesignTimeChanges = false;
private bool _shouldRepersistStyles = false;
private EventHandler _loadComplete = null;
private const String _templatesStylePropName = "TemplateStyle";
private const String _persistedStylesPropName = "PersistedStyles";
private const String _designTimeHTML =
@"
<table cellpadding=4 cellspacing=0 width='300px' style='font-family:tahoma;font-size:8pt;color:buttontext;background-color:buttonface;border: solid 1px;border-top-color:buttonhighlight;border-left-color:buttonhighlight;border-bottom-color:buttonshadow;border-right-color:buttonshadow'>
<tr><td colspan=2><span style='font-weight:bold'>StyleSheet</span> - {0}</td></tr>
<tr><td style='padding-top:0;padding-bottom:0;width:55%;padding-left:10px;font-weight:bold'>Template Style:</td><td style='padding-top:0;padding-bottom:0'>{1}</td></tr>
<tr><td style='padding-top:0;padding-bottom:0;width:55%;padding-left:10px;font-weight:bold'>Template Device Filter:</td><td style='padding-top:0;padding-bottom:0'>{2}</td></tr>
<tr><td colspan=2 style='padding-top:4px'>{3}</td></tr>
</table>
";
private const String _specialCaseDesignTimeHTML =
@"
<table cellpadding=4 cellspacing=0 width='300px' style='font-family:tahoma;font-size:8pt;color:buttontext;background-color:buttonface;border: solid 1px;border-top-color:buttonhighlight;border-left-color:buttonhighlight;border-bottom-color:buttonshadow;border-right-color:buttonshadow'>
<tr><td colspan=2><span style='font-weight:bold'>StyleSheet</span> - {0}</td></tr>
<tr><td style='padding-top:0;padding-bottom:0;width:55%;padding-left:10px;font-weight:bold'>Template Style:</td><td style='padding-top:0;padding-bottom:0'>{1}</td></tr>
<tr><td style='padding-top:0;padding-bottom:0;width:55%;padding-left:10px;font-weight:bold'>Template Device Filter:</td><td style='padding-top:0;padding-bottom:0'>{2}</td></tr>
<tr><td colspan=2 style='padding-top:4px'>{3}</td></tr>
<tr><td colspan=2>
<table style='font-size:8pt;color:window;background-color:ButtonShadow'>
<tr><td valign='top'><img src='{4}'/></td><td>{5}</td></tr>
</table>
</td></tr>
</table>
";
private const int _headerFooterTemplates = 0;
private const int _itemTemplates = 1;
private const int _separatorTemplate = 2;
private const int _contentTemplate = 3;
private const int _numberOfTemplateFrames = 4;
private static readonly String[][] _templateFrameNames =
new String[][] {
new String [] { Constants.HeaderTemplateTag, Constants.FooterTemplateTag },
new String [] { Constants.ItemTemplateTag, Constants.AlternatingItemTemplateTag, Constants.ItemDetailsTemplateTag },
new String [] { Constants.SeparatorTemplateTag },
new String [] { Constants.ContentTemplateTag }
};
private const String _templateStyle = "__TemplateStyle__";
// used by DesignerAdapterUtil.GetMaxWidthToFit
// and needs to be exposed in object model because
// custom controls may need to access the value just like
// DesignerAdapterUtil.GetMaxWidthToFit does.
public override int TemplateWidth
{
get
{
return _templateWidth;
}
}
private MobilePage MobilePage
{
get
{
IComponent component = DesignerAdapterUtil.GetRootComponent(Component);
if (component is MobileUserControl)
{
return ((Control)component).Page as MobilePage;
}
return component as MobilePage;
}
}
private Control RootControl
{
get
{
IComponent component = DesignerAdapterUtil.GetRootComponent(Component);
return component as Control;
}
}
/// <summary>
/// <para>
/// Initializes the designer.
/// </para>
/// </summary>
/// <param name='component'>
/// The control element being designed.
/// </param>
/// <remarks>
/// <para>
/// This is called by the designer host to establish the component being
/// designed.
/// </para>
/// </remarks>
/// <seealso cref='System.ComponentModel.Design.IDesigner'/>
public override void Initialize(IComponent component)
{
Debug.Assert(component is System.Web.UI.MobileControls.StyleSheet,
"StyleSheetDesigner.Initialize - Invalid StyleSheet Control");
base.Initialize(component);
_isDuplicate = false;
_styleSheet = (System.Web.UI.MobileControls.StyleSheet) component;
if(_requiresDesignTimeChanges)
{
_shouldRepersistStyles = true;
}
_loadComplete = new EventHandler(this.OnLoadComplete);
IWebFormsDocumentService.LoadComplete += _loadComplete;
if (IMobileWebFormServices != null)
{
TemplateStyle = (String) IMobileWebFormServices.GetCache(_styleSheet.ID, _templateStyle);
TemplateDeviceFilter =
(String) IMobileWebFormServices.GetCache(
_styleSheet.ID,
MobileTemplatedControlDesigner.DefaultTemplateDeviceFilter);
}
}
private void OnLoadComplete(Object source, EventArgs e)
{
if(_shouldRepersistStyles)
{
IsDirty = true;
OnInternalChange();
}
_requiresDesignTimeChanges = false;
_shouldRepersistStyles = false;
UpdateDesignTimeHtml();
}
internal static void SetRequiresDesignTimeChanges()
{
_requiresDesignTimeChanges = true;
}
private IWebFormsDocumentService IWebFormsDocumentService
{
get
{
if (_iWebFormsDocumentService == null)
{
_iWebFormsDocumentService =
(IWebFormsDocumentService)GetService(typeof(IWebFormsDocumentService));
Debug.Assert(_iWebFormsDocumentService != null);
}
return _iWebFormsDocumentService;
}
}
protected override ITemplateEditingFrame CreateTemplateEditingFrame(TemplateEditingVerb verb)
{
ITemplateEditingService teService =
(ITemplateEditingService)GetService(typeof(ITemplateEditingService));
Debug.Assert(teService != null,
"How did we get this far without an ITemplateEditingService");
String[] templateNames = GetTemplateFrameNames(verb.Index);
ITemplateEditingFrame editingFrame = teService.CreateFrame(
this,
TemplateDeviceFilter + " (" + TemplateStyle + ")",
templateNames,
WebCtrlStyle,
null /* we don't have template styles */);
editingFrame.InitialWidth = _templateWidth;
return editingFrame;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
UpdateActiveStyleSheet();
if (_loadComplete != null)
{
IWebFormsDocumentService.LoadComplete -= _loadComplete;
_loadComplete = null;
}
if (IMobileWebFormServices != null)
{
// If the page is in loading mode, it means the remove is trigged by webformdesigner.
if (!LoadComplete)
{
IMobileWebFormServices.SetCache(_styleSheet.ID, (Object) _templateStyle, (Object) this.TemplateStyle);
}
else
{
// setting to null will remove the entry.
IMobileWebFormServices.SetCache(_styleSheet.ID, (Object) _templateStyle, null);
}
}
}
base.Dispose(disposing);
}
private void UpdateActiveStyleSheet()
{
if (MobilePage != null && MobilePage.StyleSheet == _styleSheet)
{
IDesigner designer = null;
// currently active stylesheet is deleted
MobilePage.StyleSheet = StyleSheet.Default;
StyleSheet _newStyleSheet = null;
Debug.Assert(RootControl != null);
foreach (Control control in RootControl.Controls)
{
// Find new stylesheet
if (control is StyleSheet && _newStyleSheet == null && control != _styleSheet)
{
designer = Host.GetDesigner((IComponent) control);
// AUI 7285
if (designer != null)
{
_newStyleSheet = (StyleSheet) control;
}
}
}
MobilePage.StyleSheet = _newStyleSheet;
if (null != _newStyleSheet)
{
Debug.Assert(designer != null);
StyleSheetDesigner ssd = designer as StyleSheetDesigner;
Debug.Assert(ssd != null, "ssd is null in StyleSheetDesigner");
ssd.TreatAsDuplicate(false);
}
RefreshPageView();
}
}
protected override String[] GetTemplateFrameNames(int index)
{
Debug.Assert(index >= 0 & index <= _templateFrameNames.Length);
return _templateFrameNames[index];
}
protected override TemplateEditingVerb[] GetTemplateVerbs()
{
TemplateEditingVerb[] templateVerbs = new TemplateEditingVerb[_numberOfTemplateFrames];
templateVerbs[_headerFooterTemplates] = new TemplateEditingVerb(
SR.GetString(SR.TemplateFrame_HeaderFooterTemplates),
_headerFooterTemplates,
this);
templateVerbs[_itemTemplates] = new TemplateEditingVerb(
SR.GetString(SR.TemplateFrame_ItemTemplates),
_itemTemplates,
this);
templateVerbs[_separatorTemplate] = new TemplateEditingVerb(
SR.GetString(SR.TemplateFrame_SeparatorTemplate),
_separatorTemplate,
this);
templateVerbs[_contentTemplate] = new TemplateEditingVerb(
SR.GetString(SR.TemplateFrame_ContentTemplate),
_contentTemplate,
this);
return templateVerbs;
}
/// <summary>
/// <para>
/// Delegate to handle component changed event.
/// </para>
/// </summary>
/// <param name='sender'>
/// The object sending the event.
/// </param>
/// <param name='ce'>
/// The event object used when firing a component changed notification.
/// </param>
/// <remarks>
/// <para>
/// This is called after a property has been changed. It allows the implementor
/// to do any post-processing that may be needed after a property change.
/// </para>
/// </remarks>
public override void OnComponentChanged(Object sender, ComponentChangedEventArgs ce)
{
// Delegate to the base class implementation first!
base.OnComponentChanged(sender, ce);
MemberDescriptor member = ce.Member;
if (member != null &&
member.GetType().FullName.Equals(Constants.ReflectPropertyDescriptorTypeFullName))
{
PropertyDescriptor propDesc = (PropertyDescriptor)member;
if (propDesc.Name.Equals("ID"))
{
// Update the dictionary of device filters stored in the page designer
// setting to null will remove the entry.
IMobileWebFormServices.SetCache(ce.OldValue.ToString(), (Object) _templateStyle, null);
}
}
}
internal void OnStylesChanged()
{
// If this is not a new stylesheet and it is the current stylesheet
if (MobilePage != null && MobilePage.StyleSheet == _styleSheet)
{
// Refresh the whole page assuming styles have been changed.
RefreshPageView();
ClearCycledStyles();
}
}
private void RefreshPageView()
{
if (IMobileWebFormServices != null)
{
IMobileWebFormServices.RefreshPageView();
}
}
public override void OnSetParent()
{
base.OnSetParent();
// This is not a MobilePage or the styleSheet is already the active styleSheet.
// The latter happens when the active StyleSheet is drag/drop to another location
// which forces its parent to be changed.
if (MobilePage == null)
{
return;
}
if (MobilePage.StyleSheet == _styleSheet)
{
if (!(_styleSheet.Parent is MobilePage
|| _styleSheet.Parent is MobileUserControl))
{
UpdateActiveStyleSheet();
}
return;
}
if (MobilePage.StyleSheet != StyleSheet.Default)
{
// can't accept more than 1 stylesheet
TreatAsDuplicate(true);
// the current valid StyleSheet is intentionaly refreshed because
// if this stylesheet instance is recreated via a Undo operation
// the current valid StyleSheet appears as a duplicate if not refreshed.
IDesigner designer = Host.GetDesigner((IComponent) MobilePage.StyleSheet);
Debug.Assert(designer != null, "designer is null in StyleSheetDesigner");
StyleSheetDesigner ssd = (StyleSheetDesigner) designer;
ssd.UpdateRendering();
}
else if (_styleSheet.Parent is MobilePage ||
_styleSheet.Parent is MobileUserControl)
{
// the active stylesheet is changed
MobilePage.StyleSheet = _styleSheet;
_isDuplicate = false;
}
RefreshPageView();
}
protected override void OnTemplateModeChanged()
{
base.OnTemplateModeChanged();
// Refresh all mobilecontrols after exit template editing mode.
if (!InTemplateMode)
{
RefreshPageView();
}
}
public void TreatAsDuplicate(bool isDuplicate)
{
if (isDuplicate != _isDuplicate)
{
_isDuplicate = isDuplicate;
SetTemplateVerbsDirty();
UpdateDesignTimeHtml();
}
}
protected override bool ErrorMode
{
get
{
return base.ErrorMode
|| _isDuplicate
|| _styleSheet.DuplicateStyles.Count > 0;
}
}
private StringCollection GetDuplicateStyleNames()
{
StringCollection duplicateNamesList = new StringCollection();
// Filter out repeated duplicate names using case insensitive
// hash table
HybridDictionary duplicateNamesHash = new HybridDictionary(
true /* Names not case sensitive */ );
foreach(Style style in _styleSheet.DuplicateStyles)
{
duplicateNamesHash[style.Name] = true;
}
// Copy remaining names into a string list
foreach(DictionaryEntry entry in duplicateNamesHash)
{
duplicateNamesList.Add((String)entry.Key);
}
return duplicateNamesList;
}
protected override String GetDesignTimeNormalHtml()
{
String curStyle, message;
ArrayList lstStylesInCycle = null;
if (null == CurrentStyle)
{
curStyle = SR.GetString(SR.StyleSheet_PropNotSet);
}
else
{
curStyle = HttpUtility.HtmlEncode(CurrentStyle.Name);
}
String curChoice;
if (null == CurrentChoice)
{
curChoice = SR.GetString(SR.StyleSheet_PropNotSet);
}
else
{
if (CurrentChoice.Filter.Length == 0)
{
curChoice = SR.GetString(SR.DeviceFilter_DefaultChoice);
}
else
{
curChoice = HttpUtility.HtmlEncode(DesignerUtility.ChoiceToUniqueIdentifier(CurrentChoice));
}
}
message = SR.GetString(SR.StyleSheet_DefaultMessage);
bool renderErrorMsg = false;
String errorMsg = null;
String errorIconUrl = null;
if(_isDuplicate)
{
renderErrorMsg = true;
errorMsg = SR.GetString(SR.StyleSheet_DuplicateWarningMessage);
errorIconUrl = MobileControlDesigner.errorIcon;
}
else if(_styleSheet.DuplicateStyles.Count > 0)
{
renderErrorMsg = true;
errorMsg = SR.GetString(
SR.StyleSheet_DuplicateStyleNamesMessage,
GenericUI.BuildCommaDelimitedList(
GetDuplicateStyleNames()
)
);
errorIconUrl = MobileControlDesigner.errorIcon;
}
else if (null != CurrentStyle && null != CurrentChoice)
{
if (IsHTMLSchema(CurrentChoice))
{
message = SR.GetString(SR.StyleSheet_TemplateEditingMessage);
}
else
{
// User has selected non-html schema
renderErrorMsg = true;
errorMsg = SR.GetString(SR.MobileControl_NonHtmlSchemaErrorMessage);
errorIconUrl = MobileControlDesigner.infoIcon;
}
}
if (renderErrorMsg)
{
Debug.Assert(errorMsg != null && errorIconUrl != null);
return String.Format(CultureInfo.CurrentCulture, _specialCaseDesignTimeHTML,
new Object[]
{
_styleSheet.Site.Name,
curStyle,
curChoice,
message,
errorIconUrl,
errorMsg
});
}
else
{
lstStylesInCycle = DetectCycles();
//
if (lstStylesInCycle != null && lstStylesInCycle.Count > 0)
{
String cycledStyles = String.Empty;
//
foreach (Object obj in lstStylesInCycle)
{
Style cycledStyle = (Style) obj;
if (cycledStyles.Length > 0)
{
cycledStyles += ", ";
}
cycledStyles += cycledStyle.Name;
}
return String.Format(CultureInfo.CurrentCulture, _specialCaseDesignTimeHTML,
new Object[]
{
_styleSheet.Site.Name,
curStyle,
curChoice,
message,
MobileControlDesigner.errorIcon,
SR.GetString(SR.StyleSheet_RefCycleErrorMessage, cycledStyles)
});
}
else
{
return String.Format(CultureInfo.CurrentCulture, _designTimeHTML,
new Object[]
{
_styleSheet.Site.Name,
curStyle,
curChoice,
message
});
}
}
}
private void ClearCycledStyles()
{
_cycledStyles = null;
}
/* O(n) algorithm for loop detection
private HybridDictionary DetectCycles()
{
if (_cycledStyles == null)
{
_cycledStyles = new HybridDictionary();
ICollection styles = _styleSheet.Styles;
// Initialize the set
Hashtable styleSet = new Hashtable(styles.Count);
foreach (String key in styles)
{
styleSet.Add(key, true);
}
while (styleSet.Count > 0)
{
Style style = null;
foreach (String key in styleSet.Keys)
{
style = (Style)_styleSheet[key];
Debug.Assert(style != null);
break;
}
int count = 0;
Traverse(styleSet, style, count);
}
}
return _cycledStyles;
}
private bool Traverse(Hashtable styleSet, Style style)
{
String reference = style.StyleReference;
Style nextStyle = null;
bool result = false;
styleSet.Remove(style.Name.ToLower(CultureInfo.InvariantCulture));
if (reference == null || reference.Length == 0 ||
((nextStyle = (Style)_styleSheet[reference]) == null) ||
(!styleSet.Contains(nextStyle)))
{
result = false;
}
else if (_cycledStyles.Contains(nextStyle) ||
Traverse(styleSet, nextStyle, ++count))
{
Debug.Assert(_cycledStyles != null);
if (!_cycledStyles.Contains(style))
{
_cycledStyles.Add(style, "");
}
result = true;
}
return result;
}
*/
private ArrayList DetectCycles()
{
if (_cycledStyles == null)
{
_cycledStyles = new ArrayList();
ICollection styles = _styleSheet.Styles;
foreach (String key in styles)
{
Style style = (Style) _styleSheet[key];
Style styleTmp;
Debug.Assert(style != null);
bool cycle = false;
String reference = style.StyleReference;
String name = style.Name;
int count = styles.Count + 1;
while ((reference != null && reference.Length > 0) && count > 0)
{
if (0 == String.Compare(name, reference, StringComparison.OrdinalIgnoreCase))
{
cycle = true;
break;
}
else
{
styleTmp = _styleSheet[reference];
if (null != styleTmp)
{
reference = styleTmp.StyleReference;
count --;
}
else
{
reference = null;
}
}
}
if (cycle)
{
_cycledStyles.Add(style);
}
}
}
return _cycledStyles;
}
////////////////////////////////////////////////////////////////////////
// Begin IDeviceSpecificDesigner Implementation
////////////////////////////////////////////////////////////////////////
void IDeviceSpecificDesigner.SetDeviceSpecificEditor
(IRefreshableDeviceSpecificEditor editor)
{
_deviceSpecificEditor = editor;
}
String IDeviceSpecificDesigner.CurrentDeviceSpecificID
{
get
{
if (_tmpCurrentStyle == null)
{
return null;
}
if (_styleSheet[_tmpCurrentStyle.Name] == null)
{
_tmpCurrentStyle = null;
}
return (_tmpCurrentStyle != null) ? _tmpCurrentStyle.Name.ToLower(CultureInfo.InvariantCulture) : null;
}
}
System.Windows.Forms.Control IDeviceSpecificDesigner.Header
{
get
{
return _mergedUI;
}
}
System.Web.UI.Control IDeviceSpecificDesigner.UnderlyingControl
{
get
{
return _styleSheet;
}
}
Object IDeviceSpecificDesigner.UnderlyingObject
{
get
{
if (null != _mergedUI.CbStyles.SelectedItem)
{
String styleName = (String) _mergedUI.CbStyles.SelectedItem;
return _styleSheet[styleName];
}
else
{
return null;
}
}
}
bool IDeviceSpecificDesigner.GetDeviceSpecific(String deviceSpecificParentID, out DeviceSpecific ds)
{
Style style = (Style) _styleSheet[deviceSpecificParentID];
if (null == style)
{
ds = null;
return false;
}
else
{
ds = style.DeviceSpecific;
return true;
}
}
void IDeviceSpecificDesigner.SetDeviceSpecific(String deviceSpecificParentID, DeviceSpecific ds)
{
Style style = (Style) _styleSheet[deviceSpecificParentID];
Debug.Assert(null != style, "style is null in IDeviceSpecificDesigner.SetDeviceSpecific");
if (null != ds)
{
ds.SetOwner((MobileControl) _styleSheet);
}
style.DeviceSpecific = ds;
if (CurrentChoice != null && 0 == String.Compare(CurrentStyle.Name, deviceSpecificParentID, StringComparison.OrdinalIgnoreCase))
{
if (ds == null)
{
CurrentChoice = null;
}
else
{
// This makes sure that the CurrentChoice value is set to null is
// it was deleted during the deviceSpecific object editing
if (CurrentChoice.Filter.Length == 0)
{
TemplateDeviceFilter = SR.GetString(SR.DeviceFilter_DefaultChoice);
}
else
{
TemplateDeviceFilter = DesignerUtility.ChoiceToUniqueIdentifier(CurrentChoice);
}
}
}
}
void IDeviceSpecificDesigner.InitHeader(int mergingContext)
{
_mergedUI = new MergedUI();
_mergedUI.LblStyles.Text = SR.GetString(SR.StyleSheet_StylesCaption);
_mergedUI.LblStyles.TabIndex = 1;
_mergedUI.CbStyles.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
_mergedUI.CbStyles.SelectedIndexChanged += new EventHandler(this.OnSelectedIndexChangedStylesComboBox);
_mergedUI.CbStyles.TabIndex = 2;
_mergedUI.CbStyles.Sorted = true;
_mergedUI.BtnEdit.Text = SR.GetString(SR.Stylesheet_EditBtnCaption);
_mergedUI.BtnEdit.Click += new EventHandler(this.OnClickEditStylesButton);
_mergedUI.BtnEdit.TabIndex = 3;
switch (mergingContext)
{
case MobileControlDesigner.MergingContextTemplates:
{
_mergedUI.LblHeader.Text = SR.GetString(SR.StyleSheet_SettingTemplatingStyleChoiceDescription);
// AUI 2730
_mergedUI.CbStyles.Width = 195;
_mergedUI.BtnEdit.Location = new System.Drawing.Point(201, 39);
break;
}
default:
{
_mergedUI.LblHeader.Text = SR.GetString(SR.StyleSheet_SettingGenericStyleChoiceDescription);
// AUI 2730
_mergedUI.CbStyles.Width = 195;
_mergedUI.BtnEdit.Location = new System.Drawing.Point(201, 39);
break;
}
}
}
void IDeviceSpecificDesigner.RefreshHeader(int mergingContext)
{
_mergedUI.CbStyles.Items.Clear();
ICollection styles = _styleSheet.Styles;
foreach (String key in styles)
{
Style style = (Style) _styleSheet[key];
Debug.Assert(style != null);
_mergedUI.CbStyles.Items.Add(style.Name);
}
if (_mergedUI.CbStyles.Items.Count > 0)
{
Debug.Assert(null != CurrentStyle);
_mergedUI.CbStyles.SelectedItem = CurrentStyle.Name;
_oldSelectedIndex = _mergedUI.CbStyles.SelectedIndex;
}
_mergedUI.CbStyles.Enabled = (_mergedUI.CbStyles.Items.Count > 0);
}
void IDeviceSpecificDesigner.UseCurrentDeviceSpecificID()
{
if (CurrentStyle != _tmpCurrentStyle)
{
CurrentChoice = null;
CurrentStyle = _tmpCurrentStyle;
}
}
/////////////////////////////////////////////////////////////////////////
// End IDeviceSpecificDesigner Implementation
/////////////////////////////////////////////////////////////////////////
private int _oldSelectedIndex;
private void OnSelectedIndexChangedStylesComboBox(Object source, EventArgs e)
{
if (_mergedUI.CbStyles.SelectedIndex != _oldSelectedIndex
&& !_deviceSpecificEditor.RequestRefresh())
{
// User needs to correct error before editing a new style.
_mergedUI.CbStyles.SelectedIndex = _oldSelectedIndex;
return;
}
if (_mergedUI.CbStyles.SelectedIndex >= 0)
{
_tmpCurrentStyle = (Style) _styleSheet[((String) _mergedUI.CbStyles.SelectedItem).ToLower(CultureInfo.InvariantCulture)];
_deviceSpecificEditor.Refresh((String) _mergedUI.CbStyles.SelectedItem, _tmpCurrentStyle.DeviceSpecific);
}
_oldSelectedIndex = _mergedUI.CbStyles.SelectedIndex;
}
private void OnStyleRenamedInEditor(Object source, StyleRenamedEventArgs e)
{
_deviceSpecificEditor.DeviceSpecificRenamed(e.OldName, e.NewName);
}
private void OnStyleDeletedInEditor(Object source, StyleDeletedEventArgs e)
{
_deviceSpecificEditor.DeviceSpecificDeleted(e.Name);
}
private void OnClickEditStylesButton(Object source, EventArgs e)
{
StylesEditorDialog dialog;
try
{
dialog = new StylesEditorDialog(
_styleSheet,
this,
(null != _tmpCurrentStyle) ? _tmpCurrentStyle.Name : null
);
}
catch(ArgumentException ex)
{
Debug.Fail(ex.ToString());
// Block user from entering StylesEditorDialog until they fix
// duplicate style declarations.
return;
}
StylesEditorDialog.StyleRenamedEventHandler renameHandler =
new StylesEditorDialog.StyleRenamedEventHandler(OnStyleRenamedInEditor);
StylesEditorDialog.StyleDeletedEventHandler deleteHandler =
new StylesEditorDialog.StyleDeletedEventHandler(OnStyleDeletedInEditor);
dialog.StyleRenamed += renameHandler;
dialog.StyleDeleted += deleteHandler;
try
{
_deviceSpecificEditor.BeginExternalDeviceSpecificEdit();
if (dialog.ShowDialog() == DialogResult.OK)
{
_deviceSpecificEditor.EndExternalDeviceSpecificEdit(
true /* commit changes */ );
OnInternalChange();
((IDeviceSpecificDesigner) this).RefreshHeader(0);
// using mergingContext 0 because this implementation does not use the param.
if (_mergedUI.CbStyles.Items.Count == 0)
{
_deviceSpecificEditor.Refresh(null, null); // force the clean up and
// disabling of the filter controls.
_tmpCurrentStyle = null;
}
_deviceSpecificEditor.UnderlyingObjectsChanged();
}
else
{
_deviceSpecificEditor.EndExternalDeviceSpecificEdit(
false /* do not commit changes */ );
}
}
finally
{
dialog.StyleRenamed -= renameHandler;
dialog.StyleDeleted -= deleteHandler;
}
}
public Style CurrentStyle
{
get
{
if (null == _currentStyle)
{
// Since this property is registered to property window (from TemplateStyle),
// it will be accessed even before Initialize is called. In that case,
// _styleSheet will be null;
if (_styleSheet != null && _styleSheet.Styles.Count > 0)
{
// how else can you get an entry in the Styles hashtable?
// this needs to be fixed once we use an ordered list of styles.
ICollection styles = _styleSheet.Styles;
foreach (String key in styles)
{
_currentStyle = (Style) _styleSheet[key];
Debug.Assert (_currentStyle != null);
break;
}
}
}
return _currentStyle;
}
set
{
_currentStyle = value;
}
}
public override DeviceSpecific CurrentDeviceSpecific
{
get
{
if (null == CurrentStyle)
{
return null;
}
return CurrentStyle.DeviceSpecific;
}
}
public String TemplateStyle
{
get
{
if (null == CurrentStyle)
{
return SR.GetString(SR.StyleSheet_PropNotSet);
}
return CurrentStyle.Name;
}
set
{
// Clear DeviceSpecificChoice of previously selected Style
CurrentChoice = null;
CurrentStyle = null;
if (!String.IsNullOrEmpty(value) &&
!value.Equals(SR.GetString(SR.StyleSheet_PropNotSet)))
{
ICollection styles = _styleSheet.Styles;
foreach (String key in styles)
{
Style style = (Style) _styleSheet[key];
if (style.Name.Equals(value))
{
CurrentStyle = style;
break;
}
}
}
// Clear DeviceSpecificChoice of currently selected Style
CurrentChoice = null;
// Invalidate the type descriptor so that the TemplateDeviceFilter gets updated
TypeDescriptor.Refresh(Component);
}
}
protected override void SetStyleAttributes()
{
Debug.Assert(Behavior != null, "Behavior is null");
String marginTop = null, marginBottom = null, marginRight = null;
if (ContainmentStatus == ContainmentStatus.AtTopLevel)
{
marginTop = "5px";
marginBottom = "5px";
marginRight = "30%";
}
else
{
marginTop = "3px";
marginBottom = "3px";
marginRight = "5px";
}
Behavior.SetStyleAttribute("marginTop", true, marginTop, true);
Behavior.SetStyleAttribute("marginBottom", true, marginBottom, true);
Behavior.SetStyleAttribute("marginRight", true, marginRight, true);
Behavior.SetStyleAttribute("marginLeft", true, "5px", true);
}
protected override void PreFilterProperties(IDictionary properties)
{
base.PreFilterProperties(properties);
// DesignTime Property only, we will use this to select the current style.
PropertyDescriptor designerTemplateStyleProp;
designerTemplateStyleProp =
TypeDescriptor.CreateProperty(this.GetType(), _templatesStylePropName, typeof(String),
DesignerSerializationVisibilityAttribute.Hidden,
MobileCategoryAttribute.Design,
InTemplateMode ? ReadOnlyAttribute.Yes : ReadOnlyAttribute.No,
InTemplateMode ? BrowsableAttribute.No : BrowsableAttribute.Yes,
new DefaultValueAttribute(SR.GetString(SR.StyleSheet_PropNotSet)),
new TypeConverterAttribute(typeof(StyleConverter)),
new DescriptionAttribute(SR.GetString(SR.StyleSheet_TemplateStyleDescription)));
properties[_templatesStylePropName] = designerTemplateStyleProp;
PropertyDescriptor designerPersistedStyles;
designerPersistedStyles =
TypeDescriptor.CreateProperty(this.GetType(), _persistedStylesPropName, typeof(ICollection),
//PersistenceTypeAttribute.InnerChild,
PersistenceModeAttribute.InnerDefaultProperty,
BrowsableAttribute.No);
properties[_persistedStylesPropName] = designerPersistedStyles;
}
public ICollection PersistedStyles
{
get
{
Debug.Assert(null != _styleSheet, "_styleSheet is null");
ICollection styleKeys = _styleSheet.Styles;
ArrayList persistedStyles = new ArrayList();
foreach (String key in styleKeys)
{
Style style = _styleSheet[key];
persistedStyles.Add(style);
}
foreach (Style style in _styleSheet.DuplicateStyles)
{
persistedStyles.Add(style);
}
return persistedStyles;
}
}
/// <summary>
/// <para>
/// The designer's collection of verbs.
/// </para>
/// </summary>
/// <value>
/// <para>
/// An array of type <see cref='DesignerVerb'/> containing the verbs available to the
/// designer.
/// </para>
/// </value>
public override DesignerVerbCollection Verbs
{
get
{
if (_designerVerbs == null)
{
_designerVerbs = base.Verbs;
_designerVerbs.Add(new DesignerVerb(SR.GetString(SR.StyleSheet_StylesEditorVerb),
new EventHandler(this.OnShowStylesEditor)));
}
Debug.Assert(_designerVerbs.Count == 2);
_designerVerbs[0].Enabled = !this.InTemplateMode;
_designerVerbs[1].Enabled = !this.InTemplateMode;
return _designerVerbs;
}
}
/////////////////////////////////////////////////////////////////////////
// BEGIN STYLE DESIGNER EVENTHANDLERS
/////////////////////////////////////////////////////////////////////////
protected void OnShowStylesEditor(Object sender, EventArgs e)
{
IComponentChangeService changeService = null;
changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
if (changeService != null)
{
try
{
changeService.OnComponentChanging(_styleSheet, null);
}
catch (CheckoutException ex)
{
if (ex == CheckoutException.Canceled)
{
return;
}
throw;
}
}
DialogResult result = DialogResult.Cancel;
try
{
StylesEditorDialog dialog = new StylesEditorDialog(_styleSheet, this, null);
result = dialog.ShowDialog();
}
catch(ArgumentException ex)
{
Debug.Fail(ex.ToString());
// Block user from entering StylesEditorDialog until they fix
// duplicate style declarations.
}
finally
{
if (changeService != null)
{
changeService.OnComponentChanged(_styleSheet, null, null, null);
if (IMobileWebFormServices != null)
{
IMobileWebFormServices.ClearUndoStack();
}
}
}
}
protected override void OnCurrentChoiceChange()
{
SetCurrentChoice();
RefreshPageView();
}
private void SetCurrentChoice()
{
if (CurrentStyle != null && CurrentStyle.DeviceSpecific != null)
{
this.CurrentStyle.DeviceSpecific.SetDesignerChoice(CurrentChoice);
}
}
private bool ValidContainment
{
get
{
return (ContainmentStatus == ContainmentStatus.AtTopLevel);
}
}
protected override String GetErrorMessage(out bool infoMode)
{
infoMode = false;
if (!DesignerAdapterUtil.InMobileUserControl(_styleSheet))
{
if (DesignerAdapterUtil.InUserControl(_styleSheet))
{
infoMode = true;
return MobileControlDesigner._userControlWarningMessage;
}
if (!DesignerAdapterUtil.InMobilePage(_styleSheet))
{
return MobileControlDesigner._mobilePageErrorMessage;
}
}
if (!ValidContainment)
{
return MobileControlDesigner._topPageContainmentErrorMessage;
}
// No error condition, return null;
return null;
}
/////////////////////////////////////////////////////////////////////////
// END STYLE DESIGNER EVENTHANDLERS
/////////////////////////////////////////////////////////////////////////
[
System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand,
Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)
]
private class MergedUI : HeaderPanel
{
internal System.Windows.Forms.Label LblStyles;
internal System.Windows.Forms.ComboBox CbStyles;
internal System.Windows.Forms.Button BtnEdit;
internal HeaderLabel LblHeader;
internal MergedUI()
{
this.LblStyles = new System.Windows.Forms.Label();
this.CbStyles = new System.Windows.Forms.ComboBox();
this.BtnEdit = new System.Windows.Forms.Button();
this.LblHeader = new HeaderLabel();
// this.LblStyles.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
// | System.Windows.Forms.AnchorStyles.Right);
this.LblStyles.Location = new System.Drawing.Point(0, 24);
this.LblStyles.Size = new System.Drawing.Size(160, 16);
// this.CbStyles.Anchor = ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
// | System.Windows.Forms.AnchorStyles.Right);
this.CbStyles.DropDownWidth = 124;
this.CbStyles.Location = new System.Drawing.Point(0, 40);
this.CbStyles.Size = new System.Drawing.Size(160, 21);
// this.BtnEdit.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.BtnEdit.Location = new System.Drawing.Point(164, 39);
this.BtnEdit.Size = new System.Drawing.Size(75, 23);
this.LblHeader.Location = new System.Drawing.Point(0, 0);
this.LblHeader.Size = new System.Drawing.Size(240, 16);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.CbStyles,
this.LblStyles,
this.BtnEdit,
this.LblHeader});
this.Size = new System.Drawing.Size(240, 70);
this.Location = new System.Drawing.Point(5,6);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// CustomDomainsOperations operations.
/// </summary>
public partial interface ICustomDomainsOperations
{
/// <summary>
/// Lists all of the existing custom domains within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CustomDomain>>> ListByEndpointWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets an exisitng custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> GetWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> CreateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an existing custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> DeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disable https delivery of the custom domain.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> DisableCustomHttpsWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enable https delivery of the custom domain.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> EnableCustomHttpsWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an existing custom domain within an endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CustomDomain>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointName, string customDomainName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all of the existing custom domains within an endpoint.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<CustomDomain>>> ListByEndpointNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class StopRecordingRequestDecoder
{
public const ushort BLOCK_LENGTH = 20;
public const ushort TEMPLATE_ID = 5;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private StopRecordingRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public StopRecordingRequestDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public StopRecordingRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int StreamIdId()
{
return 3;
}
public static int StreamIdSinceVersion()
{
return 0;
}
public static int StreamIdEncodingOffset()
{
return 16;
}
public static int StreamIdEncodingLength()
{
return 4;
}
public static string StreamIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int StreamIdNullValue()
{
return -2147483648;
}
public static int StreamIdMinValue()
{
return -2147483647;
}
public static int StreamIdMaxValue()
{
return 2147483647;
}
public int StreamId()
{
return _buffer.GetInt(_offset + 16, ByteOrder.LittleEndian);
}
public static int ChannelId()
{
return 4;
}
public static int ChannelSinceVersion()
{
return 0;
}
public static string ChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ChannelHeaderLength()
{
return 4;
}
public int ChannelLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetChannel(IMutableDirectBuffer dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public int GetChannel(byte[] dst, int dstOffset, int length)
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
int bytesCopied = Math.Min(length, dataLength);
_parentMessage.Limit(limit + headerLength + dataLength);
_buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied);
return bytesCopied;
}
public string Channel()
{
int headerLength = 4;
int limit = _parentMessage.Limit();
int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
_parentMessage.Limit(limit + headerLength + dataLength);
byte[] tmp = new byte[dataLength];
_buffer.GetBytes(limit + headerLength, tmp, 0, dataLength);
return Encoding.ASCII.GetString(tmp);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[StopRecordingRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='streamId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("StreamId=");
builder.Append(StreamId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='channel', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=20, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Channel=");
builder.Append(Channel());
Limit(originalLimit);
return builder;
}
}
}
| |
/*
Pax : tool support for prototyping packet processors
Nik Sultana, Cambridge University Computer Lab, June 2016
Jonny Shipton, Cambridge University Computer Lab, July 2016
Use of this source code is governed by the Apache 2.0 license; see LICENSE.
*/
using System;
using System.Collections.Generic;
using PacketDotNet;
using SharpPcap;
using System.Text;
using System.Diagnostics;
// FIXME use javadoc-style comments to describe the API
namespace Pax {
// Support for checking the version of Pax that an element expects to be run on.
// An element declares the expected major.minor.patch version of the Pax runtime,
// and the runtime checks whether it can run this element. Up-front version
// checking of this kind can help avoid situations involving mysterious
// failures.
public interface IVersioned {
int expected_major_Pax_version { get; }
int expected_minor_Pax_version { get; }
int expected_patch_Pax_version { get; }
}
// An abstract interface to packet processors.
public interface IAbstract_PacketProcessor {
ForwardingDecision process_packet (int in_port, ref Packet packet);
}
/* FIXME Rather than the sort of specification above, I'd much rather be able to
subtype derivatives of IAbstract_PacketProcessor by specialising the
ForwardingDecision result of process_packet. One idea is to use the
following spec (but note that this would add lots of complications
elsewhere, particularly in the reflection code):
// NOTE this can be specialised by specialising parameter T (ForwardingDecision)
// to specific kinds of decisions. I use this feature below.
public interface PacketProcessor<T> where T : ForwardingDecision {
T process_packet (int in_port, ref Packet packet);
}
then one could define:
public abstract class SimplePacketProcessor : IPacketProcessor<ForwardingDecision.SinglePortForward> {
...
abstract public ForwardingDecision.SinglePortForward process_packet (int in_port, ref Packet packet);
i.e., we'd use C#'s type checker instead of the silly "is" checks at runtime.
*/
public interface IHostbased_PacketProcessor {
void packetHandler (object sender, CaptureEventArgs e);
}
public interface IPacketProcessor : IAbstract_PacketProcessor, IHostbased_PacketProcessor {}
// A packet monitor does not output anything onto the network, it simply
// accumulates state based on what it observes happening on the network.
// It might produce output on side-channels, through side-effects.
// This could be used for diagnosis, to observe network activity and print
// digests to the console or log.
public abstract class PacketMonitor : IPacketProcessor {
abstract public ForwardingDecision process_packet (int in_port, ref Packet packet);
public void packetHandler (object sender, CaptureEventArgs e)
{
var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
int in_port = PaxConfig.rdeviceMap[e.Device.Name];
Debug.Assert(process_packet (in_port, ref packet) is ForwardingDecision.Drop);
#if DEBUG
// FIXME could append name of the class in the debug message, so we know which
// packet processor is being used.
Debug.Write(PaxConfig.deviceMap[in_port].Name + " -|");
#endif
}
}
// Simple packet processor: it can only transform the given packet and forward it to at most one interface.
public abstract class SimplePacketProcessor : IPacketProcessor {
// Return the offset of network interface that "packet" is to be forwarded to.
abstract public ForwardingDecision process_packet (int in_port, ref Packet packet);
public void packetHandler (object sender, CaptureEventArgs e)
{
var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
int in_port = PaxConfig.rdeviceMap[e.Device.Name];
int out_port;
ForwardingDecision des = process_packet (in_port, ref packet);
if (des is ForwardingDecision.SinglePortForward)
{
out_port = ((ForwardingDecision.SinglePortForward)des).target_port;
} else {
throw (new Exception ("Expected SinglePortForward"));
}
#if DEBUG
Debug.Write(PaxConfig.deviceMap[in_port].Name + " -1> ");
#endif
if (out_port > -1)
{
var device = PaxConfig.deviceMap[out_port];
if (packet is EthernetPacket)
((EthernetPacket)packet).SourceHwAddress = device.MacAddress;
device.SendPacket(packet);
#if DEBUG
Debug.WriteLine(PaxConfig.deviceMap[out_port].Name);
} else {
Debug.WriteLine("<dropped>");
#endif
}
}
}
// Simple packet processor that can forward to multiple interfaces. It is "simple" because
// it can only transform the given packet, and cannot generate new ones.
public abstract class MultiInterface_SimplePacketProcessor : IPacketProcessor {
// Return the offsets of network interfaces that "packet" is to be forwarded to.
abstract public ForwardingDecision process_packet (int in_port, ref Packet packet);
public void packetHandler (object sender, CaptureEventArgs e)
{
var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);
int in_port = PaxConfig.rdeviceMap[e.Device.Name];
int[] out_ports;
ForwardingDecision des = process_packet (in_port, ref packet);
if (des is ForwardingDecision.MultiPortForward)
{
out_ports = ((ForwardingDecision.MultiPortForward)des).target_ports;
/*
Since MultiPortForward works with arrays, this increases the exposure
to dud values:
* negative values within arrays
* repeated values within arrays
* an array might be larger than intended, and contains rubbish data.
These could manifest themselves as bugs or abused behaviour.
FIXME determine how each of these cases will be treated.
*/
} else {
throw (new Exception ("Expected MultiPortForward"));
}
#if DEBUG
Debug.Write(PaxConfig.deviceMap[in_port].Name + " -> ");
// It's useful to know the width of the returned array during debugging,
// since it might be that the array was wider than intended, and contained
// repeated or rubbish values.
Debug.Write("[" + out_ports.Length.ToString() + "] ");
#endif
for (int idx = 0; idx < out_ports.Length; idx++)
{
int out_port = out_ports[idx];
// Check if trying to send over a non-existent port.
if (out_port < PaxConfig_Lite.no_interfaces) {
PaxConfig.deviceMap[out_port].SendPacket(packet);
#if DEBUG
Debug.Write("(" + out_port.ToString() + ") "); // Show the network interface offset.
// And now show the network interface name that the offset resolves to.
if (idx < out_ports.Length - 1)
{
Debug.Write(PaxConfig.deviceMap[out_port].Name + ", ");
} else {
Debug.Write(PaxConfig.deviceMap[out_port].Name);
}
#endif
} else if (!(out_port < PaxConfig_Lite.no_interfaces) &&
!PaxConfig_Lite.ignore_phantom_forwarding) {
throw (new Exception ("Tried forward to non-existant port"));
}
}
#if DEBUG
Debug.WriteLine("");
#endif
}
}
public class PacketProcessor_Chain : IPacketProcessor {
List<IPacketProcessor> chain;
public PacketProcessor_Chain (List<IPacketProcessor> chain) {
this.chain = chain;
}
public void packetHandler (object sender, CaptureEventArgs e) {
foreach (IPacketProcessor pp in chain) {
pp.packetHandler (sender, e);
}
}
public ForwardingDecision process_packet (int in_port, ref Packet packet)
{
ForwardingDecision fd = null;
//We return the ForwardingDecision made by the last element in the chain.
foreach (IPacketProcessor pp in chain) {
fd = pp.process_packet (in_port, ref packet);
}
return fd;
}
}
public interface IActive {
// NOTE "PreStart" and "Start" might be called multiple times -- once for
// each device to which a packet processor is associated with.
void PreStart (ICaptureDevice device);
void Start ();
void Stop ();
}
public abstract class ByteBased_PacketProcessor : IPacketProcessor {
// FIXME include LL interface type as parameter.
abstract public void process_packet (int in_port, byte[] packet);
public void packetHandler (object sender, CaptureEventArgs e)
{
byte[] packet = e.Packet.Data;
int in_port = PaxConfig.rdeviceMap[e.Device.Name];
process_packet (in_port, packet);
}
public void send_packet (int out_port, byte[] packet, int packet_size) {
var device = PaxConfig.deviceMap[out_port];
device.SendPacket(packet, packet_size);
}
public ForwardingDecision process_packet (int in_port, ref Packet packet) {
throw new Exception("Wrong instance of 'process_packet'");
}
}
// This element does nothing to the packets it receives, and doesn't forward
// them on.
public class Dropper : PacketMonitor {
override public ForwardingDecision process_packet (int in_port, ref Packet packet)
{
return ForwardingDecision.Drop.Instance;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole
//
// 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.
// ***********************************************************************
// TODO: Get to work in Portable and Silverlight - will require building mock-assembly
#if !SILVERLIGHT && !PORTABLE
using System;
using System.Collections;
using System.IO;
using System.Threading;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
using NUnit.Tests;
using NUnit.Tests.Assemblies;
namespace NUnit.Framework.Api
{
// Functional tests of the TestAssemblyRunner and all subordinate classes
public class TestAssemblyRunnerTests : ITestListener
{
private const string MOCK_ASSEMBLY = "mock-assembly.exe";
private const string BAD_FILE = "mock-assembly.pdb";
private const string SLOW_TESTS = "slow-nunit-tests.dll";
private const string MISSING_FILE = "junk.dll";
private IDictionary _settings = new Hashtable();
private ITestAssemblyRunner _runner;
private string _mockAssemblyPath;
private string _slowTestsPath;
private int _testStartedCount;
private int _testFinishedCount;
private int _successCount;
private int _failCount;
private int _skipCount;
private int _inconclusiveCount;
[SetUp]
public void CreateRunner()
{
_mockAssemblyPath = Path.Combine(TestContext.CurrentContext.TestDirectory, MOCK_ASSEMBLY);
_slowTestsPath = Path.Combine(TestContext.CurrentContext.TestDirectory, SLOW_TESTS);
_runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
_testStartedCount = 0;
_testFinishedCount = 0;
_successCount = 0;
_failCount = 0;
_skipCount = 0;
_inconclusiveCount = 0;
}
#region Load
[Test]
public void Load_GoodFile_ReturnsRunnableSuite()
{
var result = _runner.Load(_mockAssemblyPath, _settings);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(MOCK_ASSEMBLY));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.Runnable));
Assert.That(result.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void Load_FileNotFound_ReturnsNonRunnableSuite()
{
var result = _runner.Load(MISSING_FILE, _settings);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(MISSING_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
#if NETCF
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("File or assembly name").And.Contains(MISSING_FILE));
#else
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Could not load").And.Contains(MISSING_FILE));
#endif
}
[Test]
public void Load_BadFile_ReturnsNonRunnableSuite()
{
var result = _runner.Load(BAD_FILE, _settings);
Assert.That(result.IsSuite);
Assert.That(result, Is.TypeOf<TestAssembly>());
Assert.That(result.Name, Is.EqualTo(BAD_FILE));
Assert.That(result.RunState, Is.EqualTo(Interfaces.RunState.NotRunnable));
Assert.That(result.TestCaseCount, Is.EqualTo(0));
#if NETCF
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("File or assembly name").And.Contains(BAD_FILE));
#else
Assert.That(result.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Could not load").And.Contains(BAD_FILE));
#endif
}
#endregion
#region CountTestCases
[Test]
public void CountTestCases_AfterLoad_ReturnsCorrectCount()
{
_runner.Load(_mockAssemblyPath, _settings);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(MockAssembly.Tests));
}
[Test]
public void CountTestCases_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.CountTestCases(TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded"));
}
[Test]
public void CountTestCases_FileNotFound_ReturnsZero()
{
_runner.Load(MISSING_FILE, _settings);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
[Test]
public void CountTestCases_BadFile_ReturnsZero()
{
_runner.Load(BAD_FILE, _settings);
Assert.That(_runner.CountTestCases(TestFilter.Empty), Is.EqualTo(0));
}
#endregion
#region Run
[Test]
public void Run_AfterLoad_ReturnsRunnableSuite()
{
_runner.Load(_mockAssemblyPath, _settings);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(result.PassCount, Is.EqualTo(MockAssembly.Success));
Assert.That(result.FailCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_AfterLoad_SendsExpectedEvents()
{
_runner.Load(_mockAssemblyPath, _settings);
var result = _runner.Run(this, TestFilter.Empty);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.Tests - IgnoredFixture.Tests - BadFixture.Tests - ExplicitFixture.Tests));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Success));
Assert.That(_failCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void Run_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.Run(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void Run_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, _settings);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(result.Message, Does.StartWith("File or assembly name").And.Contains(MISSING_FILE));
#else
Assert.That(result.Message, Does.StartWith("Could not load").And.Contains(MISSING_FILE));
#endif
}
[Test]
public void Run_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, _settings);
var result = _runner.Run(TestListener.NULL, TestFilter.Empty);
Assert.That(result.Test.IsSuite);
Assert.That(result.Test, Is.TypeOf<TestAssembly>());
Assert.That(result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(result.Message, Does.StartWith("File or assembly name").And.Contains(BAD_FILE));
#else
Assert.That(result.Message, Does.StartWith("Could not load").And.Contains(BAD_FILE));
#endif
}
#endregion
#region RunAsync
[Test]
public void RunAsync_AfterLoad_ReturnsRunnableSuite()
{
_runner.Load(_mockAssemblyPath, _settings);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.ChildFailure));
Assert.That(_runner.Result.PassCount, Is.EqualTo(MockAssembly.Success));
Assert.That(_runner.Result.FailCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(_runner.Result.SkipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_runner.Result.InconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_AfterLoad_SendsExpectedEvents()
{
_runner.Load(_mockAssemblyPath, _settings);
_runner.RunAsync(this, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.That(_testStartedCount, Is.EqualTo(MockAssembly.Tests - IgnoredFixture.Tests - BadFixture.Tests - ExplicitFixture.Tests));
Assert.That(_testFinishedCount, Is.EqualTo(MockAssembly.Tests));
Assert.That(_successCount, Is.EqualTo(MockAssembly.Success));
Assert.That(_failCount, Is.EqualTo(MockAssembly.ErrorsAndFailures));
Assert.That(_skipCount, Is.EqualTo(MockAssembly.Skipped));
Assert.That(_inconclusiveCount, Is.EqualTo(MockAssembly.Inconclusive));
}
[Test]
public void RunAsync_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => _runner.RunAsync(TestListener.NULL, TestFilter.Empty));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void RunAsync_FileNotFound_ReturnsNonRunnableSuite()
{
_runner.Load(MISSING_FILE, _settings);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(_runner.Result.Message, Does.StartWith("File or assembly name").And.Contains(MISSING_FILE));
#else
Assert.That(_runner.Result.Message, Does.StartWith("Could not load").And.Contains(MISSING_FILE));
#endif
}
[Test]
public void RunAsync_BadFile_ReturnsNonRunnableSuite()
{
_runner.Load(BAD_FILE, _settings);
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.NotNull(_runner.Result, "No result returned");
Assert.That(_runner.Result.Test.IsSuite);
Assert.That(_runner.Result.Test, Is.TypeOf<TestAssembly>());
Assert.That(_runner.Result.Test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(_runner.Result.Test.TestCaseCount, Is.EqualTo(0));
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.NotRunnable.WithSite(FailureSite.SetUp)));
#if NETCF
Assert.That(_runner.Result.Message, Does.StartWith("File or assembly name").And.Contains(BAD_FILE));
#else
Assert.That(_runner.Result.Message, Does.StartWith("Could not load").And.Contains(BAD_FILE));
#endif
}
#endregion
#region StopRun
[Test]
public void StopRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(false);
}
[Test]
public void StopRun_WhenTestIsRunning_StopsTest()
{
var tests = _runner.Load(_slowTestsPath, _settings);
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(false);
_runner.WaitForCompletion(Timeout.Infinite);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success) // Test may have finished before we stopped it
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region Cancel Run
[Test]
public void CancelRun_WhenNoTestIsRunning_Succeeds()
{
_runner.StopRun(true);
}
[Test, Explicit("Intermittent failure")]
public void CancelRun_WhenTestIsRunning_StopsTest()
{
var tests = _runner.Load(_slowTestsPath, _settings);
var count = tests.TestCaseCount;
_runner.RunAsync(TestListener.NULL, TestFilter.Empty);
_runner.StopRun(true);
// When cancelling, the completion event may not be signalled,
// so we only wait a short time before checking.
_runner.WaitForCompletion(10000);
Assert.True(_runner.IsTestComplete, "Test is not complete");
if (_runner.Result.ResultState != ResultState.Success)
{
Assert.That(_runner.Result.ResultState, Is.EqualTo(ResultState.Cancelled));
Assert.That(_runner.Result.PassCount, Is.LessThan(count));
}
}
#endregion
#region ITestListener Implementation
void ITestListener.TestStarted(ITest test)
{
if (!test.IsSuite)
_testStartedCount++;
}
void ITestListener.TestFinished(ITestResult result)
{
if (!result.Test.IsSuite)
{
_testFinishedCount++;
switch (result.ResultState.Status)
{
case TestStatus.Passed:
_successCount++;
break;
case TestStatus.Failed:
_failCount++;
break;
case TestStatus.Skipped:
_skipCount++;
break;
case TestStatus.Inconclusive:
_inconclusiveCount++;
break;
}
}
}
#endregion
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NSubstitute.Core;
using NSubstitute.Routing;
using NSubstitute.ClearExtensions;
#if (NET4 || NET45 || NETSTANDARD1_5)
using System.Threading.Tasks;
#endif
namespace NSubstitute
{
public static class SubstituteExtensions
{
/// <summary>
/// Set a return value for this call.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return</param>
/// <param name="returnThese">Optionally return these values next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this T value, T returnThis, params T[] returnThese)
{
return Returns(MatchArgs.AsSpecifiedInCall, returnThis, returnThese);
}
/// <summary>
/// Set a return value for this call, calculated by the provided function.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this T value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
return Returns(MatchArgs.AsSpecifiedInCall, returnThis, returnThese);
}
#if (NET4 || NET45 || NETSTANDARD1_5)
/// <summary>
/// Set a return value for this call. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return. Will be wrapped in a Task</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this Task<T> value, T returnThis, params T[] returnThese)
{
var wrappedReturnValue = CompletedTask(returnThis);
var wrappedParameters = returnThese.Select(CompletedTask);
return Returns(MatchArgs.AsSpecifiedInCall, wrappedReturnValue, wrappedParameters.ToArray());
}
/// <summary>
/// Set a return value for this call, calculated by the provided function. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall Returns<T>(this Task<T> value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
var wrappedFunc = WrapFuncInTask(returnThis);
var wrappedFuncs = returnThese.Select(WrapFuncInTask);
return Returns(MatchArgs.AsSpecifiedInCall, wrappedFunc, wrappedFuncs.ToArray());
}
/// <summary>
/// Set a return value for this call made with any arguments. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return</param>
/// <param name="returnThese">Optionally return these values next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this Task<T> value, T returnThis, params T[] returnThese)
{
var wrappedReturnValue = CompletedTask(returnThis);
var wrappedParameters = returnThese.Select(CompletedTask);
return Returns(MatchArgs.Any, wrappedReturnValue, wrappedParameters.ToArray());
}
/// <summary>
/// Set a return value for this call made with any arguments, calculated by the provided function. The value(s) to be returned will be wrapped in Tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this Task<T> value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
var wrappedFunc = WrapFuncInTask(returnThis);
var wrappedFuncs = returnThese.Select(WrapFuncInTask);
return Returns(MatchArgs.Any, wrappedFunc, wrappedFuncs.ToArray());
}
#endif
/// <summary>
/// Set a return value for this call made with any arguments.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Value to return</param>
/// <param name="returnThese">Optionally return these values next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this T value, T returnThis, params T[] returnThese)
{
return Returns(MatchArgs.Any, returnThis, returnThese);
}
/// <summary>
/// Set a return value for this call made with any arguments, calculated by the provided function.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="returnThis">Function to calculate the return value</param>
/// <param name="returnThese">Optionally use these functions next</param>
/// <returns></returns>
public static ConfiguredCall ReturnsForAnyArgs<T>(this T value, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
return Returns(MatchArgs.Any, returnThis, returnThese);
}
internal static ConfiguredCall Returns<T>(MatchArgs matchArgs, T returnThis, params T[] returnThese)
{
var context = SubstitutionContext.Current;
IReturn returnValue;
if (returnThese == null || returnThese.Length == 0)
{
returnValue = new ReturnValue(returnThis);
}
else
{
returnValue = new ReturnMultipleValues<T>(new[] { returnThis }.Concat(returnThese).ToArray());
}
return context.LastCallShouldReturn(returnValue, matchArgs);
}
internal static ConfiguredCall Returns<T>(MatchArgs matchArgs, Func<CallInfo, T> returnThis, params Func<CallInfo, T>[] returnThese)
{
var context = SubstitutionContext.Current;
IReturn returnValue;
if (returnThese == null || returnThese.Length == 0)
{
returnValue = new ReturnValueFromFunc<T>(returnThis);
}
else
{
returnValue = new ReturnMultipleFuncsValues<T>(new[] { returnThis }.Concat(returnThese).ToArray());
}
return context.LastCallShouldReturn(returnValue, matchArgs);
}
/// <summary>
/// Checks this substitute has received the following call.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T Received<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.AsSpecifiedInCall, Quantity.AtLeastOne()));
return substitute;
}
/// <summary>
/// Checks this substitute has received the following call the required number of times.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="requiredNumberOfCalls"></param>
/// <returns></returns>
public static T Received<T>(this T substitute, int requiredNumberOfCalls) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.AsSpecifiedInCall, Quantity.Exactly(requiredNumberOfCalls)));
return substitute;
}
/// <summary>
/// Checks this substitute has not received the following call.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T DidNotReceive<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.AsSpecifiedInCall, Quantity.None()));
return substitute;
}
/// <summary>
/// Checks this substitute has received the following call with any arguments.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T ReceivedWithAnyArgs<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.Any, Quantity.AtLeastOne()));
return substitute;
}
/// <summary>
/// Checks this substitute has received the following call with any arguments the required number of times.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="requiredNumberOfCalls"></param>
/// <returns></returns>
public static T ReceivedWithAnyArgs<T>(this T substitute, int requiredNumberOfCalls) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.Any, Quantity.Exactly(requiredNumberOfCalls)));
return substitute;
}
/// <summary>
/// Checks this substitute has not received the following call with any arguments.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static T DidNotReceiveWithAnyArgs<T>(this T substitute) where T : class
{
var router = GetRouterForSubstitute(substitute);
router.SetRoute(x => RouteFactory().CheckReceivedCalls(x, MatchArgs.Any, Quantity.None()));
return substitute;
}
/// <summary>
/// Forget all the calls this substitute has received.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <remarks>
/// Note that this will not clear any results set up for the substitute using Returns().
/// See <see cref="NSubstitute.ClearExtensions.ClearExtensions.ClearSubstitute{T}"/> for more options with resetting
/// a substitute.
/// </remarks>
public static void ClearReceivedCalls<T>(this T substitute) where T : class
{
substitute.ClearSubstitute(ClearOptions.ReceivedCalls);
}
/// <summary>
/// Perform an action when this member is called.
/// Must be followed by <see cref="WhenCalled{T}.Do(Action{CallInfo})"/> to provide the callback.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="substituteCall"></param>
/// <returns></returns>
public static WhenCalled<T> When<T>(this T substitute, Action<T> substituteCall) where T : class
{
var context = SubstitutionContext.Current;
return new WhenCalled<T>(context, substitute, substituteCall, MatchArgs.AsSpecifiedInCall);
}
/// <summary>
/// Perform an action when this member is called with any arguments.
/// Must be followed by <see cref="WhenCalled{T}.Do(Action{CallInfo})"/> to provide the callback.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <param name="substituteCall"></param>
/// <returns></returns>
public static WhenCalled<T> WhenForAnyArgs<T>(this T substitute, Action<T> substituteCall) where T : class
{
var context = SubstitutionContext.Current;
return new WhenCalled<T>(context, substitute, substituteCall, MatchArgs.Any);
}
/// <summary>
/// Returns the calls received by this substitute.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="substitute"></param>
/// <returns></returns>
public static IEnumerable<ICall> ReceivedCalls<T>(this T substitute) where T : class
{
return GetRouterForSubstitute(substitute).ReceivedCalls();
}
#if (NET4 || NET45 || NETSTANDARD1_5)
private static Func<CallInfo, Task<T>> WrapFuncInTask<T>(Func<CallInfo, T> returnThis)
{
return x => CompletedTask(returnThis(x));
}
internal static Task<T> CompletedTask<T>(T result)
{
#if (NET45 || NETSTANDARD1_5)
return Task.FromResult(result);
#elif NET4
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(result);
return tcs.Task;
#endif
}
#endif
private static ICallRouter GetRouterForSubstitute<T>(T substitute)
{
var context = SubstitutionContext.Current;
return context.GetCallRouterFor(substitute);
}
private static IRouteFactory RouteFactory()
{
return SubstitutionContext.Current.GetRouteFactory();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class NullableArrayIndexTests
{
#region NullableBool tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableBoolArrayIndexTest(bool useInterpreter)
{
CheckNullableBoolArrayIndex(GenerateNullableBoolArray(0), useInterpreter);
CheckNullableBoolArrayIndex(GenerateNullableBoolArray(1), useInterpreter);
CheckNullableBoolArrayIndex(GenerateNullableBoolArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableBoolArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableBoolArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableBoolArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableBoolArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(0), -1, useInterpreter);
CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(0), 0, useInterpreter);
CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(1), -1, useInterpreter);
CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(1), 1, useInterpreter);
CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(5), -1, useInterpreter);
CheckExceptionNullableBoolArrayIndex(GenerateNullableBoolArray(5), 5, useInterpreter);
}
#endregion
#region NullableByte tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableByteArrayIndexTest(bool useInterpreter)
{
CheckNullableByteArrayIndex(GenerateNullableByteArray(0), useInterpreter);
CheckNullableByteArrayIndex(GenerateNullableByteArray(1), useInterpreter);
CheckNullableByteArrayIndex(GenerateNullableByteArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableByteArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableByteArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableByteArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableByteArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(0), -1, useInterpreter);
CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(0), 0, useInterpreter);
CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(1), -1, useInterpreter);
CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(1), 1, useInterpreter);
CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(5), -1, useInterpreter);
CheckExceptionNullableByteArrayIndex(GenerateNullableByteArray(5), 5, useInterpreter);
}
#endregion
#region NullableChar tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableCharArrayIndexTest(bool useInterpreter)
{
CheckNullableCharArrayIndex(GenerateNullableCharArray(0), useInterpreter);
CheckNullableCharArrayIndex(GenerateNullableCharArray(1), useInterpreter);
CheckNullableCharArrayIndex(GenerateNullableCharArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableCharArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableCharArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableCharArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableCharArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(0), -1, useInterpreter);
CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(0), 0, useInterpreter);
CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(1), -1, useInterpreter);
CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(1), 1, useInterpreter);
CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(5), -1, useInterpreter);
CheckExceptionNullableCharArrayIndex(GenerateNullableCharArray(5), 5, useInterpreter);
}
#endregion
#region NullableDecimal tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalArrayIndexTest(bool useInterpreter)
{
CheckNullableDecimalArrayIndex(GenerateNullableDecimalArray(0), useInterpreter);
CheckNullableDecimalArrayIndex(GenerateNullableDecimalArray(1), useInterpreter);
CheckNullableDecimalArrayIndex(GenerateNullableDecimalArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableDecimalArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableDecimalArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableDecimalArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableDecimalArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(0), -1, useInterpreter);
CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(0), 0, useInterpreter);
CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(1), -1, useInterpreter);
CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(1), 1, useInterpreter);
CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(5), -1, useInterpreter);
CheckExceptionNullableDecimalArrayIndex(GenerateNullableDecimalArray(5), 5, useInterpreter);
}
#endregion
#region NullableDouble tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoubleArrayIndexTest(bool useInterpreter)
{
CheckNullableDoubleArrayIndex(GenerateNullableDoubleArray(0), useInterpreter);
CheckNullableDoubleArrayIndex(GenerateNullableDoubleArray(1), useInterpreter);
CheckNullableDoubleArrayIndex(GenerateNullableDoubleArray(9), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableDoubleArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableDoubleArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableDoubleArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableDoubleArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(0), -1, useInterpreter);
CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(0), 0, useInterpreter);
CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(1), -1, useInterpreter);
CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(1), 1, useInterpreter);
CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(9), -1, useInterpreter);
CheckExceptionNullableDoubleArrayIndex(GenerateNullableDoubleArray(9), 9, useInterpreter);
}
#endregion
#region NullableEnum tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableEnumArrayIndexTest(bool useInterpreter)
{
CheckNullableEnumArrayIndex(GenerateNullableEnumArray(0), useInterpreter);
CheckNullableEnumArrayIndex(GenerateNullableEnumArray(1), useInterpreter);
CheckNullableEnumArrayIndex(GenerateNullableEnumArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableEnumArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableEnumArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableEnumArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableEnumArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(0), -1, useInterpreter);
CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(0), 0, useInterpreter);
CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(1), -1, useInterpreter);
CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(1), 1, useInterpreter);
CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(5), -1, useInterpreter);
CheckExceptionNullableEnumArrayIndex(GenerateNullableEnumArray(5), 5, useInterpreter);
}
#endregion
#region NullableLongEnum tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongEnumArrayIndexTest(bool useInterpreter)
{
CheckNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(0), useInterpreter);
CheckNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(1), useInterpreter);
CheckNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableLongEnumArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableLongEnumArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableLongEnumArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableLongEnumArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(0), -1, useInterpreter);
CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(0), 0, useInterpreter);
CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(1), -1, useInterpreter);
CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(1), 1, useInterpreter);
CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(5), -1, useInterpreter);
CheckExceptionNullableLongEnumArrayIndex(GenerateNullableLongEnumArray(5), 5, useInterpreter);
}
#endregion
#region NullableFloat tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatArrayIndexTest(bool useInterpreter)
{
CheckNullableFloatArrayIndex(GenerateNullableFloatArray(0), useInterpreter);
CheckNullableFloatArrayIndex(GenerateNullableFloatArray(1), useInterpreter);
CheckNullableFloatArrayIndex(GenerateNullableFloatArray(9), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableFloatArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableFloatArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableFloatArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableFloatArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(0), -1, useInterpreter);
CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(0), 0, useInterpreter);
CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(1), -1, useInterpreter);
CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(1), 1, useInterpreter);
CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(9), -1, useInterpreter);
CheckExceptionNullableFloatArrayIndex(GenerateNullableFloatArray(9), 9, useInterpreter);
}
#endregion
#region NullableInt tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntArrayIndexTest(bool useInterpreter)
{
CheckNullableIntArrayIndex(GenerateNullableIntArray(0), useInterpreter);
CheckNullableIntArrayIndex(GenerateNullableIntArray(1), useInterpreter);
CheckNullableIntArrayIndex(GenerateNullableIntArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableIntArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableIntArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableIntArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableIntArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(0), -1, useInterpreter);
CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(0), 0, useInterpreter);
CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(1), -1, useInterpreter);
CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(1), 1, useInterpreter);
CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(5), -1, useInterpreter);
CheckExceptionNullableIntArrayIndex(GenerateNullableIntArray(5), 5, useInterpreter);
}
#endregion
#region NullableLong tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongArrayIndexTest(bool useInterpreter)
{
CheckNullableLongArrayIndex(GenerateNullableLongArray(0), useInterpreter);
CheckNullableLongArrayIndex(GenerateNullableLongArray(1), useInterpreter);
CheckNullableLongArrayIndex(GenerateNullableLongArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableLongArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableLongArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableLongArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableLongArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(0), -1, useInterpreter);
CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(0), 0, useInterpreter);
CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(1), -1, useInterpreter);
CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(1), 1, useInterpreter);
CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(5), -1, useInterpreter);
CheckExceptionNullableLongArrayIndex(GenerateNullableLongArray(5), 5, useInterpreter);
}
#endregion
#region NullableSByte tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableSByteArrayIndexTest(bool useInterpreter)
{
CheckNullableSByteArrayIndex(GenerateNullableSByteArray(0), useInterpreter);
CheckNullableSByteArrayIndex(GenerateNullableSByteArray(1), useInterpreter);
CheckNullableSByteArrayIndex(GenerateNullableSByteArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableSByteArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableSByteArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableSByteArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableSByteArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(0), -1, useInterpreter);
CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(0), 0, useInterpreter);
CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(1), -1, useInterpreter);
CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(1), 1, useInterpreter);
CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(5), -1, useInterpreter);
CheckExceptionNullableSByteArrayIndex(GenerateNullableSByteArray(5), 5, useInterpreter);
}
#endregion
#region NullableShort tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortArrayIndexTest(bool useInterpreter)
{
CheckNullableShortArrayIndex(GenerateNullableShortArray(0), useInterpreter);
CheckNullableShortArrayIndex(GenerateNullableShortArray(1), useInterpreter);
CheckNullableShortArrayIndex(GenerateNullableShortArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableShortArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableShortArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableShortArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableShortArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(0), -1, useInterpreter);
CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(0), 0, useInterpreter);
CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(1), -1, useInterpreter);
CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(1), 1, useInterpreter);
CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(5), -1, useInterpreter);
CheckExceptionNullableShortArrayIndex(GenerateNullableShortArray(5), 5, useInterpreter);
}
#endregion
#region NullableStruct tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableStructArrayIndexTest(bool useInterpreter)
{
CheckNullableStructArrayIndex(GenerateNullableStructArray(0), useInterpreter);
CheckNullableStructArrayIndex(GenerateNullableStructArray(1), useInterpreter);
CheckNullableStructArrayIndex(GenerateNullableStructArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableStructArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableStructArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableStructArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableStructArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(0), -1, useInterpreter);
CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(0), 0, useInterpreter);
CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(1), -1, useInterpreter);
CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(1), 1, useInterpreter);
CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(5), -1, useInterpreter);
CheckExceptionNullableStructArrayIndex(GenerateNullableStructArray(5), 5, useInterpreter);
}
#endregion
#region NullableStructWithString tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableStructWithStringArrayIndexTest(bool useInterpreter)
{
CheckNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(0), useInterpreter);
CheckNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(1), useInterpreter);
CheckNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableStructWithStringArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableStructWithStringArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableStructWithStringArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableStructWithStringArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(0), -1, useInterpreter);
CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(0), 0, useInterpreter);
CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(1), -1, useInterpreter);
CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(1), 1, useInterpreter);
CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(5), -1, useInterpreter);
CheckExceptionNullableStructWithStringArrayIndex(GenerateNullableStructWithStringArray(5), 5, useInterpreter);
}
#endregion
#region NullableStructWithStringAndValue tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableStructWithStringAndValueArrayIndexTest(bool useInterpreter)
{
CheckNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(0), useInterpreter);
CheckNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(1), useInterpreter);
CheckNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableStructWithStringAndValueArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableStructWithStringAndValueArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableStructWithStringAndValueArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableStructWithStringAndValueArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(0), -1, useInterpreter);
CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(0), 0, useInterpreter);
CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(1), -1, useInterpreter);
CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(1), 1, useInterpreter);
CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(5), -1, useInterpreter);
CheckExceptionNullableStructWithStringAndValueArrayIndex(GenerateNullableStructWithStringAndValueArray(5), 5, useInterpreter);
}
#endregion
#region NullableStructWithTwoValues tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableStructWithTwoValuesArrayIndexTest(bool useInterpreter)
{
CheckNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(0), useInterpreter);
CheckNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(1), useInterpreter);
CheckNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableStructWithTwoValuesArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableStructWithTwoValuesArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableStructWithTwoValuesArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableStructWithTwoValuesArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(0), -1, useInterpreter);
CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(0), 0, useInterpreter);
CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(1), -1, useInterpreter);
CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(1), 1, useInterpreter);
CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(5), -1, useInterpreter);
CheckExceptionNullableStructWithTwoValuesArrayIndex(GenerateNullableStructWithTwoValuesArray(5), 5, useInterpreter);
}
#endregion
#region NullableStructWithStruct tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableStructWithStructArrayIndexTest(bool useInterpreter)
{
CheckNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(0), useInterpreter);
CheckNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(1), useInterpreter);
CheckNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableStructWithStructArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableStructWithStructArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableStructWithStructArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableStructWithStructArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(0), -1, useInterpreter);
CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(0), 0, useInterpreter);
CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(1), -1, useInterpreter);
CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(1), 1, useInterpreter);
CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(5), -1, useInterpreter);
CheckExceptionNullableStructWithStructArrayIndex(GenerateNullableStructWithStructArray(5), 5, useInterpreter);
}
#endregion
#region NullableUInt tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntArrayIndexTest(bool useInterpreter)
{
CheckNullableUIntArrayIndex(GenerateNullableUIntArray(0), useInterpreter);
CheckNullableUIntArrayIndex(GenerateNullableUIntArray(1), useInterpreter);
CheckNullableUIntArrayIndex(GenerateNullableUIntArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableUIntArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableUIntArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableUIntArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableUIntArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(0), -1, useInterpreter);
CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(0), 0, useInterpreter);
CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(1), -1, useInterpreter);
CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(1), 1, useInterpreter);
CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(5), -1, useInterpreter);
CheckExceptionNullableUIntArrayIndex(GenerateNullableUIntArray(5), 5, useInterpreter);
}
#endregion
#region NullableULong tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongArrayIndexTest(bool useInterpreter)
{
CheckNullableULongArrayIndex(GenerateNullableULongArray(0), useInterpreter);
CheckNullableULongArrayIndex(GenerateNullableULongArray(1), useInterpreter);
CheckNullableULongArrayIndex(GenerateNullableULongArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableULongArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableULongArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableULongArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableULongArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(0), -1, useInterpreter);
CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(0), 0, useInterpreter);
CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(1), -1, useInterpreter);
CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(1), 1, useInterpreter);
CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(5), -1, useInterpreter);
CheckExceptionNullableULongArrayIndex(GenerateNullableULongArray(5), 5, useInterpreter);
}
#endregion
#region NullableUShort tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortArrayIndexTest(bool useInterpreter)
{
CheckNullableUShortArrayIndex(GenerateNullableUShortArray(0), useInterpreter);
CheckNullableUShortArrayIndex(GenerateNullableUShortArray(1), useInterpreter);
CheckNullableUShortArrayIndex(GenerateNullableUShortArray(5), useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableUShortArrayIndexTest(bool useInterpreter)
{
// null arrays
CheckExceptionNullableUShortArrayIndex(null, -1, useInterpreter);
CheckExceptionNullableUShortArrayIndex(null, 0, useInterpreter);
CheckExceptionNullableUShortArrayIndex(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(0), -1, useInterpreter);
CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(0), 0, useInterpreter);
CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(1), -1, useInterpreter);
CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(1), 1, useInterpreter);
CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(5), -1, useInterpreter);
CheckExceptionNullableUShortArrayIndex(GenerateNullableUShortArray(5), 5, useInterpreter);
}
#endregion
#region Generic tests
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableGenericWithStructRestriction(bool useInterpreter)
{
CheckNullableGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableGenericWithStructRestriction(bool useInterpreter)
{
CheckExceptionNullableGenericWithStructRestrictionHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableGenericWithStructRestriction2(bool useInterpreter)
{
CheckNullableGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableGenericWithStructRestriction2(bool useInterpreter)
{
CheckExceptionNullableGenericWithStructRestrictionHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableGenericWithStructRestriction3(bool useInterpreter)
{
CheckNullableGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckExceptionNullableGenericWithStructRestriction3(bool useInterpreter)
{
CheckExceptionNullableGenericWithStructRestrictionHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
private static void CheckNullableGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(0), useInterpreter);
CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(1), useInterpreter);
CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(5), useInterpreter);
}
private static void CheckExceptionNullableGenericWithStructRestrictionHelper<Ts>(bool useInterpreter) where Ts : struct
{
// null arrays
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(null, -1, useInterpreter);
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(null, 0, useInterpreter);
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(null, 1, useInterpreter);
// index out of bounds
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(0), -1, useInterpreter);
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(0), 0, useInterpreter);
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(1), -1, useInterpreter);
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(1), 1, useInterpreter);
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(5), -1, useInterpreter);
CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(GenerateNullableGenericWithStructRestrictionArray<Ts>(5), 5, useInterpreter);
}
#endregion
#region Generate array
private static bool?[] GenerateNullableBoolArray(int size)
{
bool?[] array = new bool?[] { true, false };
bool?[] result = new bool?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static byte?[] GenerateNullableByteArray(int size)
{
byte?[] array = new byte?[] { 0, 1, byte.MaxValue };
byte?[] result = new byte?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static char?[] GenerateNullableCharArray(int size)
{
char?[] array = new char?[] { '\0', '\b', 'A', '\uffff' };
char?[] result = new char?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static decimal?[] GenerateNullableDecimalArray(int size)
{
decimal?[] array = new decimal?[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
decimal?[] result = new decimal?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static double?[] GenerateNullableDoubleArray(int size)
{
double?[] array = new double?[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
double?[] result = new double?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static E?[] GenerateNullableEnumArray(int size)
{
E?[] array = new E?[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue };
E?[] result = new E?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static El?[] GenerateNullableLongEnumArray(int size)
{
El?[] array = new El?[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue };
El?[] result = new El?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static float?[] GenerateNullableFloatArray(int size)
{
float?[] array = new float?[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
float?[] result = new float?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static int?[] GenerateNullableIntArray(int size)
{
int?[] array = new int?[] { 0, 1, -1, int.MinValue, int.MaxValue };
int?[] result = new int?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static long?[] GenerateNullableLongArray(int size)
{
long?[] array = new long?[] { 0, 1, -1, long.MinValue, long.MaxValue };
long?[] result = new long?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static sbyte?[] GenerateNullableSByteArray(int size)
{
sbyte?[] array = new sbyte?[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
sbyte?[] result = new sbyte?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static short?[] GenerateNullableShortArray(int size)
{
short?[] array = new short?[] { 0, 1, -1, short.MinValue, short.MaxValue };
short?[] result = new short?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static S?[] GenerateNullableStructArray(int size)
{
S?[] array = new S?[] { default(S), new S() };
S?[] result = new S?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sc?[] GenerateNullableStructWithStringArray(int size)
{
Sc?[] array = new Sc?[] { default(Sc), new Sc(), new Sc(null) };
Sc?[] result = new Sc?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Scs?[] GenerateNullableStructWithStringAndValueArray(int size)
{
Scs?[] array = new Scs?[] { default(Scs), new Scs(), new Scs(null, new S()) };
Scs?[] result = new Scs?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sp?[] GenerateNullableStructWithTwoValuesArray(int size)
{
Sp?[] array = new Sp?[] { default(Sp), new Sp(), new Sp(5, 5.0) };
Sp?[] result = new Sp?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ss?[] GenerateNullableStructWithStructArray(int size)
{
Ss?[] array = new Ss?[] { default(Ss), new Ss(), new Ss(new S()) };
Ss?[] result = new Ss?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static uint?[] GenerateNullableUIntArray(int size)
{
uint?[] array = new uint?[] { 0, 1, uint.MaxValue };
uint?[] result = new uint?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ulong?[] GenerateNullableULongArray(int size)
{
ulong?[] array = new ulong?[] { 0, 1, ulong.MaxValue };
ulong?[] result = new ulong?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ushort?[] GenerateNullableUShortArray(int size)
{
ushort?[] array = new ushort?[] { 0, 1, ushort.MaxValue };
ushort?[] result = new ushort?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ts?[] GenerateNullableGenericWithStructRestrictionArray<Ts>(int size) where Ts : struct
{
Ts?[] array = new Ts?[] { default(Ts), new Ts() };
Ts?[] result = new Ts?[size];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
#endregion
#region Check array index
private static void CheckNullableBoolArrayIndex(bool?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableBoolArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableByteArrayIndex(byte?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableByteArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableCharArrayIndex(char?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableCharArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableDecimalArrayIndex(decimal?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableDecimalArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableDoubleArrayIndex(double?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableDoubleArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableEnumArrayIndex(E?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableEnumArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableLongEnumArrayIndex(El?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableLongEnumArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableFloatArrayIndex(float?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableFloatArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableIntArrayIndex(int?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableIntArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableLongArrayIndex(long?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableLongArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableSByteArrayIndex(sbyte?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableSByteArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableShortArrayIndex(short?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableShortArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableStructArrayIndex(S?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableStructArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableStructWithStringArrayIndex(Sc?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableStructWithStringArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableStructWithStringAndValueArrayIndex(Scs?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableStructWithStringAndValueArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableStructWithTwoValuesArrayIndex(Sp?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableStructWithTwoValuesArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableStructWithStructArrayIndex(Ss?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableStructWithStructArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableUIntArrayIndex(uint?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableUIntArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableULongArrayIndex(ulong?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableULongArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableUShortArrayIndex(ushort?[] array, bool useInterpreter)
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableUShortArrayIndexExpression(array, i, useInterpreter);
}
Assert.True(success);
}
private static void CheckNullableGenericWithStructRestrictionArrayIndex<Ts>(Ts?[] array, bool useInterpreter) where Ts : struct
{
bool success = true;
for (int i = 0; i < array.Length; i++)
{
success &= CheckNullableGenericWithStructRestrictionArrayIndexExpression<Ts>(array, i, useInterpreter);
}
Assert.True(success);
}
#endregion
#region Check index expression
private static bool CheckNullableBoolArrayIndexExpression(bool?[] array, int index, bool useInterpreter)
{
Expression<Func<bool?>> e =
Expression.Lambda<Func<bool?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(bool?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<bool?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableByteArrayIndexExpression(byte?[] array, int index, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(byte?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<byte?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableCharArrayIndexExpression(char?[] array, int index, bool useInterpreter)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(char?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<char?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableDecimalArrayIndexExpression(decimal?[] array, int index, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(decimal?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableDoubleArrayIndexExpression(double?[] array, int index, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(double?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<double?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableEnumArrayIndexExpression(E?[] array, int index, bool useInterpreter)
{
Expression<Func<E?>> e =
Expression.Lambda<Func<E?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(E?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<E?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableLongEnumArrayIndexExpression(El?[] array, int index, bool useInterpreter)
{
Expression<Func<El?>> e =
Expression.Lambda<Func<El?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(El?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<El?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableFloatArrayIndexExpression(float?[] array, int index, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(float?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<float?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableIntArrayIndexExpression(int?[] array, int index, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(int?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableLongArrayIndexExpression(long?[] array, int index, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(long?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<long?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableSByteArrayIndexExpression(sbyte?[] array, int index, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(sbyte?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableShortArrayIndexExpression(short?[] array, int index, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(short?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<short?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableStructArrayIndexExpression(S?[] array, int index, bool useInterpreter)
{
Expression<Func<S?>> e =
Expression.Lambda<Func<S?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(S?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<S?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableStructWithStringArrayIndexExpression(Sc?[] array, int index, bool useInterpreter)
{
Expression<Func<Sc?>> e =
Expression.Lambda<Func<Sc?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(Sc?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<Sc?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableStructWithStringAndValueArrayIndexExpression(Scs?[] array, int index, bool useInterpreter)
{
Expression<Func<Scs?>> e =
Expression.Lambda<Func<Scs?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(Scs?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<Scs?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableStructWithTwoValuesArrayIndexExpression(Sp?[] array, int index, bool useInterpreter)
{
Expression<Func<Sp?>> e =
Expression.Lambda<Func<Sp?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(Sp?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<Sp?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableStructWithStructArrayIndexExpression(Ss?[] array, int index, bool useInterpreter)
{
Expression<Func<Ss?>> e =
Expression.Lambda<Func<Ss?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(Ss?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<Ss?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableUIntArrayIndexExpression(uint?[] array, int index, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(uint?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<uint?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableULongArrayIndexExpression(ulong?[] array, int index, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(ulong?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableUShortArrayIndexExpression(ushort?[] array, int index, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(ushort?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
private static bool CheckNullableGenericWithStructRestrictionArrayIndexExpression<Ts>(Ts?[] array, int index, bool useInterpreter) where Ts : struct
{
Expression<Func<Ts?>> e =
Expression.Lambda<Func<Ts?>>(
Expression.ArrayIndex(Expression.Constant(array, typeof(Ts?[])),
Expression.Constant(index, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<Ts?> f = e.Compile(useInterpreter);
return object.Equals(f(), array[index]);
}
#endregion
#region Check exception array index
private static void CheckExceptionNullableBoolArrayIndex(bool?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableBoolArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableBoolArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableByteArrayIndex(byte?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableByteArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableByteArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableCharArrayIndex(char?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableCharArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableCharArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableDecimalArrayIndex(decimal?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableDecimalArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableDecimalArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableDoubleArrayIndex(double?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableDoubleArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableDoubleArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableEnumArrayIndex(E?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableEnumArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableEnumArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableLongEnumArrayIndex(El?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableLongEnumArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableLongEnumArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableFloatArrayIndex(float?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableFloatArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableFloatArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableIntArrayIndex(int?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableIntArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableIntArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableLongArrayIndex(long?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableLongArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableLongArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableSByteArrayIndex(sbyte?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableSByteArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableSByteArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableShortArrayIndex(short?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableShortArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableShortArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableStructArrayIndex(S?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableStructArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableStructArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableStructWithStringArrayIndex(Sc?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableStructWithStringArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableStructWithStringArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableStructWithStringAndValueArrayIndex(Scs?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableStructWithStringAndValueArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableStructWithStringAndValueArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableStructWithTwoValuesArrayIndex(Sp?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableStructWithTwoValuesArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableStructWithTwoValuesArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableStructWithStructArrayIndex(Ss?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableStructWithStructArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableStructWithStructArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableUIntArrayIndex(uint?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableUIntArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableUIntArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableULongArrayIndex(ulong?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableULongArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableULongArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableUShortArrayIndex(ushort?[] array, int index, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableUShortArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableUShortArrayIndexExpression(array, index, useInterpreter));
}
private static void CheckExceptionNullableGenericWithStructRestrictionArrayIndex<Ts>(Ts?[] array, int index, bool useInterpreter) where Ts : struct
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckNullableGenericWithStructRestrictionArrayIndexExpression(array, index, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckNullableGenericWithStructRestrictionArrayIndexExpression(array, index, useInterpreter));
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// RandomAttribute is used to supply a set of random _values
/// to a single parameter of a parameterized test.
/// </summary>
public class RandomAttribute : DataAttribute, IParameterDataSource
{
private RandomDataSource _source;
private int _count;
#region Constructors
/// <summary>
/// Construct a random set of values appropriate for the Type of the
/// parameter on which the attribute appears, specifying only the count.
/// </summary>
/// <param name="count"></param>
public RandomAttribute(int count)
{
_count = count;
}
/// <summary>
/// Construct a set of ints within a specified range
/// </summary>
public RandomAttribute(int min, int max, int count)
{
_source = new IntDataSource(min, max, count);
}
/// <summary>
/// Construct a set of unsigned ints within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(uint min, uint max, int count)
{
_source = new UIntDataSource(min, max, count);
}
/// <summary>
/// Construct a set of longs within a specified range
/// </summary>
public RandomAttribute(long min, long max, int count)
{
_source = new LongDataSource(min, max, count);
}
/// <summary>
/// Construct a set of unsigned longs within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(ulong min, ulong max, int count)
{
_source = new ULongDataSource(min, max, count);
}
/// <summary>
/// Construct a set of shorts within a specified range
/// </summary>
public RandomAttribute(short min, short max, int count)
{
_source = new ShortDataSource(min, max, count);
}
/// <summary>
/// Construct a set of unsigned shorts within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(ushort min, ushort max, int count)
{
_source = new UShortDataSource(min, max, count);
}
/// <summary>
/// Construct a set of doubles within a specified range
/// </summary>
public RandomAttribute(double min, double max, int count)
{
_source = new DoubleDataSource(min, max, count);
}
/// <summary>
/// Construct a set of floats within a specified range
/// </summary>
public RandomAttribute(float min, float max, int count)
{
_source = new FloatDataSource(min, max, count);
}
/// <summary>
/// Construct a set of bytes within a specified range
/// </summary>
public RandomAttribute(byte min, byte max, int count)
{
_source = new ByteDataSource(min, max, count);
}
/// <summary>
/// Construct a set of sbytes within a specified range
/// </summary>
[CLSCompliant(false)]
public RandomAttribute(sbyte min, sbyte max, int count)
{
_source = new SByteDataSource(min, max, count);
}
#endregion
#region IParameterDataSource Interface
/// <summary>
/// Get the collection of _values to be used as arguments.
/// </summary>
public IEnumerable GetData(IParameterInfo parameter)
{
// Since a separate Randomizer is used for each parameter,
// we can't fill in the data in the constructor of the
// attribute. Only now, when GetData is called, do we have
// sufficient information to create the values in a
// repeatable manner.
Type parmType = parameter.ParameterType;
if (_source == null)
{
if (parmType == typeof(int))
_source = new IntDataSource(_count);
else if (parmType == typeof(uint))
_source = new UIntDataSource(_count);
else if (parmType == typeof(long))
_source = new LongDataSource(_count);
else if (parmType == typeof(ulong))
_source = new ULongDataSource(_count);
else if (parmType == typeof(short))
_source = new ShortDataSource(_count);
else if (parmType == typeof(ushort))
_source = new UShortDataSource(_count);
else if (parmType == typeof(double))
_source = new DoubleDataSource(_count);
else if (parmType == typeof(float))
_source = new FloatDataSource(_count);
else if (parmType == typeof(byte))
_source = new ByteDataSource(_count);
else if (parmType == typeof(sbyte))
_source = new SByteDataSource(_count);
else if (parmType == typeof(decimal))
_source = new DecimalDataSource(_count);
else if (parmType.IsEnum)
_source = new EnumDataSource(_count);
else // Default
_source = new IntDataSource(_count);
}
else if (_source.DataType != parmType && WeConvert(_source.DataType, parmType))
{
_source = new RandomDataConverter(_source);
}
return _source.GetData(parameter);
//// Copy the random _values into the data array
//// and call the base class which may need to
//// convert them to another type.
//this.data = new object[values.Count];
//for (int i = 0; i < values.Count; i++)
// this.data[i] = values[i];
//return base.GetData(parameter);
}
private bool WeConvert(Type sourceType, Type targetType)
{
if (targetType == typeof(short) || targetType == typeof(ushort) || targetType == typeof(byte) || targetType == typeof(sbyte))
return sourceType == typeof(int);
if (targetType == typeof(decimal))
return sourceType == typeof(int) || sourceType == typeof(double);
return false;
}
#endregion
#region Nested DataSource Classes
#region RandomDataSource
abstract class RandomDataSource : IParameterDataSource
{
public Type DataType { get; protected set; }
public abstract IEnumerable GetData(IParameterInfo parameter);
}
abstract class RandomDataSource<T> : RandomDataSource
{
private T _min;
private T _max;
private int _count;
private bool _inRange;
protected Randomizer _randomizer;
protected RandomDataSource(int count)
{
_count = count;
_inRange = false;
DataType = typeof(T);
}
protected RandomDataSource(T min, T max, int count)
{
_min = min;
_max = max;
_count = count;
_inRange = true;
DataType = typeof(T);
}
public override IEnumerable GetData(IParameterInfo parameter)
{
//Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter");
_randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo);
for (int i = 0; i < _count; i++)
yield return _inRange
? GetNext(_min, _max)
: GetNext();
}
protected abstract T GetNext();
protected abstract T GetNext(T min, T max);
}
#endregion
#region RandomDataConverter
class RandomDataConverter : RandomDataSource
{
IParameterDataSource _source;
public RandomDataConverter(IParameterDataSource source)
{
_source = source;
}
public override IEnumerable GetData(IParameterInfo parameter)
{
Type parmType = parameter.ParameterType;
foreach (object obj in _source.GetData(parameter))
{
if (obj is int)
{
int ival = (int)obj; // unbox first
if (parmType == typeof(short))
yield return (short)ival;
else if (parmType == typeof(ushort))
yield return (ushort)ival;
else if (parmType == typeof(byte))
yield return (byte)ival;
else if (parmType == typeof(sbyte))
yield return (sbyte)ival;
else if (parmType == typeof(decimal))
yield return (decimal)ival;
}
else if (obj is double)
{
double d = (double)obj; // unbox first
if (parmType == typeof(decimal))
yield return (decimal)d;
}
}
}
}
#endregion
#region IntDataSource
class IntDataSource : RandomDataSource<int>
{
public IntDataSource(int count) : base(count) { }
public IntDataSource(int min, int max, int count) : base(min, max, count) { }
protected override int GetNext()
{
return _randomizer.Next();
}
protected override int GetNext(int min, int max)
{
return _randomizer.Next(min, max);
}
}
#endregion
#region UIntDataSource
class UIntDataSource : RandomDataSource<uint>
{
public UIntDataSource(int count) : base(count) { }
public UIntDataSource(uint min, uint max, int count) : base(min, max, count) { }
protected override uint GetNext()
{
return _randomizer.NextUInt();
}
protected override uint GetNext(uint min, uint max)
{
return _randomizer.NextUInt(min, max);
}
}
#endregion
#region LongDataSource
class LongDataSource : RandomDataSource<long>
{
public LongDataSource(int count) : base(count) { }
public LongDataSource(long min, long max, int count) : base(min, max, count) { }
protected override long GetNext()
{
return _randomizer.NextLong();
}
protected override long GetNext(long min, long max)
{
return _randomizer.NextLong(min, max);
}
}
#endregion
#region ULongDataSource
class ULongDataSource : RandomDataSource<ulong>
{
public ULongDataSource(int count) : base(count) { }
public ULongDataSource(ulong min, ulong max, int count) : base(min, max, count) { }
protected override ulong GetNext()
{
return _randomizer.NextULong();
}
protected override ulong GetNext(ulong min, ulong max)
{
return _randomizer.NextULong(min, max);
}
}
#endregion
#region ShortDataSource
class ShortDataSource : RandomDataSource<short>
{
public ShortDataSource(int count) : base(count) { }
public ShortDataSource(short min, short max, int count) : base(min, max, count) { }
protected override short GetNext()
{
return _randomizer.NextShort();
}
protected override short GetNext(short min, short max)
{
return _randomizer.NextShort(min, max);
}
}
#endregion
#region UShortDataSource
class UShortDataSource : RandomDataSource<ushort>
{
public UShortDataSource(int count) : base(count) { }
public UShortDataSource(ushort min, ushort max, int count) : base(min, max, count) { }
protected override ushort GetNext()
{
return _randomizer.NextUShort();
}
protected override ushort GetNext(ushort min, ushort max)
{
return _randomizer.NextUShort(min, max);
}
}
#endregion
#region DoubleDataSource
class DoubleDataSource : RandomDataSource<double>
{
public DoubleDataSource(int count) : base(count) { }
public DoubleDataSource(double min, double max, int count) : base(min, max, count) { }
protected override double GetNext()
{
return _randomizer.NextDouble();
}
protected override double GetNext(double min, double max)
{
return _randomizer.NextDouble(min, max);
}
}
#endregion
#region FloatDataSource
class FloatDataSource : RandomDataSource<float>
{
public FloatDataSource(int count) : base(count) { }
public FloatDataSource(float min, float max, int count) : base(min, max, count) { }
protected override float GetNext()
{
return _randomizer.NextFloat();
}
protected override float GetNext(float min, float max)
{
return _randomizer.NextFloat(min, max);
}
}
#endregion
#region ByteDataSource
class ByteDataSource : RandomDataSource<byte>
{
public ByteDataSource(int count) : base(count) { }
public ByteDataSource(byte min, byte max, int count) : base(min, max, count) { }
protected override byte GetNext()
{
return _randomizer.NextByte();
}
protected override byte GetNext(byte min, byte max)
{
return _randomizer.NextByte(min, max);
}
}
#endregion
#region SByteDataSource
class SByteDataSource : RandomDataSource<sbyte>
{
public SByteDataSource(int count) : base(count) { }
public SByteDataSource(sbyte min, sbyte max, int count) : base(min, max, count) { }
protected override sbyte GetNext()
{
return _randomizer.NextSByte();
}
protected override sbyte GetNext(sbyte min, sbyte max)
{
return _randomizer.NextSByte(min, max);
}
}
#endregion
#region EnumDataSource
class EnumDataSource : RandomDataSource
{
private int _count;
public EnumDataSource(int count)
{
_count = count;
DataType = typeof(Enum);
}
public override IEnumerable GetData(IParameterInfo parameter)
{
Guard.ArgumentValid(parameter.ParameterType.IsEnum, "EnumDataSource requires an enum parameter", "parameter");
Randomizer randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo);
DataType = parameter.ParameterType;
for (int i = 0; i < _count; i++ )
yield return randomizer.NextEnum(parameter.ParameterType);
}
}
#endregion
#region DecimalDataSource
// Currently, Randomizer doesn't implement methods for decimal
// so we use random Ulongs and convert them. This doesn't cover
// the full range of decimal, so it's temporary.
class DecimalDataSource : RandomDataSource<decimal>
{
public DecimalDataSource(int count) : base(count) { }
public DecimalDataSource(decimal min, decimal max, int count) : base(min, max, count) { }
protected override decimal GetNext()
{
return _randomizer.NextDecimal();
}
protected override decimal GetNext(decimal min, decimal max)
{
return _randomizer.NextDecimal(min, max);
}
}
#endregion
#endregion
}
}
| |
using dotless.Core.Parser.Infrastructure;
using dotless.Test.Plugins;
namespace dotless.Test.Specs
{
using NUnit.Framework;
using dotless.Core.Exceptions;
using System.Text.RegularExpressions;
public class CommentsFixture : SpecFixtureBase
{
[Test]
public void CommentHeader()
{
var input =
@"
/******************\
* *
* Comment Header *
* *
\******************/
";
AssertLessUnchanged(input);
}
[Test]
public void MultilineComment()
{
var input =
@"
/*
Comment
*/
";
AssertLessUnchanged(input);
}
[Test]
public void MultilineComment2()
{
var input =
@"
/*
* Comment Test
*
* - dotless (http://dotlesscss.com)
*
*/
";
AssertLessUnchanged(input);
}
[Test]
public void LineCommentGetsRemoved()
{
var input = "////////////////";
var expected = "";
AssertLess(input, expected);
}
[Test]
public void ColorInsideComments()
{
var input =
@"
/* Colors
* ------
* #EDF8FC (background blue)
* #166C89 (darkest blue)
*
* Text:
* #333 (standard text)
* #1F9EC9 (standard link)
*
*/
";
AssertLessUnchanged(input);
}
[Test]
public void CommentInsideAComment()
{
var input =
@"
/*
* Comment Test
*
* // A comment within a comment!
*
*/
";
AssertLessUnchanged(input);
}
[Test]
public void VariablesInsideComments()
{
var input =
@"
/* @group Variables
------------------- */
";
AssertLessUnchanged(input);
}
[Test]
public void BlockCommentAfterSelector()
{
var input =
@"
#comments /* boo */ {
color: red;
}
";
var expected = @"
#comments/* boo */ {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void EmptyComment()
{
var input =
@"
#comments {
border: solid black;
/**/
color: red;
}
";
var expected =
@"
#comments {
border: solid black;
/**/
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterPropertyMissingSemiColon()
{
var input = @"
#comments {
border: solid black;
color: red /* A C-style comment */
}
";
var expected = @"
#comments {
border: solid black;
color: red/* A C-style comment */;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterPropertyMissingSemiColonDimension()
{
var input = @"
#comments {
border: 1px /* A C-style comment */
}
";
var expected = @"
#comments {
border: 1px/* A C-style comment */;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterPropertyMissingSemiColonColor()
{
var input = @"
#comments {
color: #ff1000 /* A C-style comment */
}
";
var expected = @"
#comments {
color: #ff1000/* A C-style comment */;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterMixinCallMissingSemiColon()
{
var input = @"
.cla (@a) {
color: @a;
}
#comments {
border: solid black;
.cla(red) /* A C-style comment */
}
";
var expected = @"
#comments {
border: solid black;
color: red;
/* A C-style comment */
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentAfterProperty()
{
var input =
@"
#comments {
border: solid black;
color: red; /* A C-style comment */
padding: 0;
}
";
var expected =
@"
#comments {
border: solid black;
color: red;
/* A C-style comment */
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void LineCommentAfterProperty()
{
var input =
@"
#comments {
border: solid black;
color: red; // A little comment
padding: 0;
}
";
var expected = @"
#comments {
border: solid black;
color: red;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommentBeforeProperty()
{
var input =
@"
#comments {
border: solid black;
/* comment */ color: red;
padding: 0;
}
";
var expected = @"
#comments {
border: solid black;
/* comment */
color: red;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void LineCommentAfterALineComment()
{
var input =
@"
#comments {
border: solid black;
// comment //
color: red;
padding: 0;
}
";
var expected = @"
#comments {
border: solid black;
color: red;
padding: 0;
}
";
AssertLess(input, expected);
}
[Test]
public void LineCommentAfterBlock()
{
var input =
@"
#comments /* boo */ {
color: red;
} // comment
";
var expected = @"
#comments/* boo */ {
color: red;
}
";
AssertLess(input, expected);
}
[Test]
public void BlockCommented1()
{
var input =
@"
/* commented out
#more-comments {
color: grey;
}
*/
";
AssertLessUnchanged(input);
}
[Test]
public void BlockCommented2()
{
var input =
@"
/*
#signup form h3.title {
background:transparent url(../img/ui/signup.png) no-repeat 50px top;
height:100px;
}
*/
";
AssertLessUnchanged(input);
}
[Test]
public void BlockCommented3()
{
var input =
@"
#more-comments {
quotes: ""/*"" ""*/"";
}
";
AssertLessUnchanged(input);
}
[Test]
public void CommentOnLastLine()
{
var input =
@"
#last { color: blue }
//
";
var expected = @"
#last {
color: blue;
}
";
AssertLess(input, expected);
}
[Test]
[ExpectedException(typeof(ParserException))]
public void CheckCommentsAreNotAcceptedAsASelector()
{
// Note: https://github.com/dotless/dotless/issues/31
var input = @"/* COMMENT *//* COMMENT */, /* COMMENT */,/* COMMENT */ .clb /* COMMENT */ {background-image: url(pickture.asp);}";
AssertLessUnchanged(input);
}
[Test]
public void CheckCommentsAreAcceptedBetweenSelectors()
{
// Note: https://github.com/dotless/dotless/issues/31
var input = @"/* COMMENT */body/* COMMENT */,/* COMMENT */ .clb /* COMMENT */ {background-image: url(pickture.asp);}";
var expected = @"/* COMMENT */
body/* COMMENT */,
/* COMMENT */ .clb/* COMMENT */ {
background-image: url(pickture.asp);
}";
AssertLess(input, expected);
}
[Test]
public void CheckCommentsAreAcceptedWhereWhitespaceIsAllowed()
{
// Note: https://github.com/dotless/dotless/issues/31
var input = @"/* COMMENT */body/* COMMENT */, /* COMMENT */.cls/* COMMENT */ .cla,/* COMMENT */ .clb /* COMMENT */ {background-image: url(pickture.asp);}";
var expected = @"/* COMMENT */
body/* COMMENT */,
/* COMMENT */ .cls/* COMMENT */ .cla,
/* COMMENT */ .clb/* COMMENT */ {
background-image: url(pickture.asp);
}";
AssertLess(input, expected);
}
[Test]
public void CommentCSSHackException1Accepted()
{
var input = @"/*\*/.cls {background-image: url(picture.asp);} /**/";
var expected = @"/*\*/
.cls {
background-image: url(picture.asp);
}
/**/";
AssertLess(input, expected);
}
[Test]
public void CommentCSSHackException2Accepted()
{
var input = @"/*\*/
/*/
.cls {background-image: url(picture.asp);} /**/";
AssertLessUnchanged(input);
}
[Test]
public void CommentBeforeMixinDefinition()
{
var input = @"/* COMMENT */.clb(@a) { font-size: @a; }
.cla { .clb(10); }";
var expected = @"/* COMMENT */
.cla {
font-size: 10;
}";
AssertLess(input, expected);
}
[Test]
public void CommentBeforeAndAfterMixinDefinition()
{
var input = @"/* COMMENT */.clb(/* COMMENT */@a/* COMMENT */,/* COMMENT */@b)/* COMMENT */ { font-size: @a; }
.cla { .clb(10, 10); }";
var expected = @"/* COMMENT */
.cla {
font-size: 10;
}";
AssertLess(input, expected);
}
[Test]
public void CommentBeforeAndAfterMixinDefinitionWithDefaultArgs()
{
var input = @"/* COMMENT */.clb(/* COMMENT */@a/* COMMENT */:/* COMMENT */10/* COMMENT */,/* COMMENT */@b/* COMMENT */:/* COMMENT */7px/* COMMENT */)/* COMMENT */ { font-size: @a; }
.cla { .clb(10, 10); }";
var expected = @"/* COMMENT */
.cla {
font-size: 10;
}";
AssertLess(input, expected);
}
[Test]
public void CommentBeforeVariableRuleKept()
{
var input = @"/* COMMENT */@a : 10px;/* COMMENT */
.cla { font-size: @a; }";
var expected = @"/* COMMENT */
/* COMMENT */
.cla {
font-size: 10px;
}";
AssertLess(input, expected);
}
[Test]
[Ignore]
public void CommentsInVariableRuleAccepted()
{
var input = @"/* COM1 */@a /* COM2 */: /* COM3 */10px/* COM4 */;/* COM5 */
.cla { font-size: @a; }";
var expected = @"/* COM1 */
/* COM5 */
.cla {
font-size: /* COM3 */10px/* COM4 */;
}";
AssertLess(input, expected);
}
[Test]
public void CommentsInDirective1()
{
var input = @"/* COMMENT */@charset /* COMMENT */""utf-8""/* COMMENT */;";
var expected = @"/* COMMENT */
@charset /* COMMENT */""utf-8""/* COMMENT */;";
AssertLess(input, expected);
}
[Test]
public void CommentsInDirective2()
{
var input = @"@media/*COM1*/ print /*COM2*/ {/*COM3*/
font-size: 3em;
}/*COM 6*/
@font-face /*COM4*/ { /*COM5*/
font-size: 3em;
}/*COM 6*/
";
var expected = @"@media /*COM1*/print/*COM2*/ {
/*COM3*/
font-size: 3em;
}
/*COM 6*/
@font-face/*COM4*/ {
/*COM5*/
font-size: 3em;
}
/*COM 6*/";
AssertLess(input, expected);
}
[Test]
public void CommentsInDirective3()
{
var input = @"@media/*COM1*/ print {
font-size: 3em;
}
";
var expected = @"@media /*COM1*/print {
font-size: 3em;
}";
AssertLess(input, expected);
}
[Test]
public void CommentsInSelectorPsuedos()
{
var input = @"p/*CO1*/:not/*CO1*/([class*=""lead""])/*CO2*/{ font-size: 10px; }";
var expected = @"p/*CO1*/:not/*CO1*/([class*=""lead""])/*CO2*/ {
font-size: 10px;
}";
AssertLess(input, expected);
}
[Test, Ignore("Unsupported - Requires an attribute node")]
public void CommentsInSelectorAttributes()
{
var input = @"p/*CO2*/[/*CO3*/type=""checkbox""/*CO5*/]/*CO6*/[/*CO7*/type/*CO8*/] { font-size: 10px; }";
var expected = @"p/*CO2*/[/*CO3*/type=""checkbox""/*CO5*/]/*CO6*/[/*CO7*/type/*CO8*/] {
font-size: 10px;
}";
AssertLess(input, expected);
}
[Test]
public void CommentsInUrl()
{
var input = @"url(/*A*/""test""/*R*/)/*S*/";
var expected = @"url(/*A*/""test""/*R*/)/*S*/";
AssertExpression(expected, input);
}
private void AssertExpressionWithAndWithoutComments(string expected, string input)
{
Regex removeComments = new Regex(@"(//[^\n]*|(/\*(.|[\r\n])*?\*/))");
string inputNC = removeComments.Replace(input, "");
string expectedNC = removeComments.Replace(expected, "");
AssertExpression(expectedNC, inputNC);
AssertExpression(expected, input);
}
[Test]
public void CommentsInExpression1Paren()
{
// drops some comments, but this is better than throwing an exception
var input = @"/*A*/(/*B*/12/*C*/+/*D*/(/*E*/7/*F*/-/*G*/(/*H*/8px/*I*/*/*J*/(/*K*/9/*L*/-/*M*/3/*N*/)/*O*/)/*P*/)/*Q*/)/*R*/";
var expected = @"/*A*/-29px/*B*//*C*//*D*//*E*//*F*//*G*//*H*//*I*//*J*//*K*//*L*//*M*//*N*//*O*//*P*//*Q*//*R*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpression1NoParen()
{
var input = @"/*A*/12/*B*/+/*C*/7/*D*/-/*E*/8px/*F*/*/*G*/9/*H*/-/*I*/3/*J*/";
var expected = @"/*A*/-56px/*B*//*C*//*D*//*E*//*F*//*G*//*H*//*I*//*J*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpressionMultiplication()
{
var input = @"8/*A*/*/*B*/1";
var expected = @"8/*A*//*B*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpression2()
{
var input = @"/*A*/12px/*B*/ /*C*/4px/*D*/";
var expected = @"/*A*/12px/*B*//*C*/ 4px/*D*/";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void CommentsInExpression3()
{
var input = @"/*A*/12px/*B*/ !important";
var expected = @"/*A*/12px/*B*/ !important";
AssertExpressionWithAndWithoutComments(expected, input);
}
[Test]
public void ImportantCommentIsLeftInOutputWithMinificationEnabled()
{
var input = @"/*! don't remove me */";
DefaultEnv = () => {
var env = new Env();
env.AddPlugin(new PassThroughAfterPlugin());
env.AddPlugin(new PassThroughBeforePlugin());
env.KeepFirstSpecialComment = true;
env.Compress = true;
return env;
};
AssertLessUnchanged(input, DefaultParser());
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlBatchCommand.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
internal sealed class SqlCommandSet {
private const string SqlIdentifierPattern = "^@[\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}_@#][\\p{Lo}\\p{Lu}\\p{Ll}\\p{Lm}\\p{Nd}\uff3f_@#\\$]*$";
private static readonly Regex SqlIdentifierParser = new Regex(SqlIdentifierPattern, RegexOptions.ExplicitCapture|RegexOptions.Singleline);
private List<LocalCommand> _commandList = new List<LocalCommand>();
private SqlCommand _batchCommand;
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
private sealed class LocalCommand {
internal readonly string CommandText;
internal readonly SqlParameterCollection Parameters;
internal readonly int ReturnParameterIndex;
internal readonly CommandType CmdType;
internal LocalCommand(string commandText, SqlParameterCollection parameters, int returnParameterIndex, CommandType cmdType) {
Debug.Assert(0 <= commandText.Length, "no text");
this.CommandText = commandText;
this.Parameters = parameters;
this.ReturnParameterIndex = returnParameterIndex;
this.CmdType = cmdType;
}
}
internal SqlCommandSet() : base() {
_batchCommand = new SqlCommand();
}
private SqlCommand BatchCommand {
get {
SqlCommand command = _batchCommand;
if (null == command) {
throw ADP.ObjectDisposed(this);
}
return command;
}
}
internal int CommandCount {
get {
return CommandList.Count;
}
}
private List<LocalCommand> CommandList {
get {
List<LocalCommand> commandList = _commandList;
if (null == commandList) {
throw ADP.ObjectDisposed(this);
}
return commandList;
}
}
internal int CommandTimeout {
/*get {
return BatchCommand.CommandTimeout;
}*/
set {
BatchCommand.CommandTimeout = value;
}
}
internal SqlConnection Connection {
get {
return BatchCommand.Connection;
}
set {
BatchCommand.Connection = value;
}
}
internal SqlTransaction Transaction {
/*get {
return BatchCommand.Transaction;
}*/
set {
BatchCommand.Transaction = value;
}
}
internal int ObjectID {
get {
return _objectID;
}
}
internal void Append(SqlCommand command) {
ADP.CheckArgumentNull(command, "command");
Bid.Trace("<sc.SqlCommandSet.Append|API> %d#, command=%d, parameterCount=%d\n", ObjectID, command.ObjectID, command.Parameters.Count);
string cmdText = command.CommandText;
if (ADP.IsEmpty(cmdText)) {
throw ADP.CommandTextRequired(ADP.Append);
}
CommandType commandType = command.CommandType;
switch(commandType) {
case CommandType.Text:
case CommandType.StoredProcedure:
break;
case CommandType.TableDirect:
Debug.Assert(false, "command.CommandType");
throw System.Data.SqlClient.SQL.NotSupportedCommandType(commandType);
default:
Debug.Assert(false, "command.CommandType");
throw ADP.InvalidCommandType(commandType);
}
SqlParameterCollection parameters = null;
SqlParameterCollection collection = command.Parameters;
if (0 < collection.Count) {
parameters = new SqlParameterCollection();
// clone parameters so they aren't destroyed
for(int i = 0; i < collection.Count; ++i) {
SqlParameter p = new SqlParameter();
collection[i].CopyTo(p);
parameters.Add(p);
// SQL Injection awarene
if (!SqlIdentifierParser.IsMatch(p.ParameterName)) {
throw ADP.BadParameterName(p.ParameterName);
}
}
foreach(SqlParameter p in parameters) {
// deep clone the parameter value if byte[] or char[]
object obj = p.Value;
byte[] byteValues = (obj as byte[]);
if (null != byteValues) {
int offset = p.Offset;
int size = p.Size;
int countOfBytes = byteValues.Length - offset;
if ((0 != size) && (size < countOfBytes)) {
countOfBytes = size;
}
byte[] copy = new byte[Math.Max(countOfBytes, 0)];
Buffer.BlockCopy(byteValues, offset, copy, 0, copy.Length);
p.Offset = 0;
p.Value = copy;
}
else {
char[] charValues = (obj as char[]);
if (null != charValues) {
int offset = p.Offset;
int size = p.Size;
int countOfChars = charValues.Length - offset;
if ((0 != size) && (size < countOfChars)) {
countOfChars = size;
}
char[] copy = new char[Math.Max(countOfChars, 0)];
Buffer.BlockCopy(charValues, offset, copy, 0, copy.Length*2);
p.Offset = 0;
p.Value = copy;
}
else {
ICloneable cloneable = (obj as ICloneable);
if (null != cloneable) {
p.Value = cloneable.Clone();
}
}
}
}
}
int returnParameterIndex = -1;
if (null != parameters) {
for(int i = 0; i < parameters.Count; ++i) {
if (ParameterDirection.ReturnValue == parameters[i].Direction) {
returnParameterIndex = i;
break;
}
}
}
LocalCommand cmd = new LocalCommand(cmdText, parameters, returnParameterIndex, command.CommandType);
CommandList.Add(cmd);
}
internal static void BuildStoredProcedureName(StringBuilder builder, string part) {
if ((null != part) && (0 < part.Length)) {
if ('[' == part[0]) {
int count = 0;
foreach(char c in part) {
if (']' == c) {
count++;
}
}
if (1 == (count%2)) {
builder.Append(part);
return;
}
}
// the part is not escaped, escape it now
SqlServerEscapeHelper.EscapeIdentifier(builder, part);
}
}
internal void Clear() {
Bid.Trace("<sc.SqlCommandSet.Clear|API> %d#\n", ObjectID);
DbCommand batchCommand = BatchCommand;
if (null != batchCommand) {
batchCommand.Parameters.Clear();
batchCommand.CommandText = null;
}
List<LocalCommand> commandList = _commandList;
if (null != commandList) {
commandList.Clear();
}
}
internal void Dispose() {
Bid.Trace("<sc.SqlCommandSet.Dispose|API> %d#\n", ObjectID);
SqlCommand command = _batchCommand;
_commandList = null;
_batchCommand = null;
if (null != command) {
command.Dispose();
}
}
internal int ExecuteNonQuery() {
SqlConnection.ExecutePermission.Demand();
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<sc.SqlCommandSet.ExecuteNonQuery|API> %d#", ObjectID);
try {
if (Connection.IsContextConnection) {
throw SQL.BatchedUpdatesNotAvailableOnContextConnection();
}
ValidateCommandBehavior(ADP.ExecuteNonQuery, CommandBehavior.Default);
BatchCommand.BatchRPCMode = true;
BatchCommand.ClearBatchCommand();
BatchCommand.Parameters.Clear();
for (int ii = 0 ; ii < _commandList.Count; ii++) {
LocalCommand cmd = _commandList[ii];
BatchCommand.AddBatchCommand(cmd.CommandText, cmd.Parameters, cmd.CmdType);
}
return BatchCommand.ExecuteBatchRPCCommand();
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
internal SqlParameter GetParameter(int commandIndex, int parameterIndex) {
return CommandList[commandIndex].Parameters[parameterIndex];
}
internal bool GetBatchedAffected(int commandIdentifier, out int recordsAffected, out Exception error) {
error = BatchCommand.GetErrors(commandIdentifier);
int? affected = BatchCommand.GetRecordsAffected(commandIdentifier);
recordsAffected = affected.GetValueOrDefault();
return affected.HasValue;
}
internal int GetParameterCount(int commandIndex) {
return CommandList[commandIndex].Parameters.Count;
}
private void ValidateCommandBehavior(string method, CommandBehavior behavior) {
if (0 != (behavior & ~(CommandBehavior.SequentialAccess|CommandBehavior.CloseConnection))) {
ADP.ValidateCommandBehavior(behavior);
throw ADP.NotSupportedCommandBehavior(behavior & ~(CommandBehavior.SequentialAccess|CommandBehavior.CloseConnection), method);
}
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Payment Gateway Log
///<para>SObject Name: PaymentGatewayLog</para>
///<para>Custom Object: False</para>
///</summary>
public class SfPaymentGatewayLog : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "PaymentGatewayLog"; }
}
///<summary>
/// Payment Gateway Log ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// PaymentGatewayLogNumber
/// <para>Name: PaymentGatewayLogNumber</para>
/// <para>SF Type: string</para>
/// <para>AutoNumber field</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "paymentGatewayLogNumber")]
[Updateable(false), Createable(false)]
public string PaymentGatewayLogNumber { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// ReferencedEntity ID
/// <para>Name: ReferencedEntityId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "referencedEntityId")]
public string ReferencedEntityId { get; set; }
///<summary>
/// Interaction Type
/// <para>Name: InteractionType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "interactionType")]
[Updateable(false), Createable(true)]
public string InteractionType { get; set; }
///<summary>
/// SalesforceReferenceNumber
/// <para>Name: SfRefNumber</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sfRefNumber")]
public string SfRefNumber { get; set; }
///<summary>
/// Status
/// <para>Name: InteractionStatus</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "interactionStatus")]
public string InteractionStatus { get; set; }
///<summary>
/// GatewayAuthCode
/// <para>Name: GatewayAuthCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayAuthCode")]
public string GatewayAuthCode { get; set; }
///<summary>
/// GatewayReferenceNumber
/// <para>Name: GatewayRefNumber</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayRefNumber")]
public string GatewayRefNumber { get; set; }
///<summary>
/// SalesforceResultCode
/// <para>Name: SfResultCode</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sfResultCode")]
public string SfResultCode { get; set; }
///<summary>
/// GatewayResultCode
/// <para>Name: GatewayResultCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayResultCode")]
public string GatewayResultCode { get; set; }
///<summary>
/// GatewayResultCode
/// <para>Name: GatewayResultCodeDescription</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayResultCodeDescription")]
public string GatewayResultCodeDescription { get; set; }
///<summary>
/// GatewayDate
/// <para>Name: GatewayDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayDate")]
public DateTimeOffset? GatewayDate { get; set; }
///<summary>
/// Gateway Message
/// <para>Name: GatewayMessage</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayMessage")]
public string GatewayMessage { get; set; }
///<summary>
/// GatewayAvsCode
/// <para>Name: GatewayAvsCode</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "gatewayAvsCode")]
public string GatewayAvsCode { get; set; }
///<summary>
/// Payment Gateway ID
/// <para>Name: PaymentGatewayId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "paymentGatewayId")]
public string PaymentGatewayId { get; set; }
///<summary>
/// ReferenceTo: PaymentGateway
/// <para>RelationshipName: PaymentGateway</para>
///</summary>
[JsonProperty(PropertyName = "paymentGateway")]
[Updateable(false), Createable(false)]
public SfPaymentGateway PaymentGateway { get; set; }
///<summary>
/// IsNotification
/// <para>Name: IsNotification</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "isNotification")]
public string IsNotification { get; set; }
///<summary>
/// Request
/// <para>Name: Request</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "request")]
public string Request { get; set; }
///<summary>
/// Response
/// <para>Name: Response</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "response")]
public string Response { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
/// <summary>
/// System.Byte.ToString(System.String,System.IFormatProvider)
/// </summary>
public class ByteToString4
{
public static int Main(string[] args)
{
ByteToString4 toString4 = new ByteToString4();
TestLibrary.TestFramework.BeginTestCase("Testing System.Byte.ToString(System.String,System.IFormatProvider)...");
if (toString4.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify NumberGroupSeparator of provider is _ and format string is N");
try
{
Byte myByte = 128;
CultureInfo culture = new CultureInfo("");
NumberFormatInfo numInfo = culture.NumberFormat;
numInfo.NumberGroupSizes = new int[] { 1 };
numInfo.NumberGroupSeparator = "_";
numInfo.NumberDecimalDigits = 0;
string myByteString = myByte.ToString("N",numInfo);
if (myByteString != "1_2_8")
{
TestLibrary.TestFramework.LogError("001", "The byte string is wrong!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify CurrencySymbol of provider is $ and format string is C...");
try
{
Byte myByte = 128;
CultureInfo culture = new CultureInfo("");
NumberFormatInfo numInfo = culture.NumberFormat;
numInfo.CurrencySymbol = "$";
numInfo.CurrencyDecimalDigits = 0;
string myByteString = myByte.ToString("C",numInfo);
if (myByteString != "$128")
{
TestLibrary.TestFramework.LogError("003", "The currency string is wrong!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify X format convert hex string...");
try
{
Byte myByte = 128;
CultureInfo culture = new CultureInfo("");
NumberFormatInfo numInfo = culture.NumberFormat;
numInfo.PositiveSign = "plus";
string myByteString = myByte.ToString("X",numInfo);
if (myByteString != "80")
{
TestLibrary.TestFramework.LogError("005", "The hex string is wrong!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify D format convert decimal string...");
try
{
Byte myByte = 128;
CultureInfo culture = new CultureInfo("");
NumberFormatInfo numInfo = culture.NumberFormat;
numInfo.PositiveSign = "plus";
string myByteString = myByte.ToString("D", numInfo);
if (myByteString != "128")
{
TestLibrary.TestFramework.LogError("007", "The decimal string is wrong!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify E format convert exponential format string...");
try
{
Byte myByte = 128;
CultureInfo culture = new CultureInfo("");
NumberFormatInfo numInfo = culture.NumberFormat;
numInfo.PositiveSign = "plus";
string myByteString = myByte.ToString("E", numInfo);
if (myByteString != "1.280000Eplus002")
{
TestLibrary.TestFramework.LogError("009", "The exponential string is wrong!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify F format convert Fixed-point string...");
try
{
Byte myByte = 128;
CultureInfo culture = new CultureInfo("");
NumberFormatInfo numInfo = culture.NumberFormat;
numInfo.PositiveSign = "plus";
string myByteString = myByte.ToString("F", numInfo);
if (myByteString != "128.00")
{
TestLibrary.TestFramework.LogError("011", "The Fixed-point string is wrong!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class WeakRefTest
{
private const string COMMAND_TEXT_1 = "SELECT EmployeeID, LastName, FirstName, Title, Address, City, Region, PostalCode, Country from Employees";
private const string COMMAND_TEXT_2 = "SELECT LastName from Employees";
private const string COLUMN_NAME_2 = "LastName";
private const string CHANGE_DATABASE_NAME = "master";
private enum ReaderTestType
{
ReaderClose,
ReaderDispose,
ReaderGC,
ConnectionClose,
ReaderGCConnectionClose,
}
private enum ReaderVerificationType
{
ExecuteReader,
ChangeDatabase,
BeginTransaction,
EnlistDistributedTransaction,
}
private enum TransactionTestType
{
TransactionRollback,
TransactionDispose,
TransactionGC,
ConnectionClose,
TransactionGCConnectionClose,
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestReaderNonMars()
{
string connString =
(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
MaxPoolSize = 1
}
).ConnectionString;
TestReaderNonMarsCase("Case 1: ExecuteReader, Close, ExecuteReader.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 2: ExecuteReader, Dispose, ExecuteReader.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 3: ExecuteReader, GC, ExecuteReader.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 4: ExecuteReader, Connection Close, ExecuteReader.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 5: ExecuteReader, GC, Connection Close, ExecuteReader.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 6: ExecuteReader, Close, ChangeDatabase.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 7: ExecuteReader, Dispose, ChangeDatabase.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 8: ExecuteReader, GC, ChangeDatabase.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 9: ExecuteReader, Connection Close, ChangeDatabase.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 10: ExecuteReader, GC, Connection Close, ChangeDatabase.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 11: ExecuteReader, Close, BeginTransaction.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 12: ExecuteReader, Dispose, BeginTransaction.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 13: ExecuteReader, GC, BeginTransaction.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 14: ExecuteReader, Connection Close, BeginTransaction.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 15: ExecuteReader, GC, Connection Close, BeginTransaction.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.BeginTransaction);
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestTransactionSingle()
{
string connString =
(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
MaxPoolSize = 1
}).ConnectionString;
TestTransactionSingleCase("Case 1: BeginTransaction, Rollback.", connString, TransactionTestType.TransactionRollback);
TestTransactionSingleCase("Case 2: BeginTransaction, Dispose.", connString, TransactionTestType.TransactionDispose);
TestTransactionSingleCase("Case 3: BeginTransaction, GC.", connString, TransactionTestType.TransactionGC);
TestTransactionSingleCase("Case 4: BeginTransaction, Connection Close.", connString, TransactionTestType.ConnectionClose);
TestTransactionSingleCase("Case 5: BeginTransaction, GC, Connection Close.", connString, TransactionTestType.TransactionGCConnectionClose);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void TestReaderNonMarsCase(string caseName, string connectionString, ReaderTestType testType, ReaderVerificationType verificationType)
{
WeakReference weak = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = COMMAND_TEXT_1;
SqlDataReader gch = null;
if ((testType != ReaderTestType.ReaderGC) && (testType != ReaderTestType.ReaderGCConnectionClose))
gch = cmd.ExecuteReader();
switch (testType)
{
case ReaderTestType.ReaderClose:
gch.Dispose();
break;
case ReaderTestType.ReaderDispose:
gch.Dispose();
break;
case ReaderTestType.ReaderGC:
weak = OpenNullifyReader(cmd);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Reader is still alive!");
break;
case ReaderTestType.ConnectionClose:
GC.SuppressFinalize(gch);
con.Close();
con.Open();
break;
case ReaderTestType.ReaderGCConnectionClose:
weak = OpenNullifyReader(cmd);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Reader is still alive!");
con.Close();
con.Open();
break;
}
switch (verificationType)
{
case ReaderVerificationType.ExecuteReader:
cmd.CommandText = COMMAND_TEXT_2;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
Assert.Equal(rdr.FieldCount, 1);
Assert.Equal(rdr.GetName(0), COLUMN_NAME_2);
}
break;
case ReaderVerificationType.ChangeDatabase:
con.ChangeDatabase(CHANGE_DATABASE_NAME);
Assert.Equal(con.Database, CHANGE_DATABASE_NAME);
break;
case ReaderVerificationType.BeginTransaction:
cmd.Transaction = con.BeginTransaction();
cmd.CommandText = "select @@trancount";
int tranCount = (int)cmd.ExecuteScalar();
Assert.Equal(tranCount, 1);
break;
}
}
}
}
private static WeakReference OpenNullifyReader(SqlCommand cmd)
{
SqlDataReader reader = cmd.ExecuteReader();
WeakReference weak = new WeakReference(reader);
reader = null;
return weak;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void TestTransactionSingleCase(string caseName, string connectionString, TransactionTestType testType)
{
WeakReference weak = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlTransaction gch = null;
if ((testType != TransactionTestType.TransactionGC) && (testType != TransactionTestType.TransactionGCConnectionClose))
gch = con.BeginTransaction();
switch (testType)
{
case TransactionTestType.TransactionRollback:
gch.Rollback();
break;
case TransactionTestType.TransactionDispose:
gch.Dispose();
break;
case TransactionTestType.TransactionGC:
weak = OpenNullifyTransaction(con);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive!");
break;
case TransactionTestType.ConnectionClose:
GC.SuppressFinalize(gch);
con.Close();
con.Open();
break;
case TransactionTestType.TransactionGCConnectionClose:
weak = OpenNullifyTransaction(con);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive!");
con.Close();
con.Open();
break;
}
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select @@trancount";
int tranCount = (int)cmd.ExecuteScalar();
Assert.Equal(tranCount, 0);
}
}
}
private static WeakReference OpenNullifyTransaction(SqlConnection connection)
{
SqlTransaction transaction = connection.BeginTransaction();
WeakReference weak = new WeakReference(transaction);
transaction = null;
return weak;
}
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Text;
using NodaTime.TimeZones;
using NodaTime.Utility;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace NodaTime.TzdbCompiler.Tzdb
{
/// <summary>
/// Contains the parsed information from one "Zone" line of the TZDB zone database.
/// </summary>
/// <remarks>
/// Immutable, thread-safe
/// </remarks>
internal class ZoneLine : IEquatable<ZoneLine?>
{
private static readonly OffsetPattern PercentZPattern = OffsetPattern.CreateWithInvariantCulture("i");
/// <summary>
/// Initializes a new instance of the <see cref="ZoneLine" /> class.
/// </summary>
public ZoneLine(string name, Offset offset, string? rules, string format, int untilYear, ZoneYearOffset untilYearOffset)
{
this.Name = name;
this.StandardOffset = offset;
this.Rules = rules;
this.Format = format;
this.UntilYear = untilYear;
this.UntilYearOffset = untilYearOffset;
}
internal ZoneYearOffset UntilYearOffset { get; }
internal int UntilYear { get; }
/// <summary>
/// Returns the format for generating the label for this time zone. May contain "%s" to
/// be replaced by a daylight savings indicator, or "%z" to be replaced by an offset indicator.
/// </summary>
/// <value>The format string.</value>
internal string Format { get; }
/// <summary>
/// Returns the name of the time zone.
/// </summary>
/// <value>The time zone name.</value>
internal string Name { get; }
/// <summary>
/// Returns the offset to add to UTC for this time zone's standard time.
/// </summary>
/// <value>The offset from UTC.</value>
internal Offset StandardOffset { get; }
/// <summary>
/// The name of the set of rules applicable to this zone line, or
/// null for just standard time, or an offset for a "fixed savings" rule.
/// </summary>
/// <value>The name of the rules to apply for this zone line.</value>
internal string? Rules { get; }
#region IEquatable<Zone> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name = "other" /> parameter;
/// otherwise, false.
/// </returns>
public bool Equals(ZoneLine? other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
var result = Name == other.Name && StandardOffset == other.StandardOffset && Rules == other.Rules && Format == other.Format && UntilYear == other.UntilYear;
if (UntilYear != Int32.MaxValue)
{
result = result && UntilYearOffset.Equals(other.UntilYearOffset);
}
return result;
}
#endregion
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance;
/// otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object? obj) => Equals(obj as ZoneLine);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data
/// structures like a hash table.
/// </returns>
public override int GetHashCode()
{
var hash = HashCodeHelper.Initialize()
.Hash(Name)
.Hash(StandardOffset)
.Hash(Rules)
.Hash(Format)
.Hash(UntilYear);
if (UntilYear != Int32.MaxValue)
{
hash = hash.Hash(UntilYearOffset.GetHashCode());
}
return hash.Value;
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
var builder = new StringBuilder();
builder.Append(Name).Append(" ");
builder.Append(StandardOffset).Append(" ");
builder.Append(ParserHelper.FormatOptional(Rules)).Append(" ");
builder.Append(Format);
if (UntilYear != Int32.MaxValue)
{
builder.Append(" ").Append(UntilYear.ToString("D4", CultureInfo.InvariantCulture)).Append(" ").Append(UntilYearOffset);
}
return builder.ToString();
}
public ZoneRuleSet ResolveRules(IDictionary<string, IList<RuleLine>> allRules)
{
if (Rules is null)
{
var name = FormatName(Offset.Zero, "");
return new ZoneRuleSet(name, StandardOffset, Offset.Zero, UntilYear, UntilYearOffset);
}
if (allRules.TryGetValue(Rules, out IList<RuleLine> ruleSet))
{
var rules = ruleSet.SelectMany(x => x.GetRecurrences(this));
return new ZoneRuleSet(rules.ToList(), StandardOffset, UntilYear, UntilYearOffset);
}
else
{
try
{
// Check if Rules actually just refers to a savings.
var savings = ParserHelper.ParseOffset(Rules);
var name = FormatName(savings, "");
return new ZoneRuleSet(name, StandardOffset, savings, UntilYear, UntilYearOffset);
}
catch (FormatException)
{
throw new ArgumentException(
$"Daylight savings rule name '{Rules}' for zone {Name} is neither a known ruleset nor a fixed offset");
}
}
}
internal string FormatName(Offset savings, string? daylightSavingsIndicator)
{
int index = Format.IndexOf("/", StringComparison.Ordinal);
if (index >= 0)
{
return savings == Offset.Zero ? Format.Substring(0, index) : Format.Substring(index + 1);
}
index = Format.IndexOf("%s", StringComparison.Ordinal);
if (index >= 0)
{
var left = Format.Substring(0, index);
var right = Format.Substring(index + 2);
return left + daylightSavingsIndicator + right;
}
index = Format.IndexOf("%z", StringComparison.Ordinal);
if (index >= 0)
{
var left = Format.Substring(0, index);
var right = Format.Substring(index + 2);
return left + PercentZPattern.Format(StandardOffset + savings) + right;
}
return Format;
}
}
}
| |
using System.Net;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Updating.Relationships;
public sealed class AtomicReplaceToManyRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext;
private readonly OperationsFakers _fakers = new();
public AtomicReplaceToManyRelationshipTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
}
[Fact]
public async Task Can_clear_OneToMany_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Performers = _fakers.Performer.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Performer>();
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationship = "performers"
},
data = Array.Empty<object>()
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Performers.Should().BeEmpty();
List<Performer> performersInDatabase = await dbContext.Performers.ToListAsync();
performersInDatabase.ShouldHaveCount(2);
});
}
[Fact]
public async Task Can_clear_ManyToMany_relationship()
{
// Arrange
Playlist existingPlaylist = _fakers.Playlist.Generate();
existingPlaylist.Tracks = _fakers.MusicTrack.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.Playlists.Add(existingPlaylist);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "playlists",
id = existingPlaylist.StringId,
relationship = "tracks"
},
data = Array.Empty<object>()
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(existingPlaylist.Id);
playlistInDatabase.Tracks.Should().BeEmpty();
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.ShouldHaveCount(2);
});
}
[Fact]
public async Task Can_replace_OneToMany_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Performers = _fakers.Performer.Generate(1);
List<Performer> existingPerformers = _fakers.Performer.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Performer>();
dbContext.MusicTracks.Add(existingTrack);
dbContext.Performers.AddRange(existingPerformers);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationship = "performers"
},
data = new[]
{
new
{
type = "performers",
id = existingPerformers[0].StringId
},
new
{
type = "performers",
id = existingPerformers[1].StringId
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Performers).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Performers.ShouldHaveCount(2);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[0].Id);
trackInDatabase.Performers.Should().ContainSingle(performer => performer.Id == existingPerformers[1].Id);
List<Performer> performersInDatabase = await dbContext.Performers.ToListAsync();
performersInDatabase.ShouldHaveCount(3);
});
}
[Fact]
public async Task Can_replace_ManyToMany_relationship()
{
// Arrange
Playlist existingPlaylist = _fakers.Playlist.Generate();
existingPlaylist.Tracks = _fakers.MusicTrack.Generate(1);
List<MusicTrack> existingTracks = _fakers.MusicTrack.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.Playlists.Add(existingPlaylist);
dbContext.MusicTracks.AddRange(existingTracks);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "playlists",
id = existingPlaylist.StringId,
relationship = "tracks"
},
data = new[]
{
new
{
type = "musicTracks",
id = existingTracks[0].StringId
},
new
{
type = "musicTracks",
id = existingTracks[1].StringId
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Playlist playlistInDatabase = await dbContext.Playlists.Include(playlist => playlist.Tracks).FirstWithIdAsync(existingPlaylist.Id);
playlistInDatabase.Tracks.ShouldHaveCount(2);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[0].Id);
playlistInDatabase.Tracks.Should().ContainSingle(musicTrack => musicTrack.Id == existingTracks[1].Id);
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.ShouldHaveCount(3);
});
}
[Fact]
public async Task Cannot_replace_for_href_element()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
href = "/api/v1/musicTracks/1/relationships/performers"
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'href' element is not supported.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/href");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_missing_type_in_ref()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
id = Unknown.StringId.For<Playlist, long>(),
relationship = "tracks"
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/ref");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_unknown_type_in_ref()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<Playlist, long>(),
relationship = "tracks"
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/ref/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_missing_ID_in_ref()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
relationship = "performers"
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' or 'lid' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/ref");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_unknown_ID_in_ref()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
string companyId = Unknown.StringId.For<RecordCompany, short>();
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "recordCompanies",
id = companyId,
relationship = "tracks"
},
data = new[]
{
new
{
type = "musicTracks",
id = existingTrack.StringId
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("The requested resource does not exist.");
error.Detail.Should().Be($"Resource of type 'recordCompanies' with ID '{companyId}' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]");
error.Meta.Should().NotContainKey("requestBody");
}
[Fact]
public async Task Cannot_replace_for_incompatible_ID_in_ref()
{
// Arrange
string guid = Unknown.StringId.Guid;
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "recordCompanies",
id = guid,
relationship = "tracks"
},
data = new[]
{
new
{
type = "musicTracks",
id = existingTrack.StringId
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Incompatible 'id' value found.");
error.Detail.Should().Be($"Failed to convert '{guid}' of type 'String' to type 'Int16'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/ref/id");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_ID_and_local_ID_in_ref()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
lid = "local-1",
relationship = "performers"
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' and 'lid' element are mutually exclusive.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/ref");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_unknown_relationship_in_ref()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "performers",
id = Unknown.StringId.For<Performer, int>(),
relationship = Unknown.Relationship
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown relationship found.");
error.Detail.Should().Be($"Relationship '{Unknown.Relationship}' does not exist on resource type 'performers'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/ref/relationship");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_missing_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationship = "performers"
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_null_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationship = "performers"
},
data = (object?)null
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of 'null'.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_object_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationship = "performers"
},
data = new
{
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an array, instead of an object.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_missing_type_in_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>(),
relationship = "tracks"
},
data = new[]
{
new
{
id = Unknown.StringId.For<MusicTrack, Guid>()
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_unknown_type_in_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationship = "performers"
},
data = new[]
{
new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<Performer, int>()
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data[0]/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_missing_ID_in_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationship = "performers"
},
data = new[]
{
new
{
type = "performers"
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' or 'lid' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_ID_and_local_ID_in_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationship = "performers"
},
data = new[]
{
new
{
type = "performers",
id = Unknown.StringId.For<Performer, int>(),
lid = "local-1"
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' and 'lid' element are mutually exclusive.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data[0]");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_unknown_IDs_in_data()
{
// Arrange
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
string[] trackIds =
{
Unknown.StringId.For<MusicTrack, Guid>(),
Unknown.StringId.AltFor<MusicTrack, Guid>()
};
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.RecordCompanies.Add(existingCompany);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "recordCompanies",
id = existingCompany.StringId,
relationship = "tracks"
},
data = new[]
{
new
{
type = "musicTracks",
id = trackIds[0]
},
new
{
type = "musicTracks",
id = trackIds[1]
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.ShouldHaveCount(2);
ErrorObject error1 = responseDocument.Errors[0];
error1.StatusCode.Should().Be(HttpStatusCode.NotFound);
error1.Title.Should().Be("A related resource does not exist.");
error1.Detail.Should().Be($"Related resource of type 'musicTracks' with ID '{trackIds[0]}' in relationship 'tracks' does not exist.");
error1.Source.ShouldNotBeNull();
error1.Source.Pointer.Should().Be("/atomic:operations[0]");
ErrorObject error2 = responseDocument.Errors[1];
error2.StatusCode.Should().Be(HttpStatusCode.NotFound);
error2.Title.Should().Be("A related resource does not exist.");
error2.Detail.Should().Be($"Related resource of type 'musicTracks' with ID '{trackIds[1]}' in relationship 'tracks' does not exist.");
error2.Source.ShouldNotBeNull();
error2.Source.Pointer.Should().Be("/atomic:operations[0]");
}
[Fact]
public async Task Cannot_replace_for_incompatible_ID_in_data()
{
// Arrange
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.RecordCompanies.Add(existingCompany);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "recordCompanies",
id = existingCompany.StringId,
relationship = "tracks"
},
data = new[]
{
new
{
type = "musicTracks",
id = "invalid-guid"
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Incompatible 'id' value found.");
error.Detail.Should().Be("Failed to convert 'invalid-guid' of type 'String' to type 'Guid'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data[0]/id");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_replace_for_relationship_mismatch_between_ref_and_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
@ref = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationship = "performers"
},
data = new[]
{
new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>()
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Conflict);
error.Title.Should().Be("Failed to deserialize request body: Incompatible resource type found.");
error.Detail.Should().Be("Type 'playlists' is incompatible with type 'performers' of relationship 'performers'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data[0]/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
}
| |
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2007
http://sourceforge.net/projects/directshownet/
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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DirectShowLib.SBE
{
#region Declarations
/// <summary>
/// From unnamed structure
/// </summary>
public enum RecordingType
{
Content = 0, // no post-recording or overlapped
Reference // allows post-recording & overlapped
}
/// <summary>
/// From STREAMBUFFER_ATTR_DATATYPE
/// </summary>
public enum StreamBufferAttrDataType
{
DWord = 0,
String = 1,
Binary = 2,
Bool = 3,
QWord = 4,
Word = 5,
Guid = 6
}
/// <summary>
/// From unnamed structure
/// </summary>
public enum StreamBufferEventCode
{
TimeHole = 0x0326, // STREAMBUFFER_EC_TIMEHOLE
StaleDataRead, // STREAMBUFFER_EC_STALE_DATA_READ
StaleFileDeleted, // STREAMBUFFER_EC_STALE_FILE_DELETED
ContentBecomingStale, // STREAMBUFFER_EC_CONTENT_BECOMING_STALE
WriteFailure, // STREAMBUFFER_EC_WRITE_FAILURE
ReadFailure, // STREAMBUFFER_EC_READ_FAILURE
RateChanged, // STREAMBUFFER_EC_RATE_CHANGED
PrimaryAudio, // STREAMBUFFER_EC_PRIMARY_AUDIO
// In Windows 7, Microsoft *RENUMBERED* the elements of the enum. So, if
// you are using Vista, 0x32b is STREAMBUFFER_EC_READ_FAILURE. In W7, it
// is STREAMBUFFER_EC_WRITE_FAILURE_CLEAR. This also affects RateChanged,
// and PrimaryAudio. If you are using a "case" statement to process events,
// you probably need entirely separate case statements for Vista/W7.
WriteFailureClear_W7 = 0x032b, // STREAMBUFFER_EC_WRITE_FAILURE_CLEAR
ReadFailure_W7,
RateChanged_W7,
PrimaryAudio_W7,
RateChangingForSetPositions, // STREAMBUFFER_EC_RATE_CHANGING_FOR_SETPOSITIONS
SetPositionsEventsDone // STREAMBUFFER_EC_SETPOSITIONS_EVENTS_DONE
}
/// <summary>
/// From g_wszStreamBufferRecording* static const WCHAR
/// </summary>
sealed public class StreamBufferRecording
{
private StreamBufferRecording()
{
}
////////////////////////////////////////////////////////////////
//
// List of pre-defined attributes
//
public readonly string Duration = "Duration";
public readonly string Bitrate = "Bitrate";
public readonly string Seekable = "Seekable";
public readonly string Stridable = "Stridable";
public readonly string Broadcast = "Broadcast";
public readonly string Protected = "Is_Protected";
public readonly string Trusted = "Is_Trusted";
public readonly string Signature_Name = "Signature_Name";
public readonly string HasAudio = "HasAudio";
public readonly string HasImage = "HasImage";
public readonly string HasScript = "HasScript";
public readonly string HasVideo = "HasVideo";
public readonly string CurrentBitrate = "CurrentBitrate";
public readonly string OptimalBitrate = "OptimalBitrate";
public readonly string HasAttachedImages = "HasAttachedImages";
public readonly string SkipBackward = "Can_Skip_Backward";
public readonly string SkipForward = "Can_Skip_Forward";
public readonly string NumberOfFrames = "NumberOfFrames";
public readonly string FileSize = "FileSize";
public readonly string HasArbitraryDataStream = "HasArbitraryDataStream";
public readonly string HasFileTransferStream = "HasFileTransferStream";
////////////////////////////////////////////////////////////////
//
// The content description object supports 5 basic attributes.
//
public readonly string Title = "Title";
public readonly string Author = "Author";
public readonly string Description = "Description";
public readonly string Rating = "Rating";
public readonly string Copyright = "Copyright";
////////////////////////////////////////////////////////////////
//
// These attributes are used to configure DRM using IWMDRMWriter::SetDRMAttribute.
//
public readonly string Use_DRM = "Use_DRM";
public readonly string DRM_Flags = "DRM_Flags";
public readonly string DRM_Level = "DRM_Level";
////////////////////////////////////////////////////////////////
//
// These are the additional attributes defined in the WM attribute
// namespace that give information about the content.
//
public readonly string AlbumTitle = "WM/AlbumTitle";
public readonly string Track = "WM/Track";
public readonly string PromotionURL = "WM/PromotionURL";
public readonly string AlbumCoverURL = "WM/AlbumCoverURL";
public readonly string Genre = "WM/Genre";
public readonly string Year = "WM/Year";
public readonly string GenreID = "WM/GenreID";
public readonly string MCDI = "WM/MCDI";
public readonly string Composer = "WM/Composer";
public readonly string Lyrics = "WM/Lyrics";
public readonly string TrackNumber = "WM/TrackNumber";
public readonly string ToolName = "WM/ToolName";
public readonly string ToolVersion = "WM/ToolVersion";
public readonly string IsVBR = "IsVBR";
public readonly string AlbumArtist = "WM/AlbumArtist";
////////////////////////////////////////////////////////////////
//
// These optional attributes may be used to give information
// about the branding of the content.
//
public readonly string BannerImageType = "BannerImageType";
public readonly string BannerImageData = "BannerImageData";
public readonly string BannerImageURL = "BannerImageURL";
public readonly string CopyrightURL = "CopyrightURL";
////////////////////////////////////////////////////////////////
//
// Optional attributes, used to give information
// about video stream properties.
//
public readonly string AspectRatioX = "AspectRatioX";
public readonly string AspectRatioY = "AspectRatioY";
////////////////////////////////////////////////////////////////
//
// The NSC file supports the following attributes.
//
public readonly string NSCName = "NSC_Name";
public readonly string NSCAddress = "NSC_Address";
public readonly string NSCPhone = "NSC_Phone";
public readonly string NSCEmail = "NSC_Email";
public readonly string NSCDescription = "NSC_Description";
}
/// <summary>
/// From STREAMBUFFER_ATTRIBUTE
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct StreamBufferAttribute
{
[MarshalAs(UnmanagedType.LPWStr)] public string pszName;
public StreamBufferAttrDataType StreamBufferAttributeType;
public IntPtr pbAttribute; // BYTE *
public short cbLength;
}
/// <summary>
/// From SBE_PIN_DATA
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct SBEPinData
{
public long cDataBytes; // total sample payload bytes
public long cSamplesProcessed; // samples processed
public long cDiscontinuities; // number of discontinuities
public long cSyncPoints; // number of syncpoints
public long cTimestamps; // number of timestamps
}
public sealed class SBEEvent
{
/// <summary> EVENTID_SBE2RecControlStarted </summary>
public static readonly Guid RecControlStarted = new Guid(0x8966a89e, 0xf83e, 0x4c0e, 0xbc, 0x3b, 0xbf, 0xa7, 0x64, 0x9e, 0x4, 0xcb);
/// <summary> EVENTID_SBE2RecControlStopped </summary>
public static readonly Guid RecControlStopped = new Guid(0x454b1ec8, 0xc9b, 0x4caa, 0xb1, 0xa1, 0x1e, 0x7a, 0x26, 0x66, 0xf6, 0xc3);
/// <summary> SBE2_STREAM_DESC_EVENT </summary>
public static readonly Guid StreamDescEvent = new Guid(0x2313a4ed, 0xbf2d, 0x454f, 0xad, 0x8a, 0xd9, 0x5b, 0xa7, 0xf9, 0x1f, 0xee);
/// <summary> SBE2_V1_STREAMS_CREATION_EVENT </summary>
public static readonly Guid V1StreamsCreationEvent = new Guid(0xfcf09, 0x97f5, 0x46ac, 0x97, 0x69, 0x7a, 0x83, 0xb3, 0x53, 0x84, 0xfb);
/// <summary> SBE2_V2_STREAMS_CREATION_EVENT </summary>
public static readonly Guid V2StreamsCreationEvent = new Guid(0xa72530a3, 0x344, 0x4cab, 0xa2, 0xd0, 0xfe, 0x93, 0x7d, 0xbd, 0xca, 0xb3);
}
/// <summary>
/// From CROSSBAR_DEFAULT_FLAGS
/// </summary>
[Flags]
public enum CrossbarDefaultFlags
{
None = 0x0,
Profile = 0x0000001,
Streams = 0x0000002
}
/// <summary>
/// From SBE2_STREAM_DESC
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class SBE2_StreamDesc
{
public int Version;
public int StreamId;
public int Default;
public int Reserved;
}
/// <summary>
/// From DVR_STREAM_DESC
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class DVRStreamDesc
{
public int Version;
public int StreamId;
public bool Default;
public bool Creation;
public int Reserved;
public Guid guidSubMediaType;
public Guid guidFormatType;
public AMMediaType MediaType;
}
#endregion
#region Interfaces
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("7E2D2A1E-7192-4bd7-80C1-061FD1D10402"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferConfigure3 : IStreamBufferConfigure2
{
#region IStreamBufferConfigure
[PreserveSig]
new int SetDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string pszDirectoryName);
[PreserveSig]
new int GetDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] out string pszDirectoryName);
[PreserveSig]
new int SetBackingFileCount(
[In] int dwMin,
[In] int dwMax
);
[PreserveSig]
new int GetBackingFileCount(
[Out] out int dwMin,
[Out] out int dwMax
);
[PreserveSig]
new int SetBackingFileDuration([In] int dwSeconds);
[PreserveSig]
new int GetBackingFileDuration([Out] out int pdwSeconds);
#endregion
#region IStreamBufferConfigure2
[PreserveSig]
new int SetMultiplexedPacketSize([In] int cbBytesPerPacket);
[PreserveSig]
new int GetMultiplexedPacketSize([Out] out int pcbBytesPerPacket);
[PreserveSig]
new int SetFFTransitionRates(
[In] int dwMaxFullFrameRate,
[In] int dwMaxNonSkippingRate
);
[PreserveSig]
new int GetFFTransitionRates(
[Out] out int pdwMaxFullFrameRate,
[Out] out int pdwMaxNonSkippingRate
);
#endregion
[PreserveSig]
int SetStartRecConfig([In, MarshalAs(UnmanagedType.Bool)] bool fStartStopsCur);
[PreserveSig]
int GetStartRecConfig([Out, MarshalAs(UnmanagedType.Bool)] out bool pfStartStopsCur);
[PreserveSig]
int SetNamespace([In, MarshalAs(UnmanagedType.LPWStr)] string pszNamespace);
[PreserveSig]
int GetNamespace([Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszNamespace);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("9ce50f2d-6ba7-40fb-a034-50b1a674ec78"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferInitialize
{
[PreserveSig]
int SetHKEY([In] IntPtr hkeyRoot); // HKEY
[PreserveSig]
int SetSIDs(
[In] int cSIDs,
[In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] ppSID // PSID *
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("afd1f242-7efd-45ee-ba4e-407a25c9a77a"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSink
{
[PreserveSig]
int LockProfile([In, MarshalAs(UnmanagedType.LPWStr)] string pszStreamBufferFilename);
[PreserveSig]
int CreateRecorder(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszFilename,
[In] RecordingType dwRecordType,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object pRecordingIUnknown
);
[PreserveSig]
int IsProfileLocked();
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("DB94A660-F4FB-4bfa-BCC6-FE159A4EEA93"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSink2 : IStreamBufferSink
{
#region IStreamBufferSink Methods
[PreserveSig]
new int LockProfile([In, MarshalAs(UnmanagedType.LPWStr)] string pszStreamBufferFilename);
[PreserveSig]
new int CreateRecorder(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszFilename,
[In] RecordingType dwRecordType,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object pRecordingIUnknown
);
[PreserveSig]
new int IsProfileLocked();
#endregion
[PreserveSig]
int UnlockProfile();
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("974723f2-887a-4452-9366-2cff3057bc8f"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSink3 : IStreamBufferSink2
{
#region IStreamBufferSink Methods
[PreserveSig]
new int LockProfile([In, MarshalAs(UnmanagedType.LPWStr)] string pszStreamBufferFilename);
[PreserveSig]
new int CreateRecorder(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszFilename,
[In] RecordingType dwRecordType,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object pRecordingIUnknown
);
[PreserveSig]
new int IsProfileLocked();
#endregion
#region IStreamBufferSink2
[PreserveSig]
new int UnlockProfile();
#endregion
[PreserveSig]
int SetAvailableFilter([In, Out] ref long prtMin);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("1c5bd776-6ced-4f44-8164-5eab0e98db12"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSource
{
[PreserveSig]
int SetStreamSink([In] IStreamBufferSink pIStreamBufferSink);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("ba9b6c99-f3c7-4ff2-92db-cfdd4851bf31"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferRecordControl
{
[PreserveSig]
int Start([In, Out] ref long prtStart);
[PreserveSig]
int Stop([In] long rtStop);
[PreserveSig]
int GetRecordingStatus(
[Out] out int phResult,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pbStarted,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pbStopped
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("9E259A9B-8815-42ae-B09F-221970B154FD"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferRecComp
{
[PreserveSig]
int Initialize(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszTargetFilename,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszSBRecProfileRef
);
[PreserveSig]
int Append([In, MarshalAs(UnmanagedType.LPWStr)] string pszSBRecording);
[PreserveSig]
int AppendEx(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszSBRecording,
[In] long rtStart,
[In] long rtStop
);
[PreserveSig]
int GetCurrentLength([Out] out int pcSeconds);
[PreserveSig]
int Close();
[PreserveSig]
int Cancel();
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("16CA4E03-FE69-4705-BD41-5B7DFC0C95F3"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferRecordingAttribute
{
[PreserveSig]
int SetAttribute(
[In] int ulReserved,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAttributeName,
[In] StreamBufferAttrDataType StreamBufferAttributeType,
[In] IntPtr pbAttribute, // BYTE *
[In] short cbAttributeLength
);
[PreserveSig]
int GetAttributeCount(
[In] int ulReserved,
[Out] out short pcAttributes
);
[PreserveSig]
int GetAttributeByName(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAttributeName,
[In] int pulReserved,
[Out] out StreamBufferAttrDataType pStreamBufferAttributeType,
[In, Out] IntPtr pbAttribute, // BYTE *
[In, Out] ref short pcbLength
);
[PreserveSig]
int GetAttributeByIndex(
[In] short wIndex,
[In] int pulReserved,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszAttributeName,
[In, Out] ref short pcchNameLength,
[Out] out StreamBufferAttrDataType pStreamBufferAttributeType,
IntPtr pbAttribute, // BYTE *
[In, Out] ref short pcbLength
);
int EnumAttributes([Out] out IEnumStreamBufferRecordingAttrib ppIEnumStreamBufferAttrib);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("C18A9162-1E82-4142-8C73-5690FA62FE33"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEnumStreamBufferRecordingAttrib
{
[PreserveSig]
int Next(
[In] int cRequest,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] StreamBufferAttribute[] pStreamBufferAttribute,
[In] IntPtr pcReceived
);
[PreserveSig]
int Skip([In] int cRecords);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone([Out] out IEnumStreamBufferRecordingAttrib ppIEnumStreamBufferAttrib);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("ce14dfae-4098-4af7-bbf7-d6511f835414"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferConfigure
{
[PreserveSig]
int SetDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string pszDirectoryName);
[PreserveSig]
int GetDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] out string pszDirectoryName);
[PreserveSig]
int SetBackingFileCount(
[In] int dwMin,
[In] int dwMax
);
[PreserveSig]
int GetBackingFileCount(
[Out] out int dwMin,
[Out] out int dwMax
);
[PreserveSig]
int SetBackingFileDuration([In] int dwSeconds);
[PreserveSig]
int GetBackingFileDuration([Out] out int pdwSeconds);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("53E037BF-3992-4282-AE34-2487B4DAE06B"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferConfigure2 : IStreamBufferConfigure
{
#region IStreamBufferConfigure
[PreserveSig]
new int SetDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string pszDirectoryName);
[PreserveSig]
new int GetDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] out string pszDirectoryName);
[PreserveSig]
new int SetBackingFileCount(
[In] int dwMin,
[In] int dwMax
);
[PreserveSig]
new int GetBackingFileCount(
[Out] out int dwMin,
[Out] out int dwMax
);
[PreserveSig]
new int SetBackingFileDuration([In] int dwSeconds);
[PreserveSig]
new int GetBackingFileDuration([Out] out int pdwSeconds);
#endregion
[PreserveSig]
int SetMultiplexedPacketSize([In] int cbBytesPerPacket);
[PreserveSig]
int GetMultiplexedPacketSize([Out] out int pcbBytesPerPacket);
[PreserveSig]
int SetFFTransitionRates(
[In] int dwMaxFullFrameRate,
[In] int dwMaxNonSkippingRate
);
[PreserveSig]
int GetFFTransitionRates(
[Out] out int pdwMaxFullFrameRate,
[Out] out int pdwMaxNonSkippingRate
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("f61f5c26-863d-4afa-b0ba-2f81dc978596"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferMediaSeeking : IMediaSeeking
{
#region IMediaSeeking Methods
[PreserveSig]
new int GetCapabilities([Out] out AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int CheckCapabilities([In, Out] ref AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int IsFormatSupported([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int QueryPreferredFormat([Out] out Guid pFormat);
[PreserveSig]
new int GetTimeFormat([Out] out Guid pFormat);
[PreserveSig]
new int IsUsingTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int SetTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int GetDuration([Out] out long pDuration);
[PreserveSig]
new int GetStopPosition([Out] out long pStop);
[PreserveSig]
new int GetCurrentPosition([Out] out long pCurrent);
[PreserveSig]
new int ConvertTimeFormat(
[Out] out long pTarget,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pTargetFormat,
[In] long Source,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pSourceFormat
);
[PreserveSig]
new int SetPositions(
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pCurrent,
[In] AMSeekingSeekingFlags dwCurrentFlags,
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pStop,
[In] AMSeekingSeekingFlags dwStopFlags
);
[PreserveSig]
new int GetPositions(
[Out] out long pCurrent,
[Out] out long pStop
);
[PreserveSig]
new int GetAvailable(
[Out] out long pEarliest,
[Out] out long pLatest
);
[PreserveSig]
new int SetRate([In] double dRate);
[PreserveSig]
new int GetRate([Out] out double pdRate);
[PreserveSig]
new int GetPreroll([Out] out long pllPreroll);
#endregion
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("3a439ab0-155f-470a-86a6-9ea54afd6eaf"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferMediaSeeking2 : IStreamBufferMediaSeeking
{
#region IMediaSeeking
[PreserveSig]
new int GetCapabilities([Out] out AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int CheckCapabilities([In, Out] ref AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int IsFormatSupported([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int QueryPreferredFormat([Out] out Guid pFormat);
[PreserveSig]
new int GetTimeFormat([Out] out Guid pFormat);
[PreserveSig]
new int IsUsingTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int SetTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int GetDuration([Out] out long pDuration);
[PreserveSig]
new int GetStopPosition([Out] out long pStop);
[PreserveSig]
new int GetCurrentPosition([Out] out long pCurrent);
[PreserveSig]
new int ConvertTimeFormat(
[Out] out long pTarget,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pTargetFormat,
[In] long Source,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pSourceFormat
);
[PreserveSig]
new int SetPositions(
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pCurrent,
[In] AMSeekingSeekingFlags dwCurrentFlags,
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pStop,
[In] AMSeekingSeekingFlags dwStopFlags
);
[PreserveSig]
new int GetPositions(
[Out] out long pCurrent,
[Out] out long pStop
);
[PreserveSig]
new int GetAvailable(
[Out] out long pEarliest,
[Out] out long pLatest
);
[PreserveSig]
new int SetRate([In] double dRate);
[PreserveSig]
new int GetRate([Out] out double pdRate);
[PreserveSig]
new int GetPreroll([Out] out long pllPreroll);
#endregion
[PreserveSig]
int SetRateEx(
[In] double dRate,
[In] int dwFramesPerSec
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("9D2A2563-31AB-402e-9A6B-ADB903489440"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferDataCounters
{
[PreserveSig]
int GetData([Out] out SBEPinData pPinData);
[PreserveSig]
int ResetData();
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("caede759-b6b1-11db-a578-0018f3fa24c6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2GlobalEvent
{
[PreserveSig]
int GetEvent(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid idEvt,
int param1,
int param2,
int param3,
int param4,
[MarshalAs(UnmanagedType.Bool)] out bool pSpanning,
ref int pcb,
[Out] IntPtr pb
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("6D8309BF-00FE-4506-8B03-F8C65B5C9B39"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2GlobalEvent2 : ISBE2GlobalEvent
{
#region ISBE2GlobalEvent methods
[PreserveSig]
new int GetEvent(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid idEvt,
int param1,
int param2,
int param3,
int param4,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pSpanning,
ref int pcb,
[Out] IntPtr pb
);
#endregion
[PreserveSig]
int GetEventEx(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid idEvt,
int param1,
int param2,
int param3,
int param4,
[MarshalAs(UnmanagedType.Bool)] out bool pSpanning,
ref int pcb,
[Out] IntPtr pb,
out long pStreamTime
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("caede760-b6b1-11db-a578-0018f3fa24c6"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2SpanningEvent
{
[PreserveSig]
int GetEvent(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid idEvt,
int streamId,
ref int pcb,
IntPtr pb
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("547b6d26-3226-487e-8253-8aa168749434"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2Crossbar
{
[PreserveSig]
int EnableDefaultMode(
CrossbarDefaultFlags DefaultFlags
);
[PreserveSig]
int GetInitialProfile(
out ISBE2MediaTypeProfile ppProfile
);
[PreserveSig]
int SetOutputProfile(
ISBE2MediaTypeProfile pProfile,
ref int pcOutputPins,
[Out, MarshalAs(UnmanagedType.LPArray)] IPin[] ppOutputPins
);
[PreserveSig]
int EnumStreams(
out ISBE2EnumStream ppStreams
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("667c7745-85b1-4c55-ae55-4e25056159fc"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2StreamMap
{
[PreserveSig]
int MapStream(
int Stream
);
[PreserveSig]
int UnmapStream(
int Stream
);
[PreserveSig]
int EnumMappedStreams(
out ISBE2EnumStream ppStreams
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("f7611092-9fbc-46ec-a7c7-548ea78b71a4"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2EnumStream
{
[PreserveSig]
int Next(
int cRequest,
[In, Out, MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef=typeof(SDMarshaler))] SBE2_StreamDesc[] pStreamDesc,
IntPtr pcReceived
);
[PreserveSig]
int Skip(
int cRecords
);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone(
out ISBE2EnumStream ppIEnumStream
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("f238267d-4671-40d7-997e-25dc32cfed2a"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2MediaTypeProfile
{
[PreserveSig]
int GetStreamCount(
out int pCount
);
[PreserveSig]
int GetStream(
int Index,
out AMMediaType ppMediaType
);
[PreserveSig]
int AddStream(
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType pMediaType
);
[PreserveSig]
int DeleteStream(
int Index
);
}
[ComImport, System.Security.SuppressUnmanagedCodeSecurity,
Guid("3E2BF5A5-4F96-4899-A1A3-75E8BE9A5AC0"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISBE2FileScan
{
[PreserveSig]
int RepairFile(
[In, MarshalAs(UnmanagedType.LPWStr)] string filename
);
}
#endregion
internal class SDMarshaler : ICustomMarshaler
{
SBE2_StreamDesc[] m_sd;
virtual public void CleanUpManagedData(object managedObj)
{
m_sd = null;
}
public void CleanUpNativeData(IntPtr pNativeData)
{
if (pNativeData != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pNativeData);
}
}
public int GetNativeDataSize()
{
return 0;
}
public IntPtr MarshalManagedToNative(object managedObj)
{
IntPtr ip;
m_sd = managedObj as SBE2_StreamDesc [];
int iSize = m_sd.Length * Marshal.SizeOf(typeof(SBE2_StreamDesc));
ip = Marshal.AllocCoTaskMem(iSize);
#if DEBUG
for (int x = 0; x < iSize / 8; x++)
{
Marshal.WriteInt64(ip, x * 8, 0);
}
#endif
return ip;
}
// Called just after invoking the COM method. The IntPtr is the same one that just got returned
// from MarshalManagedToNative. The return value is unused.
public object MarshalNativeToManaged(IntPtr pNativeData)
{
IntPtr ip = pNativeData;
for (int x = 0; x < m_sd.Length; x++)
{
//m_sd[x] = new SBE2_StreamDesc(); Marshal.PtrToStructure(ip, m_sd[x]);
m_sd[x] = (SBE2_StreamDesc)Marshal.PtrToStructure(ip, typeof(SBE2_StreamDesc));
ip = new IntPtr(ip.ToInt64() + Marshal.SizeOf(typeof(SBE2_StreamDesc)));
}
return null;
}
// This method is called by interop to create the custom marshaler. The (optional)
// cookie is the value specified in MarshalCookie="asdf", or "" is none is specified.
public static ICustomMarshaler GetInstance(string cookie)
{
return new SDMarshaler();
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class ThirdPartyParcelAccount : IEquatable<ThirdPartyParcelAccount>
{
/// <summary>
/// Initializes a new instance of the <see cref="ThirdPartyParcelAccount" /> class.
/// Initializes a new instance of the <see cref="ThirdPartyParcelAccount" />class.
/// </summary>
/// <param name="LobId">LobId (required).</param>
/// <param name="Carrier">Carrier (required).</param>
/// <param name="AccountNo">AccountNo (required).</param>
/// <param name="AccountName">AccountName (required).</param>
/// <param name="BillingCompany">BillingCompany (required).</param>
/// <param name="Attention">Attention.</param>
/// <param name="Street1">Street1 (required).</param>
/// <param name="Street2">Street2.</param>
/// <param name="Street3">Street3.</param>
/// <param name="City">City (required).</param>
/// <param name="State">State (required).</param>
/// <param name="Country">Country.</param>
/// <param name="ZipCode">ZipCode (required).</param>
/// <param name="Phone">Phone.</param>
/// <param name="Active">Active (required).</param>
/// <param name="CustomFields">CustomFields.</param>
public ThirdPartyParcelAccount(int? LobId = null, string Carrier = null, string AccountNo = null, string AccountName = null, string BillingCompany = null, string Attention = null, string Street1 = null, string Street2 = null, string Street3 = null, string City = null, string State = null, string Country = null, string ZipCode = null, string Phone = null, string Active = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "LobId" is required (not null)
if (LobId == null)
{
throw new InvalidDataException("LobId is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.LobId = LobId;
}
// to ensure "Carrier" is required (not null)
if (Carrier == null)
{
throw new InvalidDataException("Carrier is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.Carrier = Carrier;
}
// to ensure "AccountNo" is required (not null)
if (AccountNo == null)
{
throw new InvalidDataException("AccountNo is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.AccountNo = AccountNo;
}
// to ensure "AccountName" is required (not null)
if (AccountName == null)
{
throw new InvalidDataException("AccountName is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.AccountName = AccountName;
}
// to ensure "BillingCompany" is required (not null)
if (BillingCompany == null)
{
throw new InvalidDataException("BillingCompany is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.BillingCompany = BillingCompany;
}
// to ensure "Street1" is required (not null)
if (Street1 == null)
{
throw new InvalidDataException("Street1 is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.Street1 = Street1;
}
// to ensure "City" is required (not null)
if (City == null)
{
throw new InvalidDataException("City is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.City = City;
}
// to ensure "State" is required (not null)
if (State == null)
{
throw new InvalidDataException("State is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.State = State;
}
// to ensure "ZipCode" is required (not null)
if (ZipCode == null)
{
throw new InvalidDataException("ZipCode is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.ZipCode = ZipCode;
}
// to ensure "Active" is required (not null)
if (Active == null)
{
throw new InvalidDataException("Active is a required property for ThirdPartyParcelAccount and cannot be null");
}
else
{
this.Active = Active;
}
this.Attention = Attention;
this.Street2 = Street2;
this.Street3 = Street3;
this.Country = Country;
this.Phone = Phone;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; set; }
/// <summary>
/// Gets or Sets Carrier
/// </summary>
[DataMember(Name="carrier", EmitDefaultValue=false)]
public string Carrier { get; set; }
/// <summary>
/// Gets or Sets AccountNo
/// </summary>
[DataMember(Name="accountNo", EmitDefaultValue=false)]
public string AccountNo { get; set; }
/// <summary>
/// Gets or Sets AccountName
/// </summary>
[DataMember(Name="accountName", EmitDefaultValue=false)]
public string AccountName { get; set; }
/// <summary>
/// Gets or Sets BillingCompany
/// </summary>
[DataMember(Name="billingCompany", EmitDefaultValue=false)]
public string BillingCompany { get; set; }
/// <summary>
/// Gets or Sets Attention
/// </summary>
[DataMember(Name="attention", EmitDefaultValue=false)]
public string Attention { get; set; }
/// <summary>
/// Gets or Sets Street1
/// </summary>
[DataMember(Name="street1", EmitDefaultValue=false)]
public string Street1 { get; set; }
/// <summary>
/// Gets or Sets Street2
/// </summary>
[DataMember(Name="street2", EmitDefaultValue=false)]
public string Street2 { get; set; }
/// <summary>
/// Gets or Sets Street3
/// </summary>
[DataMember(Name="street3", EmitDefaultValue=false)]
public string Street3 { get; set; }
/// <summary>
/// Gets or Sets City
/// </summary>
[DataMember(Name="city", EmitDefaultValue=false)]
public string City { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public string State { get; set; }
/// <summary>
/// Gets or Sets Country
/// </summary>
[DataMember(Name="country", EmitDefaultValue=false)]
public string Country { get; set; }
/// <summary>
/// Gets or Sets ZipCode
/// </summary>
[DataMember(Name="zipCode", EmitDefaultValue=false)]
public string ZipCode { get; set; }
/// <summary>
/// Gets or Sets Phone
/// </summary>
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/// <summary>
/// Gets or Sets Active
/// </summary>
[DataMember(Name="active", EmitDefaultValue=false)]
public string Active { get; set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { 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 ThirdPartyParcelAccount {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" Carrier: ").Append(Carrier).Append("\n");
sb.Append(" AccountNo: ").Append(AccountNo).Append("\n");
sb.Append(" AccountName: ").Append(AccountName).Append("\n");
sb.Append(" BillingCompany: ").Append(BillingCompany).Append("\n");
sb.Append(" Attention: ").Append(Attention).Append("\n");
sb.Append(" Street1: ").Append(Street1).Append("\n");
sb.Append(" Street2: ").Append(Street2).Append("\n");
sb.Append(" Street3: ").Append(Street3).Append("\n");
sb.Append(" City: ").Append(City).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Country: ").Append(Country).Append("\n");
sb.Append(" ZipCode: ").Append(ZipCode).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).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 ThirdPartyParcelAccount);
}
/// <summary>
/// Returns true if ThirdPartyParcelAccount instances are equal
/// </summary>
/// <param name="other">Instance of ThirdPartyParcelAccount to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ThirdPartyParcelAccount other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.Carrier == other.Carrier ||
this.Carrier != null &&
this.Carrier.Equals(other.Carrier)
) &&
(
this.AccountNo == other.AccountNo ||
this.AccountNo != null &&
this.AccountNo.Equals(other.AccountNo)
) &&
(
this.AccountName == other.AccountName ||
this.AccountName != null &&
this.AccountName.Equals(other.AccountName)
) &&
(
this.BillingCompany == other.BillingCompany ||
this.BillingCompany != null &&
this.BillingCompany.Equals(other.BillingCompany)
) &&
(
this.Attention == other.Attention ||
this.Attention != null &&
this.Attention.Equals(other.Attention)
) &&
(
this.Street1 == other.Street1 ||
this.Street1 != null &&
this.Street1.Equals(other.Street1)
) &&
(
this.Street2 == other.Street2 ||
this.Street2 != null &&
this.Street2.Equals(other.Street2)
) &&
(
this.Street3 == other.Street3 ||
this.Street3 != null &&
this.Street3.Equals(other.Street3)
) &&
(
this.City == other.City ||
this.City != null &&
this.City.Equals(other.City)
) &&
(
this.State == other.State ||
this.State != null &&
this.State.Equals(other.State)
) &&
(
this.Country == other.Country ||
this.Country != null &&
this.Country.Equals(other.Country)
) &&
(
this.ZipCode == other.ZipCode ||
this.ZipCode != null &&
this.ZipCode.Equals(other.ZipCode)
) &&
(
this.Phone == other.Phone ||
this.Phone != null &&
this.Phone.Equals(other.Phone)
) &&
(
this.Active == other.Active ||
this.Active != null &&
this.Active.Equals(other.Active)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.Carrier != null)
hash = hash * 59 + this.Carrier.GetHashCode();
if (this.AccountNo != null)
hash = hash * 59 + this.AccountNo.GetHashCode();
if (this.AccountName != null)
hash = hash * 59 + this.AccountName.GetHashCode();
if (this.BillingCompany != null)
hash = hash * 59 + this.BillingCompany.GetHashCode();
if (this.Attention != null)
hash = hash * 59 + this.Attention.GetHashCode();
if (this.Street1 != null)
hash = hash * 59 + this.Street1.GetHashCode();
if (this.Street2 != null)
hash = hash * 59 + this.Street2.GetHashCode();
if (this.Street3 != null)
hash = hash * 59 + this.Street3.GetHashCode();
if (this.City != null)
hash = hash * 59 + this.City.GetHashCode();
if (this.State != null)
hash = hash * 59 + this.State.GetHashCode();
if (this.Country != null)
hash = hash * 59 + this.Country.GetHashCode();
if (this.ZipCode != null)
hash = hash * 59 + this.ZipCode.GetHashCode();
if (this.Phone != null)
hash = hash * 59 + this.Phone.GetHashCode();
if (this.Active != null)
hash = hash * 59 + this.Active.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// We don't automatically run these tests against the BCL implementation of ImmutableDictionary as it would require dual-compiling
// this file. When making changes to this test, though, it is recommended to run them manually by uncommenting the following line.
// This helps ensure that the real thing has the same behavior that we expect in our implementation.
//#define _TEST_BCL_IMMUTABLE_DICTIONARY
extern alias MSBuildTaskHost;
using System;
using System.Collections;
using System.Collections.Generic;
using Shouldly;
using Xunit;
#if _TEST_BCL_IMMUTABLE_DICTIONARY
using ImmutableDictionary = System.Collections.Immutable.ImmutableDictionary<string, string>;
#else
using ImmutableDictionary = MSBuildTaskHost::System.Collections.Immutable.ImmutableDictionary<string, string>;
#endif
namespace Microsoft.Build.UnitTests
{
public class ImmutableDictionary_Tests
{
private readonly ImmutableDictionary _emptyDict = ImmutableDictionary.Empty;
[Fact]
public void SimplesBoolPropertiesReturnExpectedValues()
{
((IDictionary)_emptyDict).IsFixedSize.ShouldBeTrue();
((IDictionary)_emptyDict).IsReadOnly.ShouldBeTrue();
((IDictionary)_emptyDict).IsSynchronized.ShouldBeTrue();
}
[Fact]
public void CountReturnsExpectedValue()
{
_emptyDict.Count.ShouldBe(0);
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
dict.Count.ShouldBe(1);
dict = dict.SetItem("Key2", "Value2");
dict.Count.ShouldBe(2);
dict = dict.Clear();
dict.Count.ShouldBe(0);
}
[Fact]
public void IndexerReturnsPreviouslySetItem()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
dict["Key1"].ShouldBe("Value1");
((IDictionary)dict)["Key1"].ShouldBe("Value1");
((IDictionary<string, string>)dict)["Key1"].ShouldBe("Value1");
}
[Fact]
public void IndexerThrowsForItemNotPreviouslySet()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
Should.Throw<KeyNotFoundException>(() => _ = dict["Key2"]);
Should.Throw<KeyNotFoundException>(() => _ = ((IDictionary)dict)["Key2"]);
Should.Throw<KeyNotFoundException>(() => _ = ((IDictionary<string, string>)dict)["Key2"]);
}
[Fact]
public void ContainsReturnsTrueForPeviouslySetItem()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
dict.Contains(new KeyValuePair<string, string>("Key1", "Value1")).ShouldBeTrue();
dict.ContainsKey("Key1").ShouldBeTrue();
((IDictionary)dict).Contains("Key1").ShouldBeTrue();
}
[Fact]
public void ContainsReturnsFalseForItemNotPeviouslySet()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
dict.Contains(new KeyValuePair<string, string>("Key2", "Value2")).ShouldBeFalse();
dict.ContainsKey("Key2").ShouldBeFalse();
((IDictionary)dict).Contains("Key2").ShouldBeFalse();
}
[Fact]
public void EnumeratorEnumeratesItems()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
IEnumerator<KeyValuePair<string, string>> enumerator1 = dict.GetEnumerator();
int i = 0;
while (enumerator1.MoveNext())
{
i++;
enumerator1.Current.Key.ShouldBe("Key1");
enumerator1.Current.Value.ShouldBe("Value1");
}
i.ShouldBe(dict.Count);
IDictionaryEnumerator enumerator2 = ((IDictionary)dict).GetEnumerator();
i = 0;
while (enumerator2.MoveNext())
{
i++;
enumerator2.Key.ShouldBe("Key1");
enumerator2.Value.ShouldBe("Value1");
}
i.ShouldBe(dict.Count);
IEnumerator enumerator3 = ((IEnumerable)dict).GetEnumerator();
i = 0;
while (enumerator3.MoveNext())
{
i++;
KeyValuePair<string, string> entry = (KeyValuePair<string, string>)enumerator3.Current;
entry.Key.ShouldBe("Key1");
entry.Value.ShouldBe("Value1");
}
i.ShouldBe(dict.Count);
}
[Fact]
public void CopyToCopiesItemsToArray()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
KeyValuePair<string, string>[] array1 = new KeyValuePair<string, string>[1];
((ICollection<KeyValuePair<string, string>>)dict).CopyTo(array1, 0);
array1[0].Key.ShouldBe("Key1");
array1[0].Value.ShouldBe("Value1");
array1 = new KeyValuePair<string, string>[2];
((ICollection<KeyValuePair<string, string>>)dict).CopyTo(array1, 1);
array1[1].Key.ShouldBe("Key1");
array1[1].Value.ShouldBe("Value1");
DictionaryEntry[] array2 = new DictionaryEntry[1];
((ICollection)dict).CopyTo(array2, 0);
array2[0].Key.ShouldBe("Key1");
array2[0].Value.ShouldBe("Value1");
array2 = new DictionaryEntry[2];
((ICollection)dict).CopyTo(array2, 1);
array2[1].Key.ShouldBe("Key1");
array2[1].Value.ShouldBe("Value1");
}
[Fact]
public void CopyToThrowsOnInvalidInput()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
Should.Throw<ArgumentNullException>(() => ((ICollection<KeyValuePair<string, string>>)dict).CopyTo(null, 0));
Should.Throw<ArgumentNullException>(() => ((ICollection)dict).CopyTo(null, 0));
KeyValuePair<string, string>[] array1 = new KeyValuePair<string, string>[1];
DictionaryEntry[] array2 = new DictionaryEntry[1];
Should.Throw<ArgumentOutOfRangeException>(() => ((ICollection<KeyValuePair<string, string>>)dict).CopyTo(array1, -1));
Should.Throw<ArgumentOutOfRangeException>(() => ((ICollection)dict).CopyTo(array1, -1));
Should.Throw<ArgumentException>(() => ((ICollection<KeyValuePair<string, string>>)dict).CopyTo(array1, 1));
Should.Throw<ArgumentException>(() => ((ICollection)dict).CopyTo(array1, 1));
}
[Fact]
public void KeysReturnsKeys()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
ICollection<string> keys1 = ((IDictionary<string, string>)dict).Keys;
keys1.ShouldBe(new string[] { "Key1" });
ICollection keys2 = ((IDictionary)dict).Keys;
keys2.ShouldBe(new string[] { "Key1" });
}
[Fact]
public void ValuesReturnsValues()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
ICollection<string> values1 = ((IDictionary<string, string>)dict).Values;
values1.ShouldBe(new string[] { "Value1" });
ICollection values2 = ((IDictionary)dict).Values;
values2.ShouldBe(new string[] { "Value1" });
}
[Fact]
public void SetItemReturnsNewInstanceAfterAdding()
{
ImmutableDictionary dict = _emptyDict.SetItem("Key1", "Value1");
dict.ShouldNotBeSameAs(_emptyDict);
}
[Fact]
public void SetItemReturnsNewInstanceAfterUpdating()
{
ImmutableDictionary dict1 = _emptyDict.SetItem("Key1", "Value1");
ImmutableDictionary dict2 = dict1.SetItem("Key1", "Value2");
dict2.ShouldNotBeSameAs(dict1);
}
[Fact]
public void SetItemReturnsSameInstanceWhenItemAlreadyExists()
{
ImmutableDictionary dict1 = _emptyDict.SetItem("Key1", "Value1");
ImmutableDictionary dict2 = dict1.SetItem("Key1", "Value1");
dict2.ShouldBeSameAs(dict1);
}
[Fact]
public void RemoveReturnsNewInstanceAfterDeleting()
{
ImmutableDictionary dict1 = _emptyDict.SetItem("Key1", "Value1");
ImmutableDictionary dict2 = dict1.Remove("Key1");
dict2.ShouldNotBeSameAs(dict1);
}
[Fact]
public void RemoveReturnsSameInstanceWhenItemDoesNotExist()
{
ImmutableDictionary dict1 = _emptyDict.SetItem("Key1", "Value1");
ImmutableDictionary dict2 = dict1.Remove("Key2");
dict2.ShouldBeSameAs(dict1);
}
[Fact]
public void ClearReturnsNewInstance()
{
ImmutableDictionary dict1 = _emptyDict.SetItem("Key1", "Value1");
ImmutableDictionary dict2 = dict1.Clear();
dict2.ShouldNotBeSameAs(dict1);
}
[Fact]
public void WithComparersCreatesNewInstanceWithSpecifiedKeyComparer()
{
ImmutableDictionary dict1 = _emptyDict.SetItem("Key1", "Value1");
ImmutableDictionary dict2 = dict1.WithComparers(StringComparer.OrdinalIgnoreCase);
dict2["KEY1"].ShouldBe("Value1");
}
[Fact]
public void AddRangeAddsAllItems()
{
ImmutableDictionary dict = _emptyDict.AddRange(new KeyValuePair<string, string>[]
{
new KeyValuePair<string, string>("Key1", "Value1"),
new KeyValuePair<string, string>("Key2", "Value2")
});
dict.Count.ShouldBe(2);
dict["Key1"].ShouldBe("Value1");
dict["Key2"].ShouldBe("Value2");
}
}
}
| |
// Copyright 2018, 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.
using Google.Api.Gax;
using Google.Protobuf;
using Google.Protobuf.Reflection;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections;
using System.Linq;
namespace Google.Ads.GoogleAds.Util
{
/// <summary>
/// Utility methods for working with field paths.
/// </summary>
public static class FieldMasks
{
/// <summary>
/// Constructs a fieldmask object that captures the list of all set fields of an object.
/// </summary>
/// <param name="modified">The modified object.</param>
/// <returns>A fieldmask object that captures the list of all set fields.</returns>
public static FieldMask AllSetFieldsOf<T>(IMessage<T> modified)
where T : class, IMessage<T>
{
IMessage<T> original = (IMessage<T>) modified.Descriptor.Parser.ParseFrom(new byte[] { });
return FromChanges(original, modified);
}
/// <summary>
/// Compares two messages, constructing a field mask to express the difference between them.
/// </summary>
/// <param name="modified">The modified object.</param>
/// <param name="original">The original object.</param>
/// <returns>A fieldmask object that captures the changes.</returns>
public static FieldMask FromChanges<T>(IMessage<T> original, IMessage<T> modified)
where T : class, IMessage<T>
{
// TODO: Permit null parameters? What would we return?
GaxPreconditions.CheckNotNull(modified, nameof(modified));
FieldMask mask = new FieldMask();
CompareField(mask, "", original, modified);
return mask;
}
/// <summary>
/// Compares a given field for two messages, and captures the differences between them.
/// </summary>
/// <param name="mask">The fieldmask to store the differences to.</param>
/// <param name="fieldName">The field name to compare.</param>
/// <param name="original">The original value of the field.</param>
/// <param name="modified">The modified value of the field.</param>
private static void CompareField(FieldMask mask, string fieldName, IMessage original,
IMessage modified)
{
var descriptor = modified.Descriptor;
foreach (var childField in descriptor.Fields.InFieldNumberOrder())
{
string childFieldName = GetFullFieldName(fieldName, childField);
var originalChildValue = childField.Accessor.GetValue(original);
var modifiedChildValue = childField.Accessor.GetValue(modified);
if (childField.IsRepeated)
{
if (!Equals(originalChildValue, modifiedChildValue))
{
mask.Paths.Add(childFieldName);
}
}
else
{
switch (childField.FieldType)
{
case FieldType.Message:
if (!Equals(originalChildValue, modifiedChildValue))
{
// For wrapper types, just emit the field name.
if (IsWrapperType(childField.MessageType))
{
mask.Paths.Add(childFieldName);
}
else if (originalChildValue == null)
{
// New value? Emit the field names for all known fields in the message,
// recursing for nested messages.
AddNewFields(mask, childFieldName, (IMessage) modifiedChildValue);
}
else if (modifiedChildValue == null)
{
// Just emit the deleted field name
mask.Paths.Add(childFieldName);
}
else
{
CompareField(mask, childFieldName, (IMessage) originalChildValue,
(IMessage) modifiedChildValue);
}
}
break;
case FieldType.Group:
throw new NotSupportedException("Groups are not supported in proto3");
default: // Primitives
if (childField.HasPresence)
{
// Presence fields should be handled based on whether the field has
// value.
bool originalChildHasValue = childField.Accessor.HasValue(original);
bool modifiedChildHasValue = childField.Accessor.HasValue(modified);
// Both fields have value, but the values don't match.
if (originalChildHasValue && modifiedChildHasValue &&
!Equals(originalChildValue, modifiedChildValue))
{
mask.Paths.Add(childFieldName);
}
else if (originalChildHasValue ^ modifiedChildHasValue)
{
// Only one of the fields have value.
mask.Paths.Add(childFieldName);
}
}
else if (!Equals(originalChildValue, modifiedChildValue))
{
mask.Paths.Add(childFieldName);
}
break;
}
}
}
}
/// <summary>
/// Gets the field value.
/// </summary>
/// <param name="fieldMaskPath">The field mask path.</param>
/// <param name="entity">The entity to retrieve values from.</param>
/// <returns>The </returns>
/// <exception cref="ArgumentException">Thrown if the path cannot be recursed further.
/// </exception>
public static object GetFieldValue(string fieldMaskPath, IMessage entity)
{
string[] fieldMaskParts = fieldMaskPath.Split('.');
int currentFieldIndex = 0;
IMessage currentEntity = entity;
bool fieldMatchFound = false;
while (currentFieldIndex < fieldMaskParts.Length)
{
fieldMatchFound = false;
if (currentEntity == null)
{
string currentPath = string.Join(".",
fieldMaskParts.Take(currentFieldIndex + 1));
throw new ArgumentException($"Cannot get field value. {currentPath} is null.");
}
var descriptor = currentEntity.Descriptor;
foreach (var childField in descriptor.Fields.InFieldNumberOrder())
{
if (childField.Name != fieldMaskParts[currentFieldIndex])
{
continue;
}
fieldMatchFound = true;
var childValue = childField.Accessor.GetValue(currentEntity);
if (!childField.IsRepeated && childField.FieldType == FieldType.Message &&
childValue is IMessage)
{
// we can recurse.
currentFieldIndex++;
currentEntity = childValue as IMessage;
break;
}
else if (childField.IsRepeated && childValue is IList)
{
if (currentFieldIndex + 1 == fieldMaskParts.Length)
{
return childValue;
}
else
{
string currentPath = string.Join(".",
fieldMaskParts.Take(currentFieldIndex + 1));
throw new ArgumentException($"Cannot retrieve field value. A " +
$"repeated field was encountered after navigating " +
$"{fieldMaskPath} upto {currentPath}.");
}
}
else
{
if (currentFieldIndex + 1 == fieldMaskParts.Length)
{
// we cannot recurse any longer.
return childValue;
}
else
{
string currentPath = string.Join(".",
fieldMaskParts.Take(currentFieldIndex + 1));
throw new ArgumentException($"Cannot retrieve field value. A " +
$"non-IMessage field was encountered after navigating " +
$"{fieldMaskPath} upto {currentPath}.");
}
}
}
if (!fieldMatchFound)
{
string currentPath = string.Join(".",
fieldMaskParts.Take(currentFieldIndex + 1));
throw new ArgumentException($"Cannot retrieve field value. A " +
$"matching field was not found after navigating the " +
$"{fieldMaskPath} upto {currentPath}.");
}
}
return currentEntity;
}
/// <summary>
/// Gets the full name of the field.
/// </summary>
/// <param name="parentFieldName">The parent field name.</param>
/// <param name="field">The field for which full name should be evaluated.</param>
/// <returns>The full name of the field.</returns>
private static string GetFullFieldName(string parentFieldName, FieldDescriptor field) =>
parentFieldName == "" ? field.Name : $"{parentFieldName}.{field.Name}";
/// <summary>
/// Recursively adds field names for a new message. Repeated fields, primitive fields and
/// unpopulated single message fields are included just by name; populated single message
/// fields are processed recursively, only including leaf nodes.
/// </summary>
/// <param name="fieldName">The current field.</param>
/// <param name="mask">The fieldmask that keeps track of changes.</param>
/// <param name="message">The message for which new fieldmasks are generated.</param>
private static void AddNewFields(FieldMask mask, string fieldName, IMessage message)
{
var descriptor = message.Descriptor;
int fieldCount = mask.Paths.Count;
foreach (var field in descriptor.Fields.InFieldNumberOrder())
{
string name = GetFullFieldName(fieldName, field);
object value = field.Accessor.GetValue(message);
if (field.IsRepeated)
{
if (value is IList && (value as IList).Count > 0)
{
// Generate fieldmask for a repeated field only if there's at least one
// element in the list. Also, don't recurse, since fieldmask doesn't
// support index notation.
mask.Paths.Add(name);
}
}
else
{
if (field.FieldType == FieldType.Message)
{
// For single message fields, recurse if there's a value.
if (value != null)
{
AddNewFields(mask, name, (IMessage) value);
}
}
else if (field.HasPresence)
{
// The presence fields should first be checked for HasValue.
if (field.Accessor.HasValue(message))
{
mask.Paths.Add(name);
}
}
else if (IsBasicType(field.FieldType))
{
// Add a field mask only if there is a non-default value.
var defaultValue = GetDefaultValue(field.FieldType);
if (!Equals(defaultValue, value))
{
mask.Paths.Add(name);
}
}
else if (field.FieldType == FieldType.Enum)
{
// Add a field mask only if there is a non-default value.
var defaultValue = System.Enum.ToObject(field.EnumType.ClrType, 0);
if (!Equals(defaultValue, value))
{
mask.Paths.Add(name);
}
}
}
}
if (fieldCount == mask.Paths.Count)
{
// We recursed the whole hierarchy, but added no new fields. This should then be
// treated as an empty submessage.
mask.Paths.Add(fieldName);
}
}
/// <summary>
/// Determines whether a field is basic type or not.
/// </summary>
/// <param name="type">The type.</param>
private static bool IsBasicType(FieldType type)
{
switch (type)
{
case FieldType.Double:
case FieldType.Float:
case FieldType.Int64:
case FieldType.UInt64:
case FieldType.Int32:
case FieldType.Fixed64:
case FieldType.Fixed32:
case FieldType.Bool:
case FieldType.String:
case FieldType.Bytes:
case FieldType.UInt32:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.SInt32:
case FieldType.SInt64:
return true;
default:
return false;
}
}
/// <summary>
/// Gets the default value for a type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The default value.</returns>
private static object GetDefaultValue(FieldType type)
{
switch (type)
{
case FieldType.Double:
case FieldType.Float:
return 0D;
case FieldType.Int64:
case FieldType.UInt64:
case FieldType.Fixed64:
case FieldType.Fixed32:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.SInt64:
return 0L;
case FieldType.Int32:
case FieldType.UInt32:
case FieldType.SInt32:
return 0;
case FieldType.Bool:
return false;
case FieldType.String:
return "";
case FieldType.Bytes:
return ByteString.Empty;
default:
return null;
}
}
/// <summary>
/// Determines whether the specified message descriptor is a wrapper type or not.
/// </summary>
/// <param name="descriptor">The message descriptor.</param>
/// <returns>True if the message descriptor is a wrapper type, false otherwise.</returns>
private static bool IsWrapperType(MessageDescriptor descriptor)
{
return descriptor.File.Package == "google.protobuf" &&
descriptor.File.Name == "google/protobuf/wrappers.proto";
}
}
}
| |
/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.Foundation.Collections;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.AppService;
using Windows.System.Threading;
using Windows.Networking.Sockets;
using System.IO;
using Windows.Storage.Streams;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
namespace WebServerTask
{
public sealed class WebServerBGTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// Associate a cancellation handler with the background task.
taskInstance.Canceled += OnCanceled;
// Get the deferral object from the task instance
_serviceDeferral = taskInstance.GetDeferral();
var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (appService != null &&
appService.Name == "App2AppComService")
{
_appServiceConnection = appService.AppServiceConnection;
_appServiceConnection.RequestReceived += OnRequestReceived;
}
}
private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
var message = args.Request.Message;
string command = message["Command"] as string;
switch (command)
{
case "Initialize":
{
var messageDeferral = args.GetDeferral();
//Set a result to return to the caller
var returnMessage = new ValueSet();
HttpServer server = new HttpServer(8000, _appServiceConnection);
IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
(workItem) =>
{
server.StartServer();
});
returnMessage.Add("Status", "Success");
var responseStatus = await args.Request.SendResponseAsync(returnMessage);
messageDeferral.Complete();
break;
}
case "Quit":
{
//Service was asked to quit. Give us service deferral
//so platform can terminate the background task
_serviceDeferral.Complete();
break;
}
}
}
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
//Clean up and get ready to exit
}
BackgroundTaskDeferral _serviceDeferral;
AppServiceConnection _appServiceConnection;
}
public sealed class HttpServer : IDisposable
{
string offHtmlString = "<html><head><title>Blinky App</title></head><body><form action=\"blinky.html\" method=\"GET\"><input type=\"radio\" name=\"state\" value=\"on\" onclick=\"this.form.submit()\"> On<br><input type=\"radio\" name=\"state\" value=\"off\" checked onclick=\"this.form.submit()\"> Off</form></body></html>";
string onHtmlString = "<html><head><title>Blinky App</title></head><body><form action=\"blinky.html\" method=\"GET\"><input type=\"radio\" name=\"state\" value=\"on\" checked onclick=\"this.form.submit()\"> On<br><input type=\"radio\" name=\"state\" value=\"off\" onclick=\"this.form.submit()\"> Off</form></body></html>";
private const uint BufferSize = 8192;
private int port = 8000;
private readonly StreamSocketListener listener;
private AppServiceConnection appServiceConnection;
public HttpServer(int serverPort, AppServiceConnection _appServiceConnection)
{
listener = new StreamSocketListener();
port = serverPort;
appServiceConnection = _appServiceConnection;
listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
}
public void StartServer()
{
#pragma warning disable CS4014
listener.BindServiceNameAsync(port.ToString());
#pragma warning restore CS4014
}
public void Dispose()
{
listener.Dispose();
}
private async void ProcessRequestAsync(StreamSocket socket)
{
// this works for text only
StringBuilder request = new StringBuilder();
using (IInputStream input = socket.InputStream)
{
byte[] data = new byte[BufferSize];
IBuffer buffer = data.AsBuffer();
uint dataRead = BufferSize;
while (dataRead == BufferSize)
{
await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
dataRead = buffer.Length;
}
}
using (IOutputStream output = socket.OutputStream)
{
string requestMethod = request.ToString().Split('\n')[0];
string[] requestParts = requestMethod.Split(' ');
if (requestParts[0] == "GET")
await WriteResponseAsync(requestParts[1], output);
else
throw new InvalidDataException("HTTP method not supported: "
+ requestParts[0]);
}
}
private async Task WriteResponseAsync(string request, IOutputStream os)
{
// See if the request is for blinky.html, if yes get the new state
string state = "Unspecified";
bool stateChanged = false;
if (request.Contains("blinky.html?state=on"))
{
state = "On";
stateChanged = true;
}
else if (request.Contains("blinky.html?state=off"))
{
state = "Off";
stateChanged = true;
}
if (stateChanged)
{
var updateMessage = new ValueSet();
updateMessage.Add("State", state);
var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
}
string html = state == "On" ? onHtmlString : offHtmlString;
// Show the html
using (Stream resp = os.AsStreamForWrite())
{
// Look in the Data subdirectory of the app package
byte[] bodyArray = Encoding.UTF8.GetBytes(html);
MemoryStream stream = new MemoryStream(bodyArray);
string header = String.Format("HTTP/1.1 200 OK\r\n" +
"Content-Length: {0}\r\n" +
"Connection: close\r\n\r\n",
stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.BackupServices;
using Microsoft.Azure.Management.BackupServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.BackupServices
{
/// <summary>
/// Definition of Container operations for the Azure Backup extension.
/// </summary>
internal partial class ContainerOperations : IServiceOperations<BackupVaultServicesManagementClient>, IContainerOperations
{
/// <summary>
/// Initializes a new instance of the ContainerOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ContainerOperations(BackupVaultServicesManagementClient client)
{
this._client = client;
}
private BackupVaultServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.BackupServices.BackupVaultServicesManagementClient.
/// </summary>
public BackupVaultServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Enable the container reregistration.
/// </summary>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='enableReregistrationRequest'>
/// Required. Enable Reregistration Request.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public async Task<OperationResponse> EnableMarsContainerReregistrationAsync(string containerId, EnableReregistrationRequest enableReregistrationRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (containerId == null)
{
throw new ArgumentNullException("containerId");
}
if (enableReregistrationRequest == null)
{
throw new ArgumentNullException("enableReregistrationRequest");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("containerId", containerId);
tracingParameters.Add("enableReregistrationRequest", enableReregistrationRequest);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "EnableMarsContainerReregistrationAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/backupContainers/";
url = url + Uri.EscapeDataString(containerId);
url = url + "/enableReRegister";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject enableReregistrationRequestValue = new JObject();
requestDoc = enableReregistrationRequestValue;
if (enableReregistrationRequest.ContainerReregistrationState != null)
{
JObject propertiesValue = new JObject();
enableReregistrationRequestValue["properties"] = propertiesValue;
propertiesValue["enableReRegister"] = enableReregistrationRequest.ContainerReregistrationState.EnableReregistration;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Guid operationIdInstance = Guid.Parse(((string)responseDoc));
result.OperationId = operationIdInstance;
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public async Task<ListMarsContainerOperationResponse> ListMarsContainersByTypeAsync(MarsContainerType containerType, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("containerType", containerType);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListMarsContainersByTypeAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/backupContainers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
List<string> odataFilter = new List<string>();
odataFilter.Add("type eq '" + Uri.EscapeDataString(containerType.ToString()) + "'");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ListMarsContainerOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ListMarsContainerOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ListMarsContainerResponse listMarsContainerResponseInstance = new ListMarsContainerResponse();
result.ListMarsContainerResponse = listMarsContainerResponseInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
MarsContainerResponse marsContainerResponseInstance = new MarsContainerResponse();
listMarsContainerResponseInstance.Value.Add(marsContainerResponseInstance);
JToken uniqueNameValue = valueValue["uniqueName"];
if (uniqueNameValue != null && uniqueNameValue.Type != JTokenType.Null)
{
string uniqueNameInstance = ((string)uniqueNameValue);
marsContainerResponseInstance.UniqueName = uniqueNameInstance;
}
JToken containerTypeValue = valueValue["containerType"];
if (containerTypeValue != null && containerTypeValue.Type != JTokenType.Null)
{
string containerTypeInstance = ((string)containerTypeValue);
marsContainerResponseInstance.ContainerType = containerTypeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
MarsContainerProperties propertiesInstance = new MarsContainerProperties();
marsContainerResponseInstance.Properties = propertiesInstance;
JToken containerIdValue = propertiesValue["containerId"];
if (containerIdValue != null && containerIdValue.Type != JTokenType.Null)
{
long containerIdInstance = ((long)containerIdValue);
propertiesInstance.ContainerId = containerIdInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken containerStampIdValue = propertiesValue["containerStampId"];
if (containerStampIdValue != null && containerStampIdValue.Type != JTokenType.Null)
{
Guid containerStampIdInstance = Guid.Parse(((string)containerStampIdValue));
propertiesInstance.ContainerStampId = containerStampIdInstance;
}
JToken containerStampUriValue = propertiesValue["containerStampUri"];
if (containerStampUriValue != null && containerStampUriValue.Type != JTokenType.Null)
{
string containerStampUriInstance = ((string)containerStampUriValue);
propertiesInstance.ContainerStampUri = containerStampUriInstance;
}
JToken canReRegisterValue = propertiesValue["canReRegister"];
if (canReRegisterValue != null && canReRegisterValue.Type != JTokenType.Null)
{
bool canReRegisterInstance = ((bool)canReRegisterValue);
propertiesInstance.CanReRegister = canReRegisterInstance;
}
JToken customerTypeValue = propertiesValue["customerType"];
if (customerTypeValue != null && customerTypeValue.Type != JTokenType.Null)
{
string customerTypeInstance = ((string)customerTypeValue);
propertiesInstance.CustomerType = customerTypeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
marsContainerResponseInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
marsContainerResponseInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
marsContainerResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
listMarsContainerResponseInstance.NextLink = nextLinkInstance;
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
listMarsContainerResponseInstance.Id = idInstance2;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
listMarsContainerResponseInstance.Name = nameInstance2;
}
JToken typeValue2 = responseDoc["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
listMarsContainerResponseInstance.Type = typeInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
customRequestHeaders.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all container based on the given query filter
/// string.
/// </summary>
/// <param name='containerType'>
/// Required. Type of container.
/// </param>
/// <param name='friendlyName'>
/// Required. Friendly name of container.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of Microsoft Azure Recovery Services (MARS) containers.
/// </returns>
public async Task<ListMarsContainerOperationResponse> ListMarsContainersByTypeAndFriendlyNameAsync(MarsContainerType containerType, string friendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (friendlyName == null)
{
throw new ArgumentNullException("friendlyName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("containerType", containerType);
tracingParameters.Add("friendlyName", friendlyName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "ListMarsContainersByTypeAndFriendlyNameAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/backupContainers";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
List<string> odataFilter = new List<string>();
odataFilter.Add("type eq '" + Uri.EscapeDataString(containerType.ToString()) + "'");
odataFilter.Add("friendlyName eq '" + Uri.EscapeDataString(friendlyName) + "'");
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ListMarsContainerOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ListMarsContainerOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ListMarsContainerResponse listMarsContainerResponseInstance = new ListMarsContainerResponse();
result.ListMarsContainerResponse = listMarsContainerResponseInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
MarsContainerResponse marsContainerResponseInstance = new MarsContainerResponse();
listMarsContainerResponseInstance.Value.Add(marsContainerResponseInstance);
JToken uniqueNameValue = valueValue["uniqueName"];
if (uniqueNameValue != null && uniqueNameValue.Type != JTokenType.Null)
{
string uniqueNameInstance = ((string)uniqueNameValue);
marsContainerResponseInstance.UniqueName = uniqueNameInstance;
}
JToken containerTypeValue = valueValue["containerType"];
if (containerTypeValue != null && containerTypeValue.Type != JTokenType.Null)
{
string containerTypeInstance = ((string)containerTypeValue);
marsContainerResponseInstance.ContainerType = containerTypeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
MarsContainerProperties propertiesInstance = new MarsContainerProperties();
marsContainerResponseInstance.Properties = propertiesInstance;
JToken containerIdValue = propertiesValue["containerId"];
if (containerIdValue != null && containerIdValue.Type != JTokenType.Null)
{
long containerIdInstance = ((long)containerIdValue);
propertiesInstance.ContainerId = containerIdInstance;
}
JToken friendlyNameValue = propertiesValue["friendlyName"];
if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null)
{
string friendlyNameInstance = ((string)friendlyNameValue);
propertiesInstance.FriendlyName = friendlyNameInstance;
}
JToken containerStampIdValue = propertiesValue["containerStampId"];
if (containerStampIdValue != null && containerStampIdValue.Type != JTokenType.Null)
{
Guid containerStampIdInstance = Guid.Parse(((string)containerStampIdValue));
propertiesInstance.ContainerStampId = containerStampIdInstance;
}
JToken containerStampUriValue = propertiesValue["containerStampUri"];
if (containerStampUriValue != null && containerStampUriValue.Type != JTokenType.Null)
{
string containerStampUriInstance = ((string)containerStampUriValue);
propertiesInstance.ContainerStampUri = containerStampUriInstance;
}
JToken canReRegisterValue = propertiesValue["canReRegister"];
if (canReRegisterValue != null && canReRegisterValue.Type != JTokenType.Null)
{
bool canReRegisterInstance = ((bool)canReRegisterValue);
propertiesInstance.CanReRegister = canReRegisterInstance;
}
JToken customerTypeValue = propertiesValue["customerType"];
if (customerTypeValue != null && customerTypeValue.Type != JTokenType.Null)
{
string customerTypeInstance = ((string)customerTypeValue);
propertiesInstance.CustomerType = customerTypeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
marsContainerResponseInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
marsContainerResponseInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
marsContainerResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
listMarsContainerResponseInstance.NextLink = nextLinkInstance;
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
listMarsContainerResponseInstance.Id = idInstance2;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
listMarsContainerResponseInstance.Name = nameInstance2;
}
JToken typeValue2 = responseDoc["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
listMarsContainerResponseInstance.Type = typeInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-client-request-id"))
{
customRequestHeaders.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Unregister the container.
/// </summary>
/// <param name='containerId'>
/// Required. MARS container ID.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a Operation Response.
/// </returns>
public async Task<OperationResponse> UnregisterMarsContainerAsync(string containerId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken)
{
// Validate
if (containerId == null)
{
throw new ArgumentNullException("containerId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("containerId", containerId);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
TracingAdapter.Enter(invocationId, this, "UnregisterMarsContainerAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/Subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(this.Client.ResourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(this.Client.ResourceName);
url = url + "/backupContainers/";
url = url + Uri.EscapeDataString(containerId);
url = url + "/UnRegisterContainer";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-03-15");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Guid operationIdInstance = Guid.Parse(((string)responseDoc));
result.OperationId = operationIdInstance;
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.IO;
using System.Reflection;
using System.Text;
using NUnit.Common;
namespace NUnit.ConsoleRunner.Tests
{
using System.Collections.Generic;
using Engine;
using Framework;
[TestFixture]
public class CommandLineTests
{
#region General Tests
[Test]
public void NoInputFiles()
{
ConsoleOptions options = new ConsoleOptions();
Assert.True(options.Validate());
Assert.AreEqual(0, options.InputFiles.Count);
}
//[Test]
//public void AllowForwardSlashDefaultsCorrectly()
//{
// ConsoleOptions options = new ConsoleOptions();
// Assert.AreEqual( Path.DirectorySeparatorChar != '/', options.AllowForwardSlash );
//}
[TestCase("ShowHelp", "help|h")]
[TestCase("StopOnError", "stoponerror")]
[TestCase("WaitBeforeExit", "wait")]
[TestCase("PauseBeforeRun", "pause")]
[TestCase("NoHeader", "noheader|noh")]
[TestCase("RunAsX86", "x86")]
[TestCase("DisposeRunners", "dispose-runners")]
[TestCase("ShadowCopyFiles", "shadowcopy")]
[TestCase("TeamCity", "teamcity")]
public void CanRecognizeBooleanOptions(string propertyName, string pattern)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName);
foreach (string option in prototypes)
{
ConsoleOptions options = new ConsoleOptions("-" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option);
options = new ConsoleOptions("-" + option + "+");
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "+");
options = new ConsoleOptions("-" + option + "-");
Assert.AreEqual(false, (bool)property.GetValue(options, null), "Didn't recognize -" + option + "-");
options = new ConsoleOptions("--" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option);
options = new ConsoleOptions("/" + option);
Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option);
}
}
[TestCase("Include", "include", new string[] { "Short,Fast" }, new string[0])]
[TestCase("Exclude", "exclude", new string[] { "Long" }, new string[0])]
[TestCase("ActiveConfig", "config", new string[] { "Debug" }, new string[0])]
[TestCase("ProcessModel", "process", new string[] { "Single", "Separate", "Multiple" }, new string[] { "JUNK" })]
[TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" }, new string[] { "JUNK" })]
[TestCase("Framework", "framework", new string[] { "net-4.0" }, new string[0])]
[TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])]
[TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])]
[TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])]
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" }, new string[] { "JUNK" })]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })]
public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string option in prototypes)
{
foreach (string value in goodValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
foreach (string value in badValues)
{
string optionPlusValue = string.Format("--{0}:{1}", option, value);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue);
}
}
}
[TestCase("ProcessModel", "process", new string[] { "Single", "Separate", "Multiple" })]
[TestCase("DomainUsage", "domain", new string[] { "None", "Single", "Multiple" })]
[TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })]
[TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })]
public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues)
{
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(string), property.PropertyType);
foreach (string canonicalValue in canonicalValues)
{
string lowercaseValue = canonicalValue.ToLowerInvariant();
string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue);
ConsoleOptions options = new ConsoleOptions(optionPlusValue);
Assert.True(options.Validate(), "Should be valid: " + optionPlusValue);
Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue);
}
}
[TestCase("DefaultTimeout", "timeout")]
[TestCase("RandomSeed", "seed")]
[TestCase("NumWorkers", "workers")]
public void CanRecognizeIntOptions(string propertyName, string pattern)
{
string[] prototypes = pattern.Split('|');
PropertyInfo property = GetPropertyInfo(propertyName);
Assert.AreEqual(typeof(int), property.PropertyType);
foreach (string option in prototypes)
{
ConsoleOptions options = new ConsoleOptions("--" + option + ":42");
Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":text");
}
}
//[TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))]
//public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType)
//{
// string[] prototypes = pattern.Split('|');
// PropertyInfo property = GetPropertyInfo(propertyName);
// Assert.IsNotNull(property, "Property {0} not found", propertyName);
// Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName);
// Assert.AreEqual(enumType, property.PropertyType);
// foreach (string option in prototypes)
// {
// foreach (string name in Enum.GetNames(enumType))
// {
// {
// ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name);
// Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name);
// }
// }
// }
//}
[TestCase("--include")]
[TestCase("--exclude")]
[TestCase("--config")]
[TestCase("--process")]
[TestCase("--domain")]
[TestCase("--framework")]
[TestCase("--timeout")]
//[TestCase("--xml")]
[TestCase("--output")]
[TestCase("--err")]
[TestCase("--work")]
[TestCase("--trace")]
public void MissingValuesAreReported(string option)
{
ConsoleOptions options = new ConsoleOptions(option + "=");
Assert.False(options.Validate(), "Missing value should not be valid");
Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]);
}
[Test]
public void AssemblyName()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count);
Assert.AreEqual("nunit.tests.dll", options.InputFiles[0]);
}
//[Test]
//public void FixtureNamePlusAssemblyIsValid()
//{
// ConsoleOptions options = new ConsoleOptions( "-fixture:NUnit.Tests.AllTests", "nunit.tests.dll" );
// Assert.AreEqual("nunit.tests.dll", options.Parameters[0]);
// Assert.AreEqual("NUnit.Tests.AllTests", options.fixture);
// Assert.IsTrue(options.Validate());
//}
[Test]
public void AssemblyAloneIsValid()
{
ConsoleOptions options = new ConsoleOptions("nunit.tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count, "command line should be valid");
}
[Test]
public void InvalidOption()
{
ConsoleOptions options = new ConsoleOptions("-assembly:nunit.tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(1, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -assembly:nunit.tests.dll", options.ErrorMessages[0]);
}
//[Test]
//public void NoFixtureNameProvided()
//{
// ConsoleOptions options = new ConsoleOptions( "-fixture:", "nunit.tests.dll" );
// Assert.IsFalse(options.Validate());
//}
[Test]
public void InvalidCommandLineParms()
{
ConsoleOptions options = new ConsoleOptions("-garbage:TestFixture", "-assembly:Tests.dll");
Assert.False(options.Validate());
Assert.AreEqual(2, options.ErrorMessages.Count);
Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]);
Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]);
}
#endregion
#region Timeout Option
[Test]
public void TimeoutIsMinusOneIfNoOptionIsProvided()
{
ConsoleOptions options = new ConsoleOptions("tests.dll");
Assert.True(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
[Test]
public void TimeoutThrowsExceptionIfOptionHasNoValue()
{
Assert.Throws<Mono.Options.OptionException>(() => new ConsoleOptions("tests.dll", "-timeout"));
}
[Test]
public void TimeoutParsesIntValueCorrectly()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:5000");
Assert.True(options.Validate());
Assert.AreEqual(5000, options.DefaultTimeout);
}
[Test]
public void TimeoutCausesErrorIfValueIsNotInteger()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-timeout:abc");
Assert.False(options.Validate());
Assert.AreEqual(-1, options.DefaultTimeout);
}
#endregion
#region EngineResult Option
[Test]
public void ResultOptionWithFilePath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ResultOptionWithFilePathAndFormat()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;format=nunit2");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit2", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ResultOptionWithFilePathAndTransform()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml;transform=transform.xslt");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
OutputSpecification spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("user", spec.Format);
Assert.AreEqual("transform.xslt", spec.Transform);
}
[Test]
public void FileNameWithoutResultOptionLooksLikeParameter()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "results.xml");
Assert.True(options.Validate());
Assert.AreEqual(0, options.ErrorMessages.Count);
Assert.AreEqual(2, options.InputFiles.Count);
}
[Test]
public void ResultOptionWithoutFileNameIsInvalid()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:");
Assert.False(options.Validate(), "Should not be valid");
Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected");
}
[Test]
public void ResultOptionMayBeRepeated()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-result:results.xml", "-result:nunit2results.xml;format=nunit2", "-result:myresult.xml;transform=mytransform.xslt");
Assert.True(options.Validate(), "Should be valid");
var specs = options.ResultOutputSpecifications;
Assert.AreEqual(3, specs.Count);
var spec1 = specs[0];
Assert.AreEqual("results.xml", spec1.OutputPath);
Assert.AreEqual("nunit3", spec1.Format);
Assert.Null(spec1.Transform);
var spec2 = specs[1];
Assert.AreEqual("nunit2results.xml", spec2.OutputPath);
Assert.AreEqual("nunit2", spec2.Format);
Assert.Null(spec2.Transform);
var spec3 = specs[2];
Assert.AreEqual("myresult.xml", spec3.OutputPath);
Assert.AreEqual("user", spec3.Format);
Assert.AreEqual("mytransform.xslt", spec3.Transform);
}
[Test]
public void DefaultResultSpecification()
{
var options = new ConsoleOptions("test.dll");
Assert.AreEqual(1, options.ResultOutputSpecifications.Count);
var spec = options.ResultOutputSpecifications[0];
Assert.AreEqual("TestResult.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void NoResultSuppressesDefaultResultSpecification()
{
var options = new ConsoleOptions("test.dll", "-noresult");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
[Test]
public void NoResultSuppressesAllResultSpecifications()
{
var options = new ConsoleOptions("test.dll", "-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2");
Assert.AreEqual(0, options.ResultOutputSpecifications.Count);
}
#endregion
#region Explore Option
[Test]
public void ExploreOptionWithoutPath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore");
Assert.True(options.Validate());
Assert.True(options.Explore);
}
[Test]
public void ExploreOptionWithFilePath()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("nunit3", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathAndFormat()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;format=cases");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("cases", spec.Format);
Assert.Null(spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathAndTransform()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore:results.xml;transform=myreport.xslt");
Assert.True(options.Validate());
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.True(options.Explore);
OutputSpecification spec = options.ExploreOutputSpecifications[0];
Assert.AreEqual("results.xml", spec.OutputPath);
Assert.AreEqual("user", spec.Format);
Assert.AreEqual("myreport.xslt", spec.Transform);
}
[Test]
public void ExploreOptionWithFilePathUsingEqualSign()
{
ConsoleOptions options = new ConsoleOptions("tests.dll", "-explore=C:/nunit/tests/bin/Debug/console-test.xml");
Assert.True(options.Validate());
Assert.True(options.Explore);
Assert.AreEqual(1, options.InputFiles.Count, "assembly should be set");
Assert.AreEqual("tests.dll", options.InputFiles[0]);
Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath);
}
[Test]
[TestCase(true, null, true)]
[TestCase(false, null, false)]
[TestCase(true, false, true)]
[TestCase(false, false, false)]
[TestCase(true, true, true)]
[TestCase(false, true, true)]
public void ShouldSetTeamCityFlagAccordingToArgsAndDefauls(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity)
{
// Given
List<string> args = new List<string> { "tests.dll" };
if (hasTeamcityInCmd)
{
args.Add("--teamcity");
}
ConsoleOptions options;
if (defaultTeamcity.HasValue)
{
options = new ConsoleOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray());
}
else
{
options = new ConsoleOptions(args.ToArray());
}
// When
var actualTeamCity = options.TeamCity;
// Then
Assert.AreEqual(actualTeamCity, expectedTeamCity);
}
#endregion
#region Helper Methods
private static FieldInfo GetFieldInfo(string fieldName)
{
FieldInfo field = typeof(ConsoleOptions).GetField(fieldName);
Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName);
return field;
}
private static PropertyInfo GetPropertyInfo(string propertyName)
{
PropertyInfo property = typeof(ConsoleOptions).GetProperty(propertyName);
Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName);
return property;
}
#endregion
internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider
{
public DefaultOptionsProviderStub(bool teamCity)
{
TeamCity = teamCity;
}
public bool TeamCity { get; private set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Runtime
{
// AsyncResult starts acquired; Complete releases.
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, SupportsAsync = true, ReleaseMethod = "Complete")]
internal abstract class AsyncResult : IAsyncResult
{
private static AsyncCallback s_asyncCompletionWrapperCallback;
private AsyncCallback _callback;
private bool _completedSynchronously;
private bool _endCalled;
private Exception _exception;
private bool _isCompleted;
private AsyncCompletion _nextAsyncCompletion;
private object _state;
private Action _beforePrepareAsyncCompletionAction;
private Func<IAsyncResult, bool> _checkSyncValidationFunc;
[Fx.Tag.SynchronizationObject]
private ManualResetEvent _manualResetEvent;
[Fx.Tag.SynchronizationObject(Blocking = false)]
private object _thisLock;
protected AsyncResult(AsyncCallback callback, object state)
{
_callback = callback;
_state = state;
_thisLock = new object();
}
public object AsyncState
{
get
{
return _state;
}
}
public WaitHandle AsyncWaitHandle
{
get
{
if (_manualResetEvent != null)
{
return _manualResetEvent;
}
lock (ThisLock)
{
if (_manualResetEvent == null)
{
_manualResetEvent = new ManualResetEvent(_isCompleted);
}
}
return _manualResetEvent;
}
}
public bool CompletedSynchronously
{
get
{
return _completedSynchronously;
}
}
public bool HasCallback
{
get
{
return _callback != null;
}
}
public bool IsCompleted
{
get
{
return _isCompleted;
}
}
// used in conjunction with PrepareAsyncCompletion to allow for finally blocks
protected Action<AsyncResult, Exception> OnCompleting { get; set; }
private object ThisLock
{
get
{
return _thisLock;
}
}
// subclasses like TraceAsyncResult can use this to wrap the callback functionality in a scope
protected Action<AsyncCallback, IAsyncResult> VirtualCallback
{
get;
set;
}
protected void Complete(bool completedSynchronously)
{
if (_isCompleted)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice(GetType())));
}
_completedSynchronously = completedSynchronously;
if (OnCompleting != null)
{
// Allow exception replacement, like a catch/throw pattern.
try
{
OnCompleting(this, _exception);
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
_exception = exception;
}
}
if (completedSynchronously)
{
// If we completedSynchronously, then there's no chance that the manualResetEvent was created so
// we don't need to worry about a race condition.
Fx.Assert(_manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult.");
_isCompleted = true;
}
else
{
lock (ThisLock)
{
_isCompleted = true;
if (_manualResetEvent != null)
{
_manualResetEvent.Set();
}
}
}
if (_callback != null)
{
try
{
if (VirtualCallback != null)
{
VirtualCallback(_callback, this);
}
else
{
_callback(this);
}
}
#pragma warning disable 1634
#pragma warning suppress 56500 // transferring exception to another thread
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw Fx.Exception.AsError(new CallbackException(InternalSR.AsyncCallbackThrewException, e));
}
#pragma warning restore 1634
}
}
protected void Complete(bool completedSynchronously, Exception exception)
{
_exception = exception;
Complete(completedSynchronously);
}
private static void AsyncCompletionWrapperCallback(IAsyncResult result)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
if (result.CompletedSynchronously)
{
return;
}
AsyncResult thisPtr = (AsyncResult)result.AsyncState;
if (!thisPtr.OnContinueAsyncCompletion(result))
{
return;
}
AsyncCompletion callback = thisPtr.GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult(result);
}
bool completeSelf = false;
Exception completionException = null;
try
{
completeSelf = callback(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
thisPtr.Complete(false, completionException);
}
}
// Note: this should be only derived by the TransactedAsyncResult
protected virtual bool OnContinueAsyncCompletion(IAsyncResult result)
{
return true;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction)
{
_beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction;
}
// Note: this should be used only by the TransactedAsyncResult
protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc)
{
_checkSyncValidationFunc = checkSyncValidationFunc;
}
protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback)
{
if (_beforePrepareAsyncCompletionAction != null)
{
_beforePrepareAsyncCompletionAction();
}
_nextAsyncCompletion = callback;
if (AsyncResult.s_asyncCompletionWrapperCallback == null)
{
AsyncResult.s_asyncCompletionWrapperCallback = Fx.ThunkCallback(new AsyncCallback(AsyncCompletionWrapperCallback));
}
return AsyncResult.s_asyncCompletionWrapperCallback;
}
protected bool CheckSyncContinue(IAsyncResult result)
{
AsyncCompletion dummy;
return TryContinueHelper(result, out dummy);
}
protected bool SyncContinue(IAsyncResult result)
{
AsyncCompletion callback;
if (TryContinueHelper(result, out callback))
{
return callback(result);
}
else
{
return false;
}
}
private bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback)
{
if (result == null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult));
}
callback = null;
if (_checkSyncValidationFunc != null)
{
if (!_checkSyncValidationFunc(result))
{
return false;
}
}
else if (!result.CompletedSynchronously)
{
return false;
}
callback = GetNextCompletion();
if (callback == null)
{
ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion).");
}
return true;
}
private AsyncCompletion GetNextCompletion()
{
AsyncCompletion result = _nextAsyncCompletion;
_nextAsyncCompletion = null;
return result;
}
protected static void ThrowInvalidAsyncResult(IAsyncResult result)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType())));
}
protected static void ThrowInvalidAsyncResult(string debugText)
{
string message = InternalSR.InvalidAsyncResultImplementationGeneric;
if (debugText != null)
{
#if DEBUG
message += " " + debugText;
#endif
}
throw Fx.Exception.AsError(new InvalidOperationException(message));
}
[Fx.Tag.Blocking(Conditional = "!asyncResult.isCompleted")]
protected static TAsyncResult End<TAsyncResult>(IAsyncResult result)
where TAsyncResult : AsyncResult
{
if (result == null)
{
throw Fx.Exception.ArgumentNull("result");
}
TAsyncResult asyncResult = result as TAsyncResult;
if (asyncResult == null)
{
throw Fx.Exception.Argument("result", InternalSR.InvalidAsyncResult);
}
if (asyncResult._endCalled)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultAlreadyEnded));
}
asyncResult._endCalled = true;
if (!asyncResult._isCompleted)
{
asyncResult.AsyncWaitHandle.WaitOne();
}
if (asyncResult._manualResetEvent != null)
{
asyncResult._manualResetEvent.Dispose();
}
if (asyncResult._exception != null)
{
throw Fx.Exception.AsError(asyncResult._exception);
}
return asyncResult;
}
// can be utilized by subclasses to write core completion code for both the sync and async paths
// in one location, signalling chainable synchronous completion with the boolean result,
// and leveraging PrepareAsyncCompletion for conversion to an AsyncCallback.
// NOTE: requires that "this" is passed in as the state object to the asynchronous sub-call being used with a completion routine.
protected delegate bool AsyncCompletion(IAsyncResult result);
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace gView.Framework.Offline.UI
{
[DefaultProperty("BlockSize")]
public partial class ProgressDisk : UserControl
{
private GraphicsPath bkGroundPath1 = new GraphicsPath();
private GraphicsPath bkGroundPath2 = new GraphicsPath();
private GraphicsPath valuePath = new GraphicsPath();
private GraphicsPath freGroundPath = new GraphicsPath();
private int sliceCount;
private int value;
[DefaultValue(0)]
public int Value
{
get { return value; }
set
{
this.value = value;
Render();
}
}
private Color backGrndColor = Color.White;
[DefaultValue(typeof(Color), "White")]
public Color BackGroundColor
{
get { return backGrndColor; }
set
{
backGrndColor = value;
Render();
}
}
private Color activeforeColor1 = Color.Blue;
[DefaultValue(typeof(Color), "Blue")]
public Color ActiveForeColor1
{
get { return activeforeColor1; }
set
{
activeforeColor1 = value;
Render();
}
}
private Color activeforeColor2 = Color.LightBlue;
[DefaultValue(typeof(Color), "LightBlue")]
public Color ActiveForeColor2
{
get { return activeforeColor2; }
set
{
activeforeColor2 = value;
Render();
}
}
private Color inactiveforeColor1 = Color.Green;
[DefaultValue(typeof(Color), "Green")]
public Color InactiveForeColor1
{
get { return inactiveforeColor1; }
set
{
inactiveforeColor1 = value;
Render();
}
}
private Color inactiveforeColor2 = Color.LightGreen;
[DefaultValue(typeof(Color), "LightGreen")]
public Color InactiveForeColor2
{
get { return inactiveforeColor2; }
set
{
inactiveforeColor2 = value;
Render();
}
}
private int size = 50;
[DefaultValue(50)]
public int SquareSize
{
get { return size; }
set
{
size = value;
Size = new Size(size, size);
}
}
private float blockRatio = .4f;
private BlockSize bs = BlockSize.Small;
[DefaultValue(typeof(BlockSize), "Small")]
public BlockSize BlockSize
{
get { return bs; }
set
{
bs = value;
switch (bs)
{
case BlockSize.XSmall:
blockRatio = 0.49f;
break;
case BlockSize.Small:
blockRatio = 0.4f;
break;
case BlockSize.Medium:
blockRatio = 0.3f;
break;
case BlockSize.Large:
blockRatio = 0.2f;
break;
case BlockSize.XLarge:
blockRatio = 0.1f;
break;
case BlockSize.XXLarge:
blockRatio = 0.01f;
break;
default:
break;
}
}
}
[DefaultValue(12)]
public int SliceCount
{
get { return sliceCount; }
set { sliceCount = value; }
}
public ProgressDisk()
{
InitializeComponent();
// CheckForIllegalCrossThreadCalls = false;
Render();
}
private Region region = new Region();
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
region = new Region(ClientRectangle);
if (backGrndColor == Color.Transparent)
{
region.Exclude(bkGroundPath2);
Region = region;
}
e.Graphics.FillPath(new SolidBrush(backGrndColor), bkGroundPath1);
e.Graphics.FillPath(
new LinearGradientBrush(new Rectangle(0, 0, size, size), inactiveforeColor1, inactiveforeColor2,
value * 360 / 12, true), valuePath);
e.Graphics.FillPath(
new LinearGradientBrush(new Rectangle(0, 0, size, size), activeforeColor1, activeforeColor2,
value * 360 / 12, true), freGroundPath);
e.Graphics.FillPath(new SolidBrush(backGrndColor), bkGroundPath2);
base.OnPaint(e);
}
private void Render()
{
// bkGroundPath1 = new GraphicsPath();
// bkGroundPath2 = new GraphicsPath();
// valuePath = new GraphicsPath();
// freGroundPath = new GraphicsPath();
bkGroundPath1.Reset();
bkGroundPath2.Reset();
valuePath.Reset();
freGroundPath.Reset();
bkGroundPath1.AddPie(new Rectangle(0, 0, size, size), 0, 360);
//just in case...
if (sliceCount == 0)
{
sliceCount = 12;
}
float sliceAngle = 360 / sliceCount;
float sweepAngle = sliceAngle - 5;
for (int i = 0; i < sliceCount; i++)
{
if (value != i)
{
valuePath.AddPie(0, 0, size, size, i * sliceAngle, sweepAngle);
}
}
bkGroundPath2.AddPie(
(size / 2 - size * blockRatio), (size / 2 - size * blockRatio),
(blockRatio * 2 * size), (blockRatio * 2 * size), 0, 360);
freGroundPath.AddPie(new Rectangle(0, 0, size, size), value * sliceAngle, sweepAngle);
Invalidate();
}
protected override void OnSizeChanged(EventArgs e)
{
size = Math.Max(Width, Height);
Size = new Size(size, size);
Render();
base.OnSizeChanged(e);
}
protected override void OnResize(EventArgs e)
{
size = Math.Max(Width, Height);
Size = new Size(size, size);
Render();
base.OnResize(e);
}
public void Start(int interval)
{
timer1.Interval = interval;
timer1.Start();
}
public void Stop()
{
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Value = this.Value + 1;
}
}
public enum BlockSize
{
XSmall,
Small,
Medium,
Large,
XLarge,
XXLarge
}
}
| |
using System.Collections.Generic;
namespace EasyNetQ;
/// <summary>
/// Allows subscription configuration to be fluently extended without adding overloads
///
/// e.g.
/// x => x.WithTopic("*.brighton")
/// </summary>
public interface ISubscriptionConfiguration
{
/// <summary>
/// Adds a topic for the queue binding
/// </summary>
/// <param name="topic">The topic to add</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithTopic(string topic);
/// <summary>
/// Configures the queue as autoDelete or not. If set, the queue is deleted when all consumers have finished using it.
/// </summary>
/// <param name="autoDelete">Queue's durability flag</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithAutoDelete(bool autoDelete = true);
/// <summary>
/// Configures the queue's durability
/// </summary>
/// <param name="durable">Queue's durability flag</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithDurable(bool durable = true);
/// <summary>
/// Configures the consumer's priority
/// </summary>
/// <param name="priority">Consumer's priority value</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithPriority(int priority);
/// <summary>
/// Configures the consumer's prefetch count
/// </summary>
/// <param name="prefetchCount">Consumer's prefetch count value</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithPrefetchCount(ushort prefetchCount);
/// <summary>
/// Expiry time can be set for a given queue by setting the x-expires argument to queue.declare, or by setting the expires policy.
/// This controls for how long a queue can be unused before it is automatically deleted.
/// Unused means the queue has no consumers, the queue has not been redeclared, and basic.get has not been invoked for a duration of at least the expiration period.
/// This can be used, for example, for RPC-style reply queues, where many queues can be created which may never be drained.
/// The server guarantees that the queue will be deleted, if unused for at least the expiration period.
/// No guarantee is given as to how promptly the queue will be removed after the expiration period has elapsed.
/// Leases of durable queues restart when the server restarts.
/// </summary>
/// <param name="expires">The value of the x-expires argument or expires policy describes the expiration period in milliseconds and is subject to the same constraints as x-message-ttl and cannot be zero. Thus a value of 1000 means a queue which is unused for 1 second will be deleted.</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithExpires(int expires);
/// <summary>
/// Configures the consumer's to be exclusive
/// </summary>
/// <param name="isExclusive">Consumer's exclusive flag</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration AsExclusive(bool isExclusive = true);
/// <summary>
/// Configures the queue's maxPriority
/// </summary>
/// <param name="priority">Queue's maxPriority value</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithMaxPriority(byte priority);
/// <summary>
/// Sets the queue name
/// </summary>
/// <param name="queueName">The queue name</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithQueueName(string queueName);
/// <summary>
/// Sets the maximum number of ready messages that may exist on the queue.
/// Messages will be dropped or dead-lettered from the front of the queue to make room for new messages once the limit is reached.
/// </summary>
/// <param name="maxLength">The maximum number of ready messages that may exist on the queue.</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithMaxLength(int maxLength);
/// <summary>
/// Sets the maximum size of the queue in bytes.
/// Messages will be dropped or dead-lettered from the front of the queue to make room for new messages once the limit is reached
/// </summary>
/// <param name="maxLengthBytes">The maximum size of the queue in bytes.</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithMaxLengthBytes(int maxLengthBytes);
/// <summary>
/// Sets the queue mode. Valid modes are "default" and "lazy". Works with RabbitMQ version 3.6+.
/// </summary>
/// <param name="queueMode">Desired queue mode.</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithQueueMode(string queueMode = QueueMode.Default);
/// <summary>
/// Sets the queue type. Valid types are "classic" and "quorum". Works with RabbitMQ version 3.8+.
/// </summary>
/// <param name="queueType">Desired queue type.</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithQueueType(string queueType = QueueType.Classic);
/// <summary>
/// Sets type of the exchange used for subscription.
/// </summary>
/// <param name="exchangeType">The type to set</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithExchangeType(string exchangeType);
/// <summary>
/// Sets alternate exchange of the exchange used for subscription.
/// </summary>
/// <param name="alternateExchange">The alternate exchange to set</param>
/// <returns>Returns a reference to itself</returns>
ISubscriptionConfiguration WithAlternateExchange(string alternateExchange);
}
internal class SubscriptionConfiguration : ISubscriptionConfiguration
{
public IList<string> Topics { get; }
public bool AutoDelete { get; private set; }
public int Priority { get; private set; }
public ushort PrefetchCount { get; private set; }
public int? Expires { get; private set; }
public bool IsExclusive { get; private set; }
public byte? MaxPriority { get; private set; }
public bool Durable { get; private set; }
public string QueueName { get; private set; }
public int? MaxLength { get; private set; }
public int? MaxLengthBytes { get; private set; }
public string QueueMode { get; private set; }
public string QueueType { get; private set; }
public string ExchangeType { get; private set; } = Topology.ExchangeType.Topic;
public string AlternateExchange { get; private set; }
public SubscriptionConfiguration(ushort defaultPrefetchCount)
{
Topics = new List<string>();
AutoDelete = false;
Priority = 0;
PrefetchCount = defaultPrefetchCount;
IsExclusive = false;
Durable = true;
}
public ISubscriptionConfiguration WithTopic(string topic)
{
if (!string.IsNullOrWhiteSpace(topic))
Topics.Add(topic);
return this;
}
public ISubscriptionConfiguration WithAutoDelete(bool autoDelete = true)
{
AutoDelete = autoDelete;
return this;
}
public ISubscriptionConfiguration WithDurable(bool durable = true)
{
Durable = durable;
return this;
}
public ISubscriptionConfiguration WithPriority(int priority)
{
Priority = priority;
return this;
}
public ISubscriptionConfiguration WithPrefetchCount(ushort prefetchCount)
{
PrefetchCount = prefetchCount;
return this;
}
public ISubscriptionConfiguration WithExpires(int expires)
{
Expires = expires;
return this;
}
public ISubscriptionConfiguration AsExclusive(bool isExclusive = true)
{
IsExclusive = isExclusive;
return this;
}
public ISubscriptionConfiguration WithMaxPriority(byte priority)
{
MaxPriority = priority;
return this;
}
public ISubscriptionConfiguration WithQueueName(string queueName)
{
QueueName = queueName;
return this;
}
public ISubscriptionConfiguration WithMaxLength(int maxLength)
{
MaxLength = maxLength;
return this;
}
public ISubscriptionConfiguration WithMaxLengthBytes(int maxLengthBytes)
{
MaxLengthBytes = maxLengthBytes;
return this;
}
public ISubscriptionConfiguration WithQueueMode(string queueMode = EasyNetQ.QueueMode.Default)
{
QueueMode = queueMode;
return this;
}
public ISubscriptionConfiguration WithQueueType(string queueType = EasyNetQ.QueueType.Classic)
{
QueueType = queueType;
return this;
}
public ISubscriptionConfiguration WithExchangeType(string exchangeType)
{
ExchangeType = exchangeType;
return this;
}
public ISubscriptionConfiguration WithAlternateExchange(string alternateExchange)
{
AlternateExchange = alternateExchange;
return this;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Xsl.XsltOld
{
using System;
using System.Diagnostics;
using System.Xml;
using System.Text;
using System.Collections;
using System.Globalization;
internal abstract class SequentialOutput : RecordOutput
{
private const char s_Colon = ':';
private const char s_GreaterThan = '>';
private const char s_LessThan = '<';
private const char s_Space = ' ';
private const char s_Quote = '\"';
private const char s_Semicolon = ';';
private const char s_NewLine = '\n';
private const char s_Return = '\r';
private const char s_Ampersand = '&';
private const string s_LessThanQuestion = "<?";
private const string s_QuestionGreaterThan = "?>";
private const string s_LessThanSlash = "</";
private const string s_SlashGreaterThan = " />";
private const string s_EqualQuote = "=\"";
private const string s_DocType = "<!DOCTYPE ";
private const string s_CommentBegin = "<!--";
private const string s_CommentEnd = "-->";
private const string s_CDataBegin = "<![CDATA[";
private const string s_CDataEnd = "]]>";
private const string s_VersionAll = " version=\"1.0\"";
private const string s_Standalone = " standalone=\"";
private const string s_EncodingStart = " encoding=\"";
private const string s_Public = "PUBLIC ";
private const string s_System = "SYSTEM ";
private const string s_Html = "html";
private const string s_QuoteSpace = "\" ";
private const string s_CDataSplit = "]]]]><![CDATA[>";
private const string s_EnLessThan = "<";
private const string s_EnGreaterThan = ">";
private const string s_EnAmpersand = "&";
private const string s_EnQuote = """;
private const string s_EnNewLine = "
";
private const string s_EnReturn = "
";
private const string s_EndOfLine = "\r\n";
private static char[] s_TextValueFind = new char[] { s_Ampersand, s_GreaterThan, s_LessThan };
private static string[] s_TextValueReplace = new string[] { s_EnAmpersand, s_EnGreaterThan, s_EnLessThan };
private static char[] s_XmlAttributeValueFind = new char[] { s_Ampersand, s_GreaterThan, s_LessThan, s_Quote, s_NewLine, s_Return };
private static string[] s_XmlAttributeValueReplace = new string[] { s_EnAmpersand, s_EnGreaterThan, s_EnLessThan, s_EnQuote, s_EnNewLine, s_EnReturn };
// Instance members
private Processor _processor;
protected Encoding encoding;
private ArrayList _outputCache;
private bool _firstLine = true;
private bool _secondRoot;
// Cached Output propertes:
private XsltOutput _output;
private bool _isHtmlOutput;
private bool _isXmlOutput;
private Hashtable _cdataElements;
private bool _indentOutput;
private bool _outputDoctype;
private bool _outputXmlDecl;
private bool _omitXmlDeclCalled;
// Uri Escaping:
private byte[] _byteBuffer;
private Encoding _utf8Encoding;
private XmlCharType _xmlCharType = XmlCharType.Instance;
private void CacheOuptutProps(XsltOutput output)
{
_output = output;
_isXmlOutput = _output.Method == XsltOutput.OutputMethod.Xml;
_isHtmlOutput = _output.Method == XsltOutput.OutputMethod.Html;
_cdataElements = _output.CDataElements;
_indentOutput = _output.Indent;
_outputDoctype = _output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null);
_outputXmlDecl = _isXmlOutput && !_output.OmitXmlDeclaration && !_omitXmlDeclCalled;
}
//
// Constructor
//
internal SequentialOutput(Processor processor)
{
_processor = processor;
CacheOuptutProps(processor.Output);
}
public void OmitXmlDecl()
{
_omitXmlDeclCalled = true;
_outputXmlDecl = false;
}
//
// Particular outputs
//
private void WriteStartElement(RecordBuilder record)
{
Debug.Assert(record.MainNode.NodeType == XmlNodeType.Element);
BuilderInfo mainNode = record.MainNode;
HtmlElementProps htmlProps = null;
if (_isHtmlOutput)
{
if (mainNode.Prefix.Length == 0)
{
htmlProps = mainNode.htmlProps;
if (htmlProps == null && mainNode.search)
{
htmlProps = HtmlElementProps.GetProps(mainNode.LocalName);
}
record.Manager.CurrentElementScope.HtmlElementProps = htmlProps;
mainNode.IsEmptyTag = false;
}
}
else if (_isXmlOutput)
{
if (mainNode.Depth == 0)
{
if (
_secondRoot && (
_output.DoctypeSystem != null ||
_output.Standalone
)
)
{
throw XsltException.Create(SR.Xslt_MultipleRoots);
}
_secondRoot = true;
}
}
if (_outputDoctype)
{
WriteDoctype(mainNode);
_outputDoctype = false;
}
if (_cdataElements != null && _cdataElements.Contains(new XmlQualifiedName(mainNode.LocalName, mainNode.NamespaceURI)) && _isXmlOutput)
{
record.Manager.CurrentElementScope.ToCData = true;
}
Indent(record);
Write(s_LessThan);
WriteName(mainNode.Prefix, mainNode.LocalName);
WriteAttributes(record.AttributeList, record.AttributeCount, htmlProps);
if (mainNode.IsEmptyTag)
{
Debug.Assert(!_isHtmlOutput || mainNode.Prefix != null, "Html can't have abreviated elements");
Write(s_SlashGreaterThan);
}
else
{
Write(s_GreaterThan);
}
if (htmlProps != null && htmlProps.Head)
{
mainNode.Depth++;
Indent(record);
mainNode.Depth--;
Write("<META http-equiv=\"Content-Type\" content=\"");
Write(_output.MediaType);
Write("; charset=");
Write(this.encoding.WebName);
Write("\">");
}
}
private void WriteTextNode(RecordBuilder record)
{
BuilderInfo mainNode = record.MainNode;
OutputScope scope = record.Manager.CurrentElementScope;
scope.Mixed = true;
if (scope.HtmlElementProps != null && scope.HtmlElementProps.NoEntities)
{
// script or stile
Write(mainNode.Value);
}
else if (scope.ToCData)
{
WriteCDataSection(mainNode.Value);
}
else
{
WriteTextNode(mainNode);
}
}
private void WriteTextNode(BuilderInfo node)
{
for (int i = 0; i < node.TextInfoCount; i++)
{
string text = node.TextInfo[i];
if (text == null)
{ // disableEscaping marker
i++;
Debug.Assert(i < node.TextInfoCount, "disableEscaping marker can't be last TextInfo record");
Write(node.TextInfo[i]);
}
else
{
WriteWithReplace(text, s_TextValueFind, s_TextValueReplace);
}
}
}
private void WriteCDataSection(string value)
{
Write(s_CDataBegin);
WriteCData(value);
Write(s_CDataEnd);
}
private void WriteDoctype(BuilderInfo mainNode)
{
Debug.Assert(_outputDoctype == true, "It supposed to check this condition before actual call");
Debug.Assert(_output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null), "We set outputDoctype == true only if");
Indent(0);
Write(s_DocType);
if (_isXmlOutput)
{
WriteName(mainNode.Prefix, mainNode.LocalName);
}
else
{
WriteName(string.Empty, "html");
}
Write(s_Space);
if (_output.DoctypePublic != null)
{
Write(s_Public);
Write(s_Quote);
Write(_output.DoctypePublic);
Write(s_QuoteSpace);
}
else
{
Write(s_System);
}
if (_output.DoctypeSystem != null)
{
Write(s_Quote);
Write(_output.DoctypeSystem);
Write(s_Quote);
}
Write(s_GreaterThan);
}
private void WriteXmlDeclaration()
{
Debug.Assert(_outputXmlDecl == true, "It supposed to check this condition before actual call");
Debug.Assert(_isXmlOutput && !_output.OmitXmlDeclaration, "We set outputXmlDecl == true only if");
_outputXmlDecl = false;
Indent(0);
Write(s_LessThanQuestion);
WriteName(string.Empty, "xml");
Write(s_VersionAll);
if (this.encoding != null)
{
Write(s_EncodingStart);
Write(this.encoding.WebName);
Write(s_Quote);
}
if (_output.HasStandalone)
{
Write(s_Standalone);
Write(_output.Standalone ? "yes" : "no");
Write(s_Quote);
}
Write(s_QuestionGreaterThan);
}
private void WriteProcessingInstruction(RecordBuilder record)
{
Indent(record);
WriteProcessingInstruction(record.MainNode);
}
private void WriteProcessingInstruction(BuilderInfo node)
{
Write(s_LessThanQuestion);
WriteName(node.Prefix, node.LocalName);
Write(s_Space);
Write(node.Value);
if (_isHtmlOutput)
{
Write(s_GreaterThan);
}
else
{
Write(s_QuestionGreaterThan);
}
}
private void WriteEndElement(RecordBuilder record)
{
BuilderInfo node = record.MainNode;
HtmlElementProps htmlProps = record.Manager.CurrentElementScope.HtmlElementProps;
if (htmlProps != null && htmlProps.Empty)
{
return;
}
Indent(record);
Write(s_LessThanSlash);
WriteName(record.MainNode.Prefix, record.MainNode.LocalName);
Write(s_GreaterThan);
}
//
// RecordOutput interface method implementation
//
public Processor.OutputResult RecordDone(RecordBuilder record)
{
if (_output.Method == XsltOutput.OutputMethod.Unknown)
{
if (!DecideDefaultOutput(record.MainNode))
{
CacheRecord(record);
}
else
{
OutputCachedRecords();
OutputRecord(record);
}
}
else
{
OutputRecord(record);
}
record.Reset();
return Processor.OutputResult.Continue;
}
public void TheEnd()
{
OutputCachedRecords();
Close();
}
private bool DecideDefaultOutput(BuilderInfo node)
{
XsltOutput.OutputMethod method = XsltOutput.OutputMethod.Xml;
switch (node.NodeType)
{
case XmlNodeType.Element:
if (node.NamespaceURI.Length == 0 && String.Compare("html", node.LocalName, StringComparison.OrdinalIgnoreCase) == 0)
{
method = XsltOutput.OutputMethod.Html;
}
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (_xmlCharType.IsOnlyWhitespace(node.Value))
{
return false;
}
method = XsltOutput.OutputMethod.Xml;
break;
default:
return false;
}
if (_processor.SetDefaultOutput(method))
{
CacheOuptutProps(_processor.Output);
}
return true;
}
private void CacheRecord(RecordBuilder record)
{
if (_outputCache == null)
{
_outputCache = new ArrayList();
}
_outputCache.Add(record.MainNode.Clone());
}
private void OutputCachedRecords()
{
if (_outputCache == null)
{
return;
}
for (int record = 0; record < _outputCache.Count; record++)
{
Debug.Assert(_outputCache[record] is BuilderInfo);
BuilderInfo info = (BuilderInfo)_outputCache[record];
OutputRecord(info);
}
_outputCache = null;
}
private void OutputRecord(RecordBuilder record)
{
BuilderInfo mainNode = record.MainNode;
if (_outputXmlDecl)
{
WriteXmlDeclaration();
}
switch (mainNode.NodeType)
{
case XmlNodeType.Element:
WriteStartElement(record);
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
WriteTextNode(record);
break;
case XmlNodeType.CDATA:
Debug.Fail("Should never get here");
break;
case XmlNodeType.EntityReference:
Write(s_Ampersand);
WriteName(mainNode.Prefix, mainNode.LocalName);
Write(s_Semicolon);
break;
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(record);
break;
case XmlNodeType.Comment:
Indent(record);
Write(s_CommentBegin);
Write(mainNode.Value);
Write(s_CommentEnd);
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
Write(mainNode.Value);
break;
case XmlNodeType.EndElement:
WriteEndElement(record);
break;
default:
break;
}
}
private void OutputRecord(BuilderInfo node)
{
if (_outputXmlDecl)
{
WriteXmlDeclaration();
}
Indent(0); // we can have only top level stuff here
switch (node.NodeType)
{
case XmlNodeType.Element:
Debug.Fail("Should never get here");
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
WriteTextNode(node);
break;
case XmlNodeType.CDATA:
Debug.Fail("Should never get here");
break;
case XmlNodeType.EntityReference:
Write(s_Ampersand);
WriteName(node.Prefix, node.LocalName);
Write(s_Semicolon);
break;
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(node);
break;
case XmlNodeType.Comment:
Write(s_CommentBegin);
Write(node.Value);
Write(s_CommentEnd);
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
Write(node.Value);
break;
case XmlNodeType.EndElement:
Debug.Fail("Should never get here");
break;
default:
break;
}
}
//
// Internal helpers
//
private void WriteName(string prefix, string name)
{
if (prefix != null && prefix.Length > 0)
{
Write(prefix);
if (name != null && name.Length > 0)
{
Write(s_Colon);
}
else
{
return;
}
}
Write(name);
}
private void WriteXmlAttributeValue(string value)
{
Debug.Assert(value != null);
WriteWithReplace(value, s_XmlAttributeValueFind, s_XmlAttributeValueReplace);
}
private void WriteHtmlAttributeValue(string value)
{
Debug.Assert(value != null);
int length = value.Length;
int i = 0;
while (i < length)
{
char ch = value[i];
i++;
switch (ch)
{
case '&':
if (i != length && value[i] == '{')
{ // &{ hasn't to be encoded in HTML output.
Write(ch);
}
else
{
Write(s_EnAmpersand);
}
break;
case '"':
Write(s_EnQuote);
break;
default:
Write(ch);
break;
}
}
}
private void WriteHtmlUri(string value)
{
Debug.Assert(value != null);
Debug.Assert(_isHtmlOutput);
int length = value.Length;
int i = 0;
while (i < length)
{
char ch = value[i];
i++;
switch (ch)
{
case '&':
if (i != length && value[i] == '{')
{ // &{ hasn't to be encoded in HTML output.
Write(ch);
}
else
{
Write(s_EnAmpersand);
}
break;
case '"':
Write(s_EnQuote);
break;
case '\n':
Write(s_EnNewLine);
break;
case '\r':
Write(s_EnReturn);
break;
default:
if (127 < ch)
{
if (_utf8Encoding == null)
{
_utf8Encoding = Encoding.UTF8;
_byteBuffer = new byte[_utf8Encoding.GetMaxByteCount(1)];
}
int bytes = _utf8Encoding.GetBytes(value, i - 1, 1, _byteBuffer, 0);
for (int j = 0; j < bytes; j++)
{
Write("%");
Write(((uint)_byteBuffer[j]).ToString("X2", CultureInfo.InvariantCulture));
}
}
else
{
Write(ch);
}
break;
}
}
}
private void WriteWithReplace(string value, char[] find, string[] replace)
{
Debug.Assert(value != null);
Debug.Assert(find.Length == replace.Length);
int length = value.Length;
int pos = 0;
while (pos < length)
{
int newPos = value.IndexOfAny(find, pos);
if (newPos == -1)
{
break; // not found;
}
// output clean leading part of the string
while (pos < newPos)
{
Write(value[pos]);
pos++;
}
// output replacement
char badChar = value[pos];
int i;
for (i = find.Length - 1; 0 <= i; i--)
{
if (find[i] == badChar)
{
Write(replace[i]);
break;
}
}
Debug.Assert(0 <= i, "find char wasn't realy find");
pos++;
}
// output rest of the string
if (pos == 0)
{
Write(value);
}
else
{
while (pos < length)
{
Write(value[pos]);
pos++;
}
}
}
private void WriteCData(string value)
{
Debug.Assert(value != null);
Write(value.Replace(s_CDataEnd, s_CDataSplit));
}
private void WriteAttributes(ArrayList list, int count, HtmlElementProps htmlElementsProps)
{
Debug.Assert(count <= list.Count);
for (int attrib = 0; attrib < count; attrib++)
{
Debug.Assert(list[attrib] is BuilderInfo);
BuilderInfo attribute = (BuilderInfo)list[attrib];
string attrValue = attribute.Value;
bool abr = false, uri = false;
{
if (htmlElementsProps != null && attribute.Prefix.Length == 0)
{
HtmlAttributeProps htmlAttrProps = attribute.htmlAttrProps;
if (htmlAttrProps == null && attribute.search)
{
htmlAttrProps = HtmlAttributeProps.GetProps(attribute.LocalName);
}
if (htmlAttrProps != null)
{
abr = htmlElementsProps.AbrParent && htmlAttrProps.Abr;
uri = htmlElementsProps.UriParent && (htmlAttrProps.Uri ||
htmlElementsProps.NameParent && htmlAttrProps.Name
);
}
}
}
Write(s_Space);
WriteName(attribute.Prefix, attribute.LocalName);
if (abr && 0 == string.Compare(attribute.LocalName, attrValue, StringComparison.OrdinalIgnoreCase))
{
// Since the name of the attribute = the value of the attribute,
// this is a boolean attribute whose value should be suppressed
continue;
}
Write(s_EqualQuote);
if (uri)
{
WriteHtmlUri(attrValue);
}
else if (_isHtmlOutput)
{
WriteHtmlAttributeValue(attrValue);
}
else
{
WriteXmlAttributeValue(attrValue);
}
Write(s_Quote);
}
}
private void Indent(RecordBuilder record)
{
if (!record.Manager.CurrentElementScope.Mixed)
{
Indent(record.MainNode.Depth);
}
}
private void Indent(int depth)
{
if (_firstLine)
{
if (_indentOutput)
{
_firstLine = false;
}
return; // preven leading CRLF
}
Write(s_EndOfLine);
for (int i = 2 * depth; 0 < i; i--)
{
Write(" ");
}
}
//
// Abstract methods
internal abstract void Write(char outputChar);
internal abstract void Write(string outputText);
internal abstract void Close();
}
}
| |
// 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.Net;
using JetBrains.Annotations;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Online.Rooms;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.OnlinePlay.Playlists;
using osu.Game.Screens.Ranking;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Tests.Visual.Playlists
{
public class TestScenePlaylistsResultsScreen : ScreenTestScene
{
private const int scores_per_result = 10;
private TestResultsScreen resultsScreen;
private int currentScoreId;
private bool requestComplete;
private int totalCount;
[SetUp]
public void Setup() => Schedule(() =>
{
currentScoreId = 0;
requestComplete = false;
totalCount = 0;
bindHandler();
});
[Test]
public void TestShowWithUserScore()
{
ScoreInfo userScore = null;
AddStep("bind user score info handler", () =>
{
userScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { OnlineScoreID = currentScoreId++ };
bindHandler(userScore: userScore);
});
createResults(() => userScore);
AddAssert("user score selected", () => this.ChildrenOfType<ScorePanel>().Single(p => p.Score.OnlineScoreID == userScore.OnlineScoreID).State == PanelState.Expanded);
}
[Test]
public void TestShowNullUserScore()
{
createResults();
AddAssert("top score selected", () => this.ChildrenOfType<ScorePanel>().OrderByDescending(p => p.Score.TotalScore).First().State == PanelState.Expanded);
}
[Test]
public void TestShowUserScoreWithDelay()
{
ScoreInfo userScore = null;
AddStep("bind user score info handler", () =>
{
userScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { OnlineScoreID = currentScoreId++ };
bindHandler(true, userScore);
});
createResults(() => userScore);
AddAssert("more than 1 panel displayed", () => this.ChildrenOfType<ScorePanel>().Count() > 1);
AddAssert("user score selected", () => this.ChildrenOfType<ScorePanel>().Single(p => p.Score.OnlineScoreID == userScore.OnlineScoreID).State == PanelState.Expanded);
}
[Test]
public void TestShowNullUserScoreWithDelay()
{
AddStep("bind delayed handler", () => bindHandler(true));
createResults();
AddAssert("top score selected", () => this.ChildrenOfType<ScorePanel>().OrderByDescending(p => p.Score.TotalScore).First().State == PanelState.Expanded);
}
[Test]
public void TestFetchWhenScrolledToTheRight()
{
createResults();
AddStep("bind delayed handler", () => bindHandler(true));
for (int i = 0; i < 2; i++)
{
int beforePanelCount = 0;
AddStep("get panel count", () => beforePanelCount = this.ChildrenOfType<ScorePanel>().Count());
AddStep("scroll to right", () => resultsScreen.ScorePanelList.ChildrenOfType<OsuScrollContainer>().Single().ScrollToEnd(false));
AddAssert("right loading spinner shown", () => resultsScreen.RightSpinner.State.Value == Visibility.Visible);
waitForDisplay();
AddAssert($"count increased by {scores_per_result}", () => this.ChildrenOfType<ScorePanel>().Count() == beforePanelCount + scores_per_result);
AddAssert("right loading spinner hidden", () => resultsScreen.RightSpinner.State.Value == Visibility.Hidden);
}
}
[Test]
public void TestFetchWhenScrolledToTheLeft()
{
ScoreInfo userScore = null;
AddStep("bind user score info handler", () =>
{
userScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { OnlineScoreID = currentScoreId++ };
bindHandler(userScore: userScore);
});
createResults(() => userScore);
AddStep("bind delayed handler", () => bindHandler(true));
for (int i = 0; i < 2; i++)
{
int beforePanelCount = 0;
AddStep("get panel count", () => beforePanelCount = this.ChildrenOfType<ScorePanel>().Count());
AddStep("scroll to left", () => resultsScreen.ScorePanelList.ChildrenOfType<OsuScrollContainer>().Single().ScrollToStart(false));
AddAssert("left loading spinner shown", () => resultsScreen.LeftSpinner.State.Value == Visibility.Visible);
waitForDisplay();
AddAssert($"count increased by {scores_per_result}", () => this.ChildrenOfType<ScorePanel>().Count() == beforePanelCount + scores_per_result);
AddAssert("left loading spinner hidden", () => resultsScreen.LeftSpinner.State.Value == Visibility.Hidden);
}
}
private void createResults(Func<ScoreInfo> getScore = null)
{
AddStep("load results", () =>
{
LoadScreen(resultsScreen = new TestResultsScreen(getScore?.Invoke(), 1, new PlaylistItem
{
Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo },
Ruleset = { Value = new OsuRuleset().RulesetInfo }
}));
});
waitForDisplay();
}
private void waitForDisplay()
{
AddUntilStep("wait for load to complete", () =>
requestComplete
&& resultsScreen.ScorePanelList.GetScorePanels().Count() == totalCount
&& resultsScreen.ScorePanelList.AllPanelsVisible);
AddWaitStep("wait for display", 5);
}
private void bindHandler(bool delayed = false, ScoreInfo userScore = null, bool failRequests = false) => ((DummyAPIAccess)API).HandleRequest = request =>
{
// pre-check for requests we should be handling (as they are scheduled below).
switch (request)
{
case ShowPlaylistUserScoreRequest _:
case IndexPlaylistScoresRequest _:
break;
default:
return false;
}
requestComplete = false;
double delay = delayed ? 3000 : 0;
Scheduler.AddDelayed(() =>
{
if (failRequests)
{
triggerFail(request);
return;
}
switch (request)
{
case ShowPlaylistUserScoreRequest s:
if (userScore == null)
triggerFail(s);
else
triggerSuccess(s, createUserResponse(userScore));
break;
case IndexPlaylistScoresRequest i:
triggerSuccess(i, createIndexResponse(i));
break;
}
}, delay);
return true;
};
private void triggerSuccess<T>(APIRequest<T> req, T result)
where T : class
{
requestComplete = true;
req.TriggerSuccess(result);
}
private void triggerFail(APIRequest req)
{
requestComplete = true;
req.TriggerFailure(new WebException("Failed."));
}
private MultiplayerScore createUserResponse([NotNull] ScoreInfo userScore)
{
var multiplayerUserScore = new MultiplayerScore
{
ID = (int)(userScore.OnlineScoreID ?? currentScoreId++),
Accuracy = userScore.Accuracy,
EndedAt = userScore.Date,
Passed = userScore.Passed,
Rank = userScore.Rank,
Position = 200,
MaxCombo = userScore.MaxCombo,
TotalScore = userScore.TotalScore,
User = userScore.User,
Statistics = userScore.Statistics,
ScoresAround = new MultiplayerScoresAround
{
Higher = new MultiplayerScores(),
Lower = new MultiplayerScores()
}
};
totalCount++;
for (int i = 1; i <= scores_per_result; i++)
{
multiplayerUserScore.ScoresAround.Lower.Scores.Add(new MultiplayerScore
{
ID = currentScoreId++,
Accuracy = userScore.Accuracy,
EndedAt = userScore.Date,
Passed = true,
Rank = userScore.Rank,
MaxCombo = userScore.MaxCombo,
TotalScore = userScore.TotalScore - i,
User = new APIUser
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics = userScore.Statistics
});
multiplayerUserScore.ScoresAround.Higher.Scores.Add(new MultiplayerScore
{
ID = currentScoreId++,
Accuracy = userScore.Accuracy,
EndedAt = userScore.Date,
Passed = true,
Rank = userScore.Rank,
MaxCombo = userScore.MaxCombo,
TotalScore = userScore.TotalScore + i,
User = new APIUser
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics = userScore.Statistics
});
totalCount += 2;
}
addCursor(multiplayerUserScore.ScoresAround.Lower);
addCursor(multiplayerUserScore.ScoresAround.Higher);
return multiplayerUserScore;
}
private IndexedMultiplayerScores createIndexResponse(IndexPlaylistScoresRequest req)
{
var result = new IndexedMultiplayerScores();
long startTotalScore = req.Cursor?.Properties["total_score"].ToObject<long>() ?? 1000000;
string sort = req.IndexParams?.Properties["sort"].ToObject<string>() ?? "score_desc";
for (int i = 1; i <= scores_per_result; i++)
{
result.Scores.Add(new MultiplayerScore
{
ID = currentScoreId++,
Accuracy = 1,
EndedAt = DateTimeOffset.Now,
Passed = true,
Rank = ScoreRank.X,
MaxCombo = 1000,
TotalScore = startTotalScore + (sort == "score_asc" ? i : -i),
User = new APIUser
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics = new Dictionary<HitResult, int>
{
{ HitResult.Miss, 1 },
{ HitResult.Meh, 50 },
{ HitResult.Good, 100 },
{ HitResult.Great, 300 }
}
});
totalCount++;
}
addCursor(result);
return result;
}
private void addCursor(MultiplayerScores scores)
{
scores.Cursor = new Cursor
{
Properties = new Dictionary<string, JToken>
{
{ "total_score", JToken.FromObject(scores.Scores[^1].TotalScore) },
{ "score_id", JToken.FromObject(scores.Scores[^1].ID) },
}
};
scores.Params = new IndexScoresParams
{
Properties = new Dictionary<string, JToken>
{
{ "sort", JToken.FromObject(scores.Scores[^1].TotalScore > scores.Scores[^2].TotalScore ? "score_asc" : "score_desc") }
}
};
}
private class TestResultsScreen : PlaylistsResultsScreen
{
public new LoadingSpinner LeftSpinner => base.LeftSpinner;
public new LoadingSpinner CentreSpinner => base.CentreSpinner;
public new LoadingSpinner RightSpinner => base.RightSpinner;
public new ScorePanelList ScorePanelList => base.ScorePanelList;
public TestResultsScreen(ScoreInfo score, int roomId, PlaylistItem playlistItem, bool allowRetry = true)
: base(score, roomId, playlistItem, allowRetry)
{
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.