context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Subjects;
using System.Threading;
using Metrics;
using Metrics.MetricData;
using Metrics.Reporters;
using Metrics.Utils;
using MoreLinq;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
namespace Core.Telemetry
{
public class MetricNetInput
{
readonly ISubject<TelemetryEvent> _subject;
public MetricNetInput(int reportingPeriodSec, Dictionary<string,string> additionalProperties, bool resetOnReport = false)
{
_subject = new Subject<TelemetryEvent>();
Metric.Config.WithReporting(config => config.StopAndClearAllReports());
Metric.Config.WithReporting(config =>
config.WithReport(new RXMetricNetReport(_subject, additionalProperties, reportingPeriodSec, resetOnReport), TimeSpan.FromSeconds(reportingPeriodSec)));
}
public IObservable<TelemetryEvent> Stream => _subject;
}
static public class MetricNetInputHelper
{
static public TelemetryPipe CollectMetricsNet(this TelemetryPipe pipe, int reportingPeriodSec, Dictionary<string, string> additionalProperties = null, bool resetOnReport = false)
{
pipe.RegisterObserver(new MetricNetInput(reportingPeriodSec, additionalProperties, resetOnReport).Stream);
return pipe;
}
}
public class RXMetricNetReport : MetricsReport
{
const string EventType = "metric";
readonly ISubject<TelemetryEvent> _subject;
readonly Dictionary<string, string> _additionalProperties;
readonly int _reportingPeriodSec;
readonly bool _resetOnReport;
public RXMetricNetReport(ISubject<TelemetryEvent> subject, Dictionary<string, string> additionalProperties, int reportingPeriodSec, bool resetOnReport = false)
{
_subject = subject;
_additionalProperties = additionalProperties;
_reportingPeriodSec = reportingPeriodSec;
_resetOnReport = resetOnReport;
}
protected string FormatContextName(IEnumerable<string> contextStack, string contextName)
{
if (contextStack == null || !contextStack.Any())
return "root";
var stack = new List<string>(contextStack.Skip(1));
if (stack.Count == 0)
return contextName;
stack.Add(contextName);
return string.Join("_", stack);
}
protected string FormatMetricName<T>(string context, MetricValueSource<T> metric)
{
return $"{context}:{metric.Name}";
}
protected void ReportGauge(string name, double value, Unit unit, MetricTags tags)
{
if (double.IsNaN(value) || double.IsInfinity(value)) return;
var te = Pack("Gauge", name, unit, tags, new JObject{
{"value", value}
});
_subject.OnNext(te);
}
protected void ReportCounter(string name, CounterValue value, Unit unit, MetricTags tags)
{
var payload = new JObject
{
{"count", value.Count}
};
value.Items.ForEach(i =>
{
payload.Add(i.Item + "Count", i.Count);
payload.Add(i.Item + "Percent", i.Percent);
});
var te = Pack("Counter", name, unit, tags, payload);
_subject.OnNext(te);
}
protected void ReportMeter(string name, MeterValue value, Unit unit, TimeUnit rateUnit, MetricTags tags)
{
var payload = new JObject
{
{"count", value.Count},
{"meanRate", _resetOnReport ? ((double)value.Count / _reportingPeriodSec) : value.MeanRate},
{"1MinRate", value.OneMinuteRate},
{"5MinRate", value.FiveMinuteRate}
};
value.Items.ForEach(i =>
{
payload.Add(i.Item + "Count", i.Value.Count);
payload.Add(i.Item + "Percent", i.Percent);
payload.Add(i.Item + "MeanRate", i.Value.MeanRate);
payload.Add(i.Item + "1MinRate", i.Value.OneMinuteRate);
payload.Add(i.Item + "5MinRate", i.Value.FiveMinuteRate);
});
var te = Pack("Meter", name, unit, tags, payload);
_subject.OnNext(te);
}
protected void ReportHistogram(string name, HistogramValue value, Unit unit, MetricTags tags)
{
var te = Pack("Histogram", name, unit, tags, new JObject {
{"totalCount",value.Count},
{"last", value.LastValue},
{"min",value.Min},
{"mean",value.Mean},
{"max",value.Max},
{"stdDev",value.StdDev},
{"median",value.Median},
{"percentile75",value.Percentile75},
{"percentile95",value.Percentile95},
{"percentile99",value.Percentile99},
{"sampleSize", value.SampleSize}
});
_subject.OnNext(te);
}
protected void ReportTimer(string name, TimerValue value, Unit unit, TimeUnit rateUnit, TimeUnit durationUnit, MetricTags tags)
{
var te = Pack("Timer", name, unit, tags, new JObject {
{"totalCount",value.Rate.Count},
{"activeSessions",value.ActiveSessions},
{"meanRate", _resetOnReport ? ((double)value.Rate.Count / _reportingPeriodSec) : value.Rate.MeanRate},
{"1MinRate", value.Rate.OneMinuteRate},
{"5MinRate", value.Rate.FiveMinuteRate},
{"last", value.Histogram.LastValue},
{"min",value.Histogram.Min},
{"mean",value.Histogram.Mean},
{"max",value.Histogram.Max},
{"stdDev",value.Histogram.StdDev},
{"median",value.Histogram.Median},
{"percentile75",value.Histogram.Percentile75},
{"percentile95",value.Histogram.Percentile95},
{"percentile99",value.Histogram.Percentile99},
{"sampleSize", value.Histogram.SampleSize}
});
_subject.OnNext(te);
}
TelemetryEvent Pack(string type, string name, Unit unit, MetricTags tags, JObject payload)
{
if (_additionalProperties != null)
{
foreach (var property in _additionalProperties)
payload.Add(property.Key, property.Value);
}
var contextAndName = name.Split(':');
payload.Add("group", contextAndName[0]);
return new TelemetryEvent
{
Type = EventType,
PublishDateTime = DateTime.UtcNow,
Data = new SingleMetricSampleEvent
{
Name = contextAndName[1],
Type = type,
Unit = unit.ToString(),
Tags = string.Join(" ", tags.Tags),
Timestamp = GetTimestampThatIsDivisableByPeriod(DateTime.UtcNow),
Fields = payload,
}
};
}
DateTime GetTimestampThatIsDivisableByPeriod(DateTime currentTimestamp)
{
return new DateTime(currentTimestamp.Ticks - currentTimestamp.Ticks % (_reportingPeriodSec * 10000000));
}
public void RunReport(MetricsData metricsData, Func<HealthStatus> healthStatus, CancellationToken token)
{
ReportContext(metricsData, Enumerable.Empty<string>());
}
void ReportContext(MetricsData data, IEnumerable<string> contextStack)
{
string contextName = FormatContextName(contextStack, data.Context);
data.Gauges.ForEach(g => ReportGauge(FormatMetricName(contextName, g), g.ValueProvider.GetValue(false), g.Unit, g.Tags));
data.Counters.ForEach(c => ReportCounter(FormatMetricName(contextName, c), c.ValueProvider.GetValue(false), c.Unit, c.Tags));
data.Meters.ForEach(m => ReportMeter(FormatMetricName(contextName, m), m.ValueProvider.GetValue(_resetOnReport), m.Unit, m.RateUnit, m.Tags));
data.Histograms.ForEach(h => ReportHistogram(FormatMetricName(contextName, h), h.ValueProvider.GetValue(_resetOnReport), h.Unit, h.Tags));
data.Timers.ForEach(t => ReportTimer(FormatMetricName(contextName, t), t.ValueProvider.GetValue(_resetOnReport), t.Unit, t.RateUnit, t.DurationUnit, t.Tags));
IEnumerable<string> newContextStack = contextStack.Concat(new[] { data.Context });
foreach (MetricsData childMetric in data.ChildMetrics)
ReportContext(childMetric, newContextStack);
}
}
public class SingleMetricSampleEvent
{
public string Name { get; set; }
public string Type { get; set; }
public string Unit { get; set; }
public string Tags { get; set; }
[JsonProperty(PropertyName = "@timestamp")]
public DateTime Timestamp { get; set; }
public object Fields { 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.
using System.Collections.Concurrent;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.Runtime
{
public struct TimeoutHelper
{
public static readonly TimeSpan MaxWait = TimeSpan.FromMilliseconds(Int32.MaxValue);
private static readonly CancellationToken s_precancelledToken = new CancellationToken(true);
private bool _cancellationTokenInitialized;
private bool _deadlineSet;
private CancellationToken _cancellationToken;
private DateTime _deadline;
private TimeSpan _originalTimeout;
public TimeoutHelper(TimeSpan timeout)
{
Contract.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative");
_cancellationTokenInitialized = false;
_originalTimeout = timeout;
_deadline = DateTime.MaxValue;
_deadlineSet = (timeout == TimeSpan.MaxValue);
}
public CancellationToken GetCancellationToken()
{
return GetCancellationTokenAsync().Result;
}
public async Task<CancellationToken> GetCancellationTokenAsync()
{
if (!_cancellationTokenInitialized)
{
var timeout = RemainingTime();
if (timeout >= MaxWait || timeout == Timeout.InfiniteTimeSpan)
{
_cancellationToken = CancellationToken.None;
}
else if (timeout > TimeSpan.Zero)
{
_cancellationToken = await TimeoutTokenSource.FromTimeoutAsync((int)timeout.TotalMilliseconds);
}
else
{
_cancellationToken = s_precancelledToken;
}
_cancellationTokenInitialized = true;
}
return _cancellationToken;
}
public TimeSpan OriginalTimeout
{
get { return _originalTimeout; }
}
public static bool IsTooLarge(TimeSpan timeout)
{
return (timeout > TimeoutHelper.MaxWait) && (timeout != TimeSpan.MaxValue);
}
public static TimeSpan FromMilliseconds(int milliseconds)
{
if (milliseconds == Timeout.Infinite)
{
return TimeSpan.MaxValue;
}
else
{
return TimeSpan.FromMilliseconds(milliseconds);
}
}
public static int ToMilliseconds(TimeSpan timeout)
{
if (timeout == TimeSpan.MaxValue)
{
return Timeout.Infinite;
}
else
{
long ticks = Ticks.FromTimeSpan(timeout);
if (ticks / TimeSpan.TicksPerMillisecond > int.MaxValue)
{
return int.MaxValue;
}
return Ticks.ToMilliseconds(ticks);
}
}
public static TimeSpan Min(TimeSpan val1, TimeSpan val2)
{
if (val1 > val2)
{
return val2;
}
else
{
return val1;
}
}
public static TimeSpan Add(TimeSpan timeout1, TimeSpan timeout2)
{
return Ticks.ToTimeSpan(Ticks.Add(Ticks.FromTimeSpan(timeout1), Ticks.FromTimeSpan(timeout2)));
}
public static DateTime Add(DateTime time, TimeSpan timeout)
{
if (timeout >= TimeSpan.Zero && DateTime.MaxValue - time <= timeout)
{
return DateTime.MaxValue;
}
if (timeout <= TimeSpan.Zero && DateTime.MinValue - time >= timeout)
{
return DateTime.MinValue;
}
return time + timeout;
}
public static DateTime Subtract(DateTime time, TimeSpan timeout)
{
return Add(time, TimeSpan.Zero - timeout);
}
public static TimeSpan Divide(TimeSpan timeout, int factor)
{
if (timeout == TimeSpan.MaxValue)
{
return TimeSpan.MaxValue;
}
return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1);
}
public TimeSpan RemainingTime()
{
if (!_deadlineSet)
{
this.SetDeadline();
return _originalTimeout;
}
else if (_deadline == DateTime.MaxValue)
{
return TimeSpan.MaxValue;
}
else
{
TimeSpan remaining = _deadline - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
{
return TimeSpan.Zero;
}
else
{
return remaining;
}
}
}
public TimeSpan ElapsedTime()
{
return _originalTimeout - this.RemainingTime();
}
private void SetDeadline()
{
Contract.Assert(!_deadlineSet, "TimeoutHelper deadline set twice.");
_deadline = DateTime.UtcNow + _originalTimeout;
_deadlineSet = true;
}
public static void ThrowIfNegativeArgument(TimeSpan timeout)
{
ThrowIfNegativeArgument(timeout, "timeout");
}
public static void ThrowIfNegativeArgument(TimeSpan timeout, string argumentName)
{
if (timeout < TimeSpan.Zero)
{
throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBeNonNegative(argumentName, timeout));
}
}
public static void ThrowIfNonPositiveArgument(TimeSpan timeout)
{
ThrowIfNonPositiveArgument(timeout, "timeout");
}
public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentName)
{
if (timeout <= TimeSpan.Zero)
{
throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBePositive(argumentName, timeout));
}
}
public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout)
{
ThrowIfNegativeArgument(timeout);
if (timeout == TimeSpan.MaxValue)
{
waitHandle.WaitOne();
return true;
}
else
{
// http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx
// with exitContext was used in Desktop which is not supported in Net Native or CoreClr
return waitHandle.WaitOne(timeout);
}
}
internal static TimeoutException CreateEnterTimedOutException(TimeSpan timeout)
{
return new TimeoutException(SR.Format(SR.LockTimeoutExceptionMessage, timeout));
}
}
/// <summary>
/// This class coalesces timeout tokens because cancelation tokens with timeouts are more expensive to expose.
/// Disposing too many such tokens will cause thread contentions in high throughput scenario.
///
/// Tokens with target cancelation time 15ms apart would resolve to the same instance.
/// </summary>
internal static class TimeoutTokenSource
{
/// <summary>
/// These are constants use to calculate timeout coalescing, for more description see method FromTimeoutAsync
/// </summary>
private const int CoalescingFactor = 15;
private const int GranularityFactor = 2000;
private const int SegmentationFactor = CoalescingFactor * GranularityFactor;
private static readonly ConcurrentDictionary<long, Task<CancellationToken>> s_tokenCache =
new ConcurrentDictionary<long, Task<CancellationToken>>();
private static readonly Action<object> s_deregisterToken = (object state) =>
{
var args = (Tuple<long, CancellationTokenSource>)state;
Task<CancellationToken> ignored;
try
{
s_tokenCache.TryRemove(args.Item1, out ignored);
}
finally
{
args.Item2.Dispose();
}
};
public static CancellationToken FromTimeout(int millisecondsTimeout)
{
return FromTimeoutAsync(millisecondsTimeout).Result;
}
public static Task<CancellationToken> FromTimeoutAsync(int millisecondsTimeout)
{
// Note that CancellationTokenSource constructor requires input to be >= -1,
// restricting millisecondsTimeout to be >= -1 would enforce that
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("Invalid millisecondsTimeout value " + millisecondsTimeout);
}
// To prevent s_tokenCache growing too large, we have to adjust the granularity of the our coalesce depending
// on the value of millisecondsTimeout. The coalescing span scales proportionally with millisecondsTimeout which
// would garentee constant s_tokenCache size in the case where similar millisecondsTimeout values are accepted.
// If the method is given a wildly different millisecondsTimeout values all the time, the dictionary would still
// only grow logarithmically with respect to the range of the input values
uint currentTime = (uint)Environment.TickCount;
long targetTime = millisecondsTimeout + currentTime;
// Formula for our coalescing span:
// Divide millisecondsTimeout by SegmentationFactor and take the highest bit and then multiply CoalescingFactor back
var segmentValue = millisecondsTimeout / SegmentationFactor;
var coalescingSpanMs = CoalescingFactor;
while (segmentValue > 0)
{
segmentValue >>= 1;
coalescingSpanMs <<= 1;
}
targetTime = ((targetTime + (coalescingSpanMs - 1)) / coalescingSpanMs) * coalescingSpanMs;
Task<CancellationToken> tokenTask;
if (!s_tokenCache.TryGetValue(targetTime, out tokenTask))
{
var tcs = new TaskCompletionSource<CancellationToken>(TaskCreationOptions.RunContinuationsAsynchronously);
// only a single thread may succeed adding its task into the cache
if (s_tokenCache.TryAdd(targetTime, tcs.Task))
{
// Since this thread was successful reserving a spot in the cache, it would be the only thread
// that construct the CancellationTokenSource
var tokenSource = new CancellationTokenSource((int)(targetTime - currentTime));
var token = tokenSource.Token;
// Clean up cache when Token is canceled
token.Register(s_deregisterToken, Tuple.Create(targetTime, tokenSource));
// set the result so other thread may observe the token, and return
tcs.TrySetResult(token);
tokenTask = tcs.Task;
}
else
{
// for threads that failed when calling TryAdd, there should be one already in the cache
if (!s_tokenCache.TryGetValue(targetTime, out tokenTask))
{
// In unlikely scenario the token was already cancelled and timed out, we would not find it in cache.
// In this case we would simply create a non-coalsed token
tokenTask = Task.FromResult(new CancellationTokenSource(millisecondsTimeout).Token);
}
}
}
return tokenTask;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using Qwack.Core.Cubes;
using System.Linq;
namespace Qwack.Core.Tests.Cubes
{
public class CubeExtensionsFacts
{
private ICube GetSUT()
{
var x = new ResultCube();
x.Initialize(new Dictionary<string, Type> { { "gwah", typeof(string) }, { "wwahh", typeof(int) } });
x.AddRow(new object[] { "woooh", 6 }, 77.6);
x.AddRow(new Dictionary<string, object> { { "gwah", "gloop" }, { "wwahh", 14 } }, 78.6);
x.AddRow(new Dictionary<string, object> { { "wwahh", 83 }, { "gwah", "bah!" } }, 79.6);
return x;
}
[Fact]
public void CanCreateCube()
{
var x = GetSUT();
Assert.True(Enumerable.SequenceEqual(new[] { "woooh", "gloop", "bah!" }, x.KeysForField<string>("gwah")));
}
[Fact]
public void ToDictionary()
{
var x = GetSUT();
Assert.Throws<Exception>(() => x.ToDictionary("ooop"));
var d = x.ToDictionary("gwah");
Assert.Equal(79.6, d["bah!"].Single().Value);
}
[Fact]
public void KeysForField()
{
var x = GetSUT();
Assert.Throws<Exception>(() => x.KeysForField<string>("ooop"));
Assert.Throws<Exception>(() => x.KeysForField<string>("wwahh"));
Assert.Throws<Exception>(() => x.KeysForField("ooop"));
var k = x.KeysForField<int>("wwahh");
Assert.Contains(14, k);
var ko = x.KeysForField("wwahh");
Assert.Contains(14, ko);
var kos = x.KeysForField("gwah");
Assert.Contains("gloop", kos);
}
[Fact]
public void CanMultiply()
{
var x = GetSUT();
var xL = x.ScalarMultiply(10.0);
Assert.Equal(796, xL.ToDictionary("gwah")["bah!"].Single().Value);
}
[Fact]
public void CanFilter()
{
var x = GetSUT();
var filters = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>( "gwah", "bah!" ),
new KeyValuePair<string, object>( "gwah", "gloop" ),
};
var z = x.Filter(filters);
Assert.True(Enumerable.SequenceEqual(new[] { "gloop", "bah!" }, z.KeysForField<string>("gwah")));
var filters2 = new Dictionary<string, object> { { "wwahh", 6 } };
z = x.Filter(filters2);
Assert.True(Enumerable.SequenceEqual(new[] { "woooh" }, z.KeysForField<string>("gwah")));
var filters3 = new Dictionary<string, object> { { "ooop", 6 } };
Assert.Throws<Exception>(() => x.Filter(filters3));
}
[Fact]
public void CanPivot()
{
var x = GetSUT();
x.AddRow(new Dictionary<string, object> { { "wwahh", 88 }, { "gwah", "bah!" } }, 80.6);
var z = x.Pivot("gwah", AggregationAction.Sum);
var rowValue = z.GetAllRows().Where(r => Convert.ToString(r.MetaData.First()) == "bah!").Single().Value;
Assert.Equal(80.6 + 79.6, rowValue);
Assert.Throws<Exception>(() => x.Pivot("ooop", AggregationAction.Sum));
z = x.Pivot("gwah", AggregationAction.Average);
rowValue = z.GetAllRows().Where(r => Convert.ToString(r.MetaData.First()) == "bah!").Single().Value;
Assert.Equal((80.6 + 79.6) / 2.0, rowValue);
z = x.Pivot("gwah", AggregationAction.Max);
rowValue = z.GetAllRows().Where(r => Convert.ToString(r.MetaData.First()) == "bah!").Single().Value;
Assert.Equal(80.6, rowValue);
z = x.Pivot("gwah", AggregationAction.Min);
rowValue = z.GetAllRows().Where(r => Convert.ToString(r.MetaData.First()) == "bah!").Single().Value;
Assert.Equal(79.6, rowValue);
}
[Fact]
public void CanSort()
{
var x = GetSUT();
x.AddRow(new Dictionary<string, object> { { "wwahh", 88 }, { "gwah", "bah!" } }, 80.6);
var z = x.Sort();
var rowValues = z.GetAllRows();
Assert.Equal(79.6, rowValues.First().Value);
}
[Fact]
public void CanSort2()
{
var x = GetSUT();
x.AddRow(new Dictionary<string, object> { { "wwahh", 88 }, { "gwah", "bah!" } }, 80.6);
var z = x.Sort(new List<string> { "wwahh" });
var rowValues = z.GetAllRows();
Assert.Equal(77.6, rowValues.First().Value);
Assert.Throws<Exception>(() => x.Sort(new List<string> { "wwahhzzz" }));
}
private ICube GetSUT2()
{
var x = new ResultCube();
x.Initialize(new Dictionary<string, Type> { { "gwah", typeof(string) }, { "wwahh", typeof(DateTime) } });
x.AddRow(new object[] { "woooh", DateTime.Today.AddDays(10) }, 77.6);
x.AddRow(new Dictionary<string, object> { { "gwah", "gloop" }, { "wwahh", DateTime.Today.AddDays(20) } }, 78.6);
x.AddRow(new Dictionary<string, object> { { "wwahh", DateTime.Today.AddDays(30) }, { "gwah", "bah!" } }, 79.6);
return x;
}
[Fact]
public void CanBucket()
{
var x = GetSUT2();
var buckets = new Dictionary<DateTime, string>
{
{DateTime.Today.AddDays(25),"b1" },
{DateTime.Today.AddDays(50),"b2" },
{DateTime.Today.AddDays(100),"b3" },
};
Assert.Throws<Exception>(() => x.BucketTimeAxis("glooop", "bucketz", buckets));
var z = x.BucketTimeAxis("wwahh", "bucketz", buckets);
var rowValues = z.GetAllRows();
Assert.Equal("b1", rowValues[0].ToDictionary(z.DataTypes.Keys.ToArray())["bucketz"]);
Assert.Equal("b1", rowValues[1].ToDictionary(z.DataTypes.Keys.ToArray())["bucketz"]);
Assert.Equal("b2", rowValues[2].ToDictionary(z.DataTypes.Keys.ToArray())["bucketz"]);
}
[Fact]
public void CanDifference()
{
var x = new ResultCube();
x.Initialize(new Dictionary<string, Type> { { "gwah", typeof(string) }, { "wwahh", typeof(int) } });
var y = new ResultCube();
y.Initialize(new Dictionary<string, Type> { { "gwah", typeof(string) }, { "wwahh", typeof(int) } });
x.AddRow(new object[] { "woooh", 6 }, 77.6);
y.AddRow(new object[] { "woooh", 6 }, 77.4);
var d = x.Difference(y);
Assert.Equal(0.2, d.GetAllRows().First().Value, 10);
var z = new ResultCube();
z.Initialize(new Dictionary<string, Type> { { "gwah", typeof(bool) }, { "wwahh", typeof(int) } });
Assert.Throws<Exception>(() => x.Difference(z));
Assert.Throws<Exception>(() => x.QuickDifference(z));
y.AddRow(new object[] { "woooh", 7 }, 77.4);
Assert.Throws<Exception>(() => x.QuickDifference(y));
}
[Fact]
public void CanMerge()
{
var x = new ResultCube();
x.Initialize(new Dictionary<string, Type> { { "gwah", typeof(string) }, { "wwahh", typeof(int) } });
var y = new ResultCube();
y.Initialize(new Dictionary<string, Type> { { "gwah", typeof(string) }, { "wwahh", typeof(int) } });
x.AddRow(new object[] { "woooh", 6 }, 77.6);
y.AddRow(new object[] { "woooh", 6 }, 77.4);
var d = x.MergeQuick(y);
Assert.Equal(2, d.GetAllRows().Length);
d = x.Merge(y);
Assert.Equal(2, d.GetAllRows().Length);
var z = new ResultCube();
z.Initialize(new Dictionary<string, Type> { { "gwah", typeof(bool) }, { "wwahh", typeof(int) } });
Assert.Throws<Exception>(() => x.MergeQuick(z));
Assert.Throws<Exception>(() => x.Merge(z));
}
[Fact]
public void ToMatrix()
{
var x = GetSUT();
Assert.Throws<Exception>(() => x.ToMatrix("ooop", "ooop", false));
Assert.Throws<Exception>(() => x.ToMatrix("wwahh", "ooop", false));
var m = x.ToMatrix("wwahh", "gwah", false);
var ms = x.ToMatrix("wwahh", "gwah", true);
for (var i = 0; i < m.GetLength(0); i++)
for (var j = 0; j < m.GetLength(1); j++)
{
if (i > 0 && j > 0)
if (i != j)
Assert.Null(m[i, j]);
else
Assert.NotNull(m[i, j]);
}
}
[Fact]
public void IsEqual()
{
Assert.True(CubeEx.IsEqual(0.77,0.77));
Assert.True(CubeEx.IsEqual(77, 77));
Assert.True(CubeEx.IsEqual('C', 'C'));
Assert.True(CubeEx.IsEqual(false, false));
Assert.True(CubeEx.IsEqual(DateTime.Today, DateTime.Today));
Assert.True(CubeEx.IsEqual(1.6M, 1.6M));
Assert.False(CubeEx.IsEqual(new List<string>(), 1.6M));
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.L1.Worker
{
[Collection("Worker L1 Tests")]
public class SigningL1Tests : L1TestBase
{
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[Trait("Level", "L1")]
[Trait("Category", "Worker")]
// TODO: When NuGet works cross-platform, remove these traits. Also, package NuGet with the Agent.
[Trait("SkipOn", "darwin")]
[Trait("SkipOn", "linux")]
public async Task SignatureVerification_PassesWhenAllTasksAreSigned(bool useFingerprintList, bool useTopLevelFingerprint)
{
try
{
// Arrange
SetupL1();
FakeConfigurationStore fakeConfigurationStore = GetMockedService<FakeConfigurationStore>();
AgentSettings settings = fakeConfigurationStore.GetSettings();
settings.SignatureVerification = new SignatureVerificationSettings()
{
Mode = SignatureVerificationMode.Error
};
if (useFingerprintList)
{
settings.SignatureVerification.Fingerprints = new List<string>() { _fingerprint };
}
else if (useTopLevelFingerprint)
{
settings.Fingerprint = _fingerprint;
}
fakeConfigurationStore.UpdateSettings(settings);
var message = LoadTemplateMessage();
message.Steps.Clear();
message.Steps.Add(GetSignedTask());
// Act
var results = await RunWorker(message);
// Assert
FakeJobServer fakeJobServer = GetMockedService<FakeJobServer>();
AssertJobCompleted();
Assert.Equal(TaskResult.Succeeded, results.Result);
}
finally
{
TearDown();
}
}
[Theory]
[InlineData(false, false)]
[InlineData(true, false)]
[InlineData(false, true)]
[Trait("Level", "L1")]
[Trait("Category", "Worker")]
// TODO: When NuGet works cross-platform, remove these traits. Also, package NuGet with the Agent.
[Trait("SkipOn", "darwin")]
[Trait("SkipOn", "linux")]
public async Task SignatureVerification_FailsWhenTasksArentSigned(bool useFingerprintList, bool useTopLevelFingerprint)
{
try
{
// Arrange
SetupL1();
FakeConfigurationStore fakeConfigurationStore = GetMockedService<FakeConfigurationStore>();
AgentSettings settings = fakeConfigurationStore.GetSettings();
settings.SignatureVerification = new SignatureVerificationSettings()
{
Mode = SignatureVerificationMode.Error
};
if (useFingerprintList)
{
settings.SignatureVerification.Fingerprints = new List<string>() { _fingerprint };
}
else if (useTopLevelFingerprint)
{
settings.Fingerprint = _fingerprint;
}
fakeConfigurationStore.UpdateSettings(settings);
var message = LoadTemplateMessage();
// Act
var results = await RunWorker(message);
// Assert
AssertJobCompleted();
Assert.Equal(TaskResult.Failed, results.Result);
}
finally
{
TearDown();
}
}
[Fact]
[Trait("Level", "L1")]
[Trait("Category", "Worker")]
[Trait("SkipOn", "darwin")]
[Trait("SkipOn", "linux")]
public async Task SignatureVerification_MultipleFingerprints()
{
try
{
// Arrange
SetupL1();
FakeConfigurationStore fakeConfigurationStore = GetMockedService<FakeConfigurationStore>();
AgentSettings settings = fakeConfigurationStore.GetSettings();
settings.SignatureVerification = new SignatureVerificationSettings()
{
Mode = SignatureVerificationMode.Error,
Fingerprints = new List<string>() { "BAD", _fingerprint }
};
fakeConfigurationStore.UpdateSettings(settings);
var message = LoadTemplateMessage();
message.Steps.Clear();
message.Steps.Add(GetSignedTask());
// Act
var results = await RunWorker(message);
// Assert
AssertJobCompleted();
Assert.Equal(TaskResult.Succeeded, results.Result);
}
finally
{
TearDown();
}
}
[Theory]
[Trait("Level", "L1")]
[Trait("Category", "Worker")]
[Trait("SkipOn", "darwin")]
[Trait("SkipOn", "linux")]
[InlineData(false)]
[InlineData(true)]
public async Task SignatureVerification_Warning(bool writeToBlobstorageService)
{
try
{
// Arrange
SetupL1();
FakeConfigurationStore fakeConfigurationStore = GetMockedService<FakeConfigurationStore>();
AgentSettings settings = fakeConfigurationStore.GetSettings();
settings.SignatureVerification = new SignatureVerificationSettings()
{
Mode = SignatureVerificationMode.Warning,
Fingerprints = new List<string>() { "BAD" }
};
fakeConfigurationStore.UpdateSettings(settings);
var message = LoadTemplateMessage();
message.Steps.Clear();
message.Steps.Add(GetSignedTask());
message.Variables.Add("agent.LogToBlobstorageService", writeToBlobstorageService.ToString());
// Act
var results = await RunWorker(message);
// Assert
AssertJobCompleted();
Assert.Equal(TaskResult.Succeeded, results.Result);
var steps = GetSteps();
var log = GetTimelineLogLines(steps[1]);
Assert.Equal(1, log.Where(x => x.Contains("##[warning]Task signature verification failed.")).Count());
}
finally
{
TearDown();
}
}
[Fact]
[Trait("Level", "L1")]
[Trait("Category", "Worker")]
[Trait("SkipOn", "darwin")]
[Trait("SkipOn", "linux")]
public async Task SignatureVerification_Disabled()
{
try
{
// Arrange
SetupL1();
FakeConfigurationStore fakeConfigurationStore = GetMockedService<FakeConfigurationStore>();
AgentSettings settings = fakeConfigurationStore.GetSettings();
settings.SignatureVerification = new SignatureVerificationSettings()
{
Mode = SignatureVerificationMode.None,
Fingerprints = new List<string>() { "BAD" }
};
fakeConfigurationStore.UpdateSettings(settings);
var message = LoadTemplateMessage();
message.Steps.Clear();
message.Steps.Add(GetSignedTask());
// Act
var results = await RunWorker(message);
// Assert
AssertJobCompleted();
Assert.Equal(TaskResult.Succeeded, results.Result);
}
finally
{
TearDown();
}
}
private static TaskStep GetSignedTask()
{
var step = new TaskStep
{
Reference = new TaskStepDefinitionReference
{
Id = Guid.Parse("5515f72c-5faa-4121-8a46-8f42a8f42132"),
Name = "servicetree-link-build-task-signed",
Version = "1.52.1"
},
Name = "servicetree-link-build-task-signed",
DisplayName = "ServiceTree Integration - SIGNED",
Id = Guid.NewGuid()
};
// These inputs let the task itself succeed.
step.Inputs.Add("Service", "23ddace0-0682-541f-bfa9-6cbc76d9c051");
step.Inputs.Add("ServiceTreeLinkNotRequiredIds", "2"); // Set to system.definitionId
step.Inputs.Add("ServiceTreeGateway", "Foo");
return step;
}
private static string _fingerprint = "3F9001EA83C560D712C24CF213C3D312CB3BFF51EE89435D3430BD06B5D0EECE";
}
}
| |
// TarArchive.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// HISTORY
// 28-01-2010 DavidPierson Added IsStreamOwner
using System;
using System.IO;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// Used to advise clients of 'events' while processing archives
/// </summary>
public delegate void ProgressMessageHandler(TarArchive archive, TarEntry entry, string message);
/// <summary>
/// The TarArchive class implements the concept of a
/// 'Tape Archive'. A tar archive is a series of entries, each of
/// which represents a file system object. Each entry in
/// the archive consists of a header block followed by 0 or more data blocks.
/// Directory entries consist only of the header block, and are followed by entries
/// for the directory's contents. File entries consist of a
/// header followed by the number of blocks needed to
/// contain the file's contents. All entries are written on
/// block boundaries. Blocks are 512 bytes long.
///
/// TarArchives are instantiated in either read or write mode,
/// based upon whether they are instantiated with an InputStream
/// or an OutputStream. Once instantiated TarArchives read/write
/// mode can not be changed.
///
/// There is currently no support for random access to tar archives.
/// However, it seems that subclassing TarArchive, and using the
/// TarBuffer.CurrentRecord and TarBuffer.CurrentBlock
/// properties, this would be rather trivial.
/// </summary>
public class TarArchive : IDisposable
{
/// <summary>
/// Client hook allowing detailed information to be reported during processing
/// </summary>
public event ProgressMessageHandler ProgressMessageEvent;
/// <summary>
/// Raises the ProgressMessage event
/// </summary>
/// <param name="entry">The <see cref="TarEntry">TarEntry</see> for this event</param>
/// <param name="message">message for this event. Null is no message</param>
protected virtual void OnProgressMessageEvent(TarEntry entry, string message)
{
ProgressMessageHandler handler = ProgressMessageEvent;
if (handler != null) {
handler(this, entry, message);
}
}
#region Constructors
/// <summary>
/// Constructor for a default <see cref="TarArchive"/>.
/// </summary>
protected TarArchive()
{
}
/// <summary>
/// Initalise a TarArchive for input.
/// </summary>
/// <param name="stream">The <see cref="TarInputStream"/> to use for input.</param>
protected TarArchive(TarInputStream stream)
{
if ( stream == null ) {
throw new ArgumentNullException("stream");
}
tarIn = stream;
}
/// <summary>
/// Initialise a TarArchive for output.
/// </summary>
/// <param name="stream">The <see cref="TarOutputStream"/> to use for output.</param>
protected TarArchive(TarOutputStream stream)
{
if ( stream == null ) {
throw new ArgumentNullException("stream");
}
tarOut = stream;
}
#endregion
#region Static factory methods
/// <summary>
/// The InputStream based constructors create a TarArchive for the
/// purposes of extracting or listing a tar archive. Thus, use
/// these constructors when you wish to extract files from or list
/// the contents of an existing tar archive.
/// </summary>
/// <param name="inputStream">The stream to retrieve archive data from.</param>
/// <returns>Returns a new <see cref="TarArchive"/> suitable for reading from.</returns>
public static TarArchive CreateInputTarArchive(Stream inputStream)
{
if ( inputStream == null ) {
throw new ArgumentNullException("inputStream");
}
TarInputStream tarStream = inputStream as TarInputStream;
TarArchive result;
if ( tarStream != null ) {
result = new TarArchive(tarStream);
}
else {
result = CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor);
}
return result;
}
/// <summary>
/// Create TarArchive for reading setting block factor
/// </summary>
/// <param name="inputStream">A stream containing the tar archive contents</param>
/// <param name="blockFactor">The blocking factor to apply</param>
/// <returns>Returns a <see cref="TarArchive"/> suitable for reading.</returns>
public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor)
{
if ( inputStream == null ) {
throw new ArgumentNullException("inputStream");
}
if ( inputStream is TarInputStream ) {
throw new ArgumentException("TarInputStream not valid");
}
return new TarArchive(new TarInputStream(inputStream, blockFactor));
}
/// <summary>
/// Create a TarArchive for writing to, using the default blocking factor
/// </summary>
/// <param name="outputStream">The <see cref="Stream"/> to write to</param>
/// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns>
public static TarArchive CreateOutputTarArchive(Stream outputStream)
{
if ( outputStream == null ) {
throw new ArgumentNullException("outputStream");
}
TarOutputStream tarStream = outputStream as TarOutputStream;
TarArchive result;
if ( tarStream != null ) {
result = new TarArchive(tarStream);
}
else {
result = CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor);
}
return result;
}
/// <summary>
/// Create a <see cref="TarArchive">tar archive</see> for writing.
/// </summary>
/// <param name="outputStream">The stream to write to</param>
/// <param name="blockFactor">The blocking factor to use for buffering.</param>
/// <returns>Returns a <see cref="TarArchive"/> suitable for writing.</returns>
public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor)
{
if ( outputStream == null ) {
throw new ArgumentNullException("outputStream");
}
if ( outputStream is TarOutputStream ) {
throw new ArgumentException("TarOutputStream is not valid");
}
return new TarArchive(new TarOutputStream(outputStream, blockFactor));
}
#endregion
/// <summary>
/// Set the flag that determines whether existing files are
/// kept, or overwritten during extraction.
/// </summary>
/// <param name="keepExistingFiles">
/// If true, do not overwrite existing files.
/// </param>
public void SetKeepOldFiles(bool keepExistingFiles)
{
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
keepOldFiles = keepExistingFiles;
}
/// <summary>
/// Get/set the ascii file translation flag. If ascii file translation
/// is true, then the file is checked to see if it a binary file or not.
/// If the flag is true and the test indicates it is ascii text
/// file, it will be translated. The translation converts the local
/// operating system's concept of line ends into the UNIX line end,
/// '\n', which is the defacto standard for a TAR archive. This makes
/// text files compatible with UNIX.
/// </summary>
public bool AsciiTranslate
{
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return asciiTranslate;
}
set {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
asciiTranslate = value;
}
}
/// <summary>
/// Set the ascii file translation flag.
/// </summary>
/// <param name= "translateAsciiFiles">
/// If true, translate ascii text files.
/// </param>
[Obsolete("Use the AsciiTranslate property")]
public void SetAsciiTranslation(bool translateAsciiFiles)
{
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
asciiTranslate = translateAsciiFiles;
}
/// <summary>
/// PathPrefix is added to entry names as they are written if the value is not null.
/// A slash character is appended after PathPrefix
/// </summary>
public string PathPrefix
{
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return pathPrefix;
}
set {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
pathPrefix = value;
}
}
/// <summary>
/// RootPath is removed from entry names if it is found at the
/// beginning of the name.
/// </summary>
public string RootPath
{
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return rootPath;
}
set {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
rootPath = value;
}
}
/// <summary>
/// Set user and group information that will be used to fill in the
/// tar archive's entry headers. This information is based on that available
/// for the linux operating system, which is not always available on other
/// operating systems. TarArchive allows the programmer to specify values
/// to be used in their place.
/// <see cref="ApplyUserInfoOverrides"/> is set to true by this call.
/// </summary>
/// <param name="userId">
/// The user id to use in the headers.
/// </param>
/// <param name="userName">
/// The user name to use in the headers.
/// </param>
/// <param name="groupId">
/// The group id to use in the headers.
/// </param>
/// <param name="groupName">
/// The group name to use in the headers.
/// </param>
public void SetUserInfo(int userId, string userName, int groupId, string groupName)
{
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
this.userId = userId;
this.userName = userName;
this.groupId = groupId;
this.groupName = groupName;
applyUserInfoOverrides = true;
}
/// <summary>
/// Get or set a value indicating if overrides defined by <see cref="SetUserInfo">SetUserInfo</see> should be applied.
/// </summary>
/// <remarks>If overrides are not applied then the values as set in each header will be used.</remarks>
public bool ApplyUserInfoOverrides
{
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return applyUserInfoOverrides;
}
set {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
applyUserInfoOverrides = value;
}
}
/// <summary>
/// Get the archive user id.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current user id.
/// </returns>
public int UserId {
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return userId;
}
}
/// <summary>
/// Get the archive user name.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current user name.
/// </returns>
public string UserName {
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return userName;
}
}
/// <summary>
/// Get the archive group id.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current group id.
/// </returns>
public int GroupId {
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return groupId;
}
}
/// <summary>
/// Get the archive group name.
/// See <see cref="ApplyUserInfoOverrides">ApplyUserInfoOverrides</see> for detail
/// on how to allow setting values on a per entry basis.
/// </summary>
/// <returns>
/// The current group name.
/// </returns>
public string GroupName {
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
return groupName;
}
}
/// <summary>
/// Get the archive's record size. Tar archives are composed of
/// a series of RECORDS each containing a number of BLOCKS.
/// This allowed tar archives to match the IO characteristics of
/// the physical device being used. Archives are expected
/// to be properly "blocked".
/// </summary>
/// <returns>
/// The record size this archive is using.
/// </returns>
public int RecordSize {
get {
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
if (tarIn != null) {
return tarIn.RecordSize;
} else if (tarOut != null) {
return tarOut.RecordSize;
}
return TarBuffer.DefaultRecordSize;
}
}
/// <summary>
/// Sets the IsStreamOwner property on the underlying stream.
/// Set this to false to prevent the Close of the TarArchive from closing the stream.
/// </summary>
public bool IsStreamOwner {
set {
if (tarIn != null) {
tarIn.IsStreamOwner = value;
} else {
tarOut.IsStreamOwner = value;
}
}
}
/// <summary>
/// Close the archive.
/// </summary>
[Obsolete("Use Close instead")]
public void CloseArchive()
{
Close();
}
/// <summary>
/// Perform the "list" command for the archive contents.
///
/// NOTE That this method uses the <see cref="ProgressMessageEvent"> progress event</see> to actually list
/// the contents. If the progress display event is not set, nothing will be listed!
/// </summary>
public void ListContents()
{
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
while (true) {
TarEntry entry = tarIn.GetNextEntry();
if (entry == null) {
break;
}
OnProgressMessageEvent(entry, null);
}
}
/// <summary>
/// Perform the "extract" command and extract the contents of the archive.
/// </summary>
/// <param name="destinationDirectory">
/// The destination directory into which to extract.
/// </param>
public void ExtractContents(string destinationDirectory)
{
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
while (true) {
TarEntry entry = tarIn.GetNextEntry();
if (entry == null) {
break;
}
ExtractEntry(destinationDirectory, entry);
}
}
/// <summary>
/// Extract an entry from the archive. This method assumes that the
/// tarIn stream has been properly set with a call to GetNextEntry().
/// </summary>
/// <param name="destDir">
/// The destination directory into which to extract.
/// </param>
/// <param name="entry">
/// The TarEntry returned by tarIn.GetNextEntry().
/// </param>
void ExtractEntry(string destDir, TarEntry entry)
{
OnProgressMessageEvent(entry, null);
string name = entry.Name;
if (Path.IsPathRooted(name)) {
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
}
name = name.Replace('/', Path.DirectorySeparatorChar);
string destFile = Path.Combine(destDir, name);
if (entry.IsDirectory) {
EnsureDirectoryExists(destFile);
} else {
string parentDirectory = Path.GetDirectoryName(destFile);
EnsureDirectoryExists(parentDirectory);
bool process = true;
FileInfo fileInfo = new FileInfo(destFile);
if (fileInfo.Exists) {
if (keepOldFiles) {
OnProgressMessageEvent(entry, "Destination file already exists");
process = false;
} else if ((fileInfo.Attributes & FileAttributes.ReadOnly) != 0) {
OnProgressMessageEvent(entry, "Destination file already exists, and is read-only");
process = false;
}
}
if (process) {
bool asciiTrans = false;
Stream outputStream = File.Create(destFile);
if (this.asciiTranslate) {
asciiTrans = !IsBinary(destFile);
}
StreamWriter outw = null;
if (asciiTrans) {
outw = new StreamWriter(outputStream);
}
byte[] rdbuf = new byte[32 * 1024];
while (true) {
int numRead = tarIn.Read(rdbuf, 0, rdbuf.Length);
if (numRead <= 0) {
break;
}
if (asciiTrans) {
for (int off = 0, b = 0; b < numRead; ++b) {
if (rdbuf[b] == 10) {
string s = Encoding.ASCII.GetString(rdbuf, off, (b - off));
outw.WriteLine(s);
off = b + 1;
}
}
} else {
outputStream.Write(rdbuf, 0, numRead);
}
}
if (asciiTrans) {
outw.Close();
} else {
outputStream.Close();
}
}
}
}
/// <summary>
/// Write an entry to the archive. This method will call the putNextEntry
/// and then write the contents of the entry, and finally call closeEntry()
/// for entries that are files. For directories, it will call putNextEntry(),
/// and then, if the recurse flag is true, process each entry that is a
/// child of the directory.
/// </summary>
/// <param name="sourceEntry">
/// The TarEntry representing the entry to write to the archive.
/// </param>
/// <param name="recurse">
/// If true, process the children of directory entries.
/// </param>
public void WriteEntry(TarEntry sourceEntry, bool recurse)
{
if ( sourceEntry == null ) {
throw new ArgumentNullException("sourceEntry");
}
if ( isDisposed ) {
throw new ObjectDisposedException("TarArchive");
}
try
{
if ( recurse ) {
TarHeader.SetValueDefaults(sourceEntry.UserId, sourceEntry.UserName,
sourceEntry.GroupId, sourceEntry.GroupName);
}
WriteEntryCore(sourceEntry, recurse);
}
finally
{
if ( recurse ) {
TarHeader.RestoreSetValues();
}
}
}
/// <summary>
/// Write an entry to the archive. This method will call the putNextEntry
/// and then write the contents of the entry, and finally call closeEntry()
/// for entries that are files. For directories, it will call putNextEntry(),
/// and then, if the recurse flag is true, process each entry that is a
/// child of the directory.
/// </summary>
/// <param name="sourceEntry">
/// The TarEntry representing the entry to write to the archive.
/// </param>
/// <param name="recurse">
/// If true, process the children of directory entries.
/// </param>
void WriteEntryCore(TarEntry sourceEntry, bool recurse)
{
string tempFileName = null;
string entryFilename = sourceEntry.File;
TarEntry entry = (TarEntry)sourceEntry.Clone();
if ( applyUserInfoOverrides ) {
entry.GroupId = groupId;
entry.GroupName = groupName;
entry.UserId = userId;
entry.UserName = userName;
}
OnProgressMessageEvent(entry, null);
if (asciiTranslate && !entry.IsDirectory) {
if (!IsBinary(entryFilename)) {
tempFileName = Path.GetTempFileName();
using (StreamReader inStream = File.OpenText(entryFilename)) {
using (Stream outStream = File.Create(tempFileName)) {
while (true) {
string line = inStream.ReadLine();
if (line == null) {
break;
}
byte[] data = Encoding.ASCII.GetBytes(line);
outStream.Write(data, 0, data.Length);
outStream.WriteByte((byte)'\n');
}
outStream.Flush();
}
}
entry.Size = new FileInfo(tempFileName).Length;
entryFilename = tempFileName;
}
}
string newName = null;
if (rootPath != null) {
if (entry.Name.StartsWith(rootPath)) {
newName = entry.Name.Substring(rootPath.Length + 1 );
}
}
if (pathPrefix != null) {
newName = (newName == null) ? pathPrefix + "/" + entry.Name : pathPrefix + "/" + newName;
}
if (newName != null) {
entry.Name = newName;
}
tarOut.PutNextEntry(entry);
if (entry.IsDirectory) {
if (recurse) {
TarEntry[] list = entry.GetDirectoryEntries();
for (int i = 0; i < list.Length; ++i) {
WriteEntryCore(list[i], recurse);
}
}
}
else {
using (Stream inputStream = File.OpenRead(entryFilename)) {
byte[] localBuffer = new byte[32 * 1024];
while (true) {
int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length);
if (numRead <=0) {
break;
}
tarOut.Write(localBuffer, 0, numRead);
}
}
if ( (tempFileName != null) && (tempFileName.Length > 0) ) {
File.Delete(tempFileName);
}
tarOut.CloseEntry();
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the FileStream and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if ( !isDisposed ) {
isDisposed = true;
if ( disposing ) {
if ( tarOut != null ) {
tarOut.Flush();
tarOut.Close();
}
if ( tarIn != null ) {
tarIn.Close();
}
}
}
}
/// <summary>
/// Closes the archive and releases any associated resources.
/// </summary>
public virtual void Close()
{
Dispose(true);
}
/// <summary>
/// Ensures that resources are freed and other cleanup operations are performed
/// when the garbage collector reclaims the <see cref="TarArchive"/>.
/// </summary>
~TarArchive()
{
Dispose(false);
}
static void EnsureDirectoryExists(string directoryName)
{
if (!Directory.Exists(directoryName)) {
try {
Directory.CreateDirectory(directoryName);
}
catch (Exception e) {
throw new TarException("Exception creating directory '" + directoryName + "', " + e.Message+ " " + e.StackTrace, e);
}
}
}
// TODO: TarArchive - Is there a better way to test for a text file?
// It no longer reads entire files into memory but is still a weak test!
// This assumes that byte values 0-7, 14-31 or 255 are binary
// and that all non text files contain one of these values
static bool IsBinary(string filename)
{
using (FileStream fs = File.OpenRead(filename))
{
int sampleSize = Math.Min(4096, (int)fs.Length);
byte[] content = new byte[sampleSize];
int bytesRead = fs.Read(content, 0, sampleSize);
for (int i = 0; i < bytesRead; ++i) {
byte b = content[i];
if ( (b < 8) || ((b > 13) && (b < 32)) || (b == 255) ) {
return true;
}
}
}
return false;
}
#region Instance Fields
bool keepOldFiles;
bool asciiTranslate;
int userId;
string userName = string.Empty;
int groupId;
string groupName = string.Empty;
string rootPath;
string pathPrefix;
bool applyUserInfoOverrides;
TarInputStream tarIn;
TarOutputStream tarOut;
bool isDisposed;
#endregion
}
}
/* The original Java file had this header:
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// CSEF Receipt details Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KEMADataSet : EduHubDataSet<KEMA>
{
/// <inheritdoc />
public override string Name { get { return "KEMA"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KEMADataSet(EduHubContext Context)
: base(Context)
{
Index_TID = new Lazy<Dictionary<int, KEMA>>(() => this.ToDictionary(i => i.TID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KEMA" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KEMA" /> fields for each CSV column header</returns>
internal override Action<KEMA, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KEMA, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "FAMILY_KEY":
mapper[i] = (e, v) => e.FAMILY_KEY = v;
break;
case "STREGISTRATION":
mapper[i] = (e, v) => e.STREGISTRATION = v;
break;
case "EMA_PERIOD":
mapper[i] = (e, v) => e.EMA_PERIOD = v;
break;
case "EMA_TRAMT":
mapper[i] = (e, v) => e.EMA_TRAMT = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "DELETE_FLAG":
mapper[i] = (e, v) => e.DELETE_FLAG = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KEMA" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KEMA" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KEMA" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KEMA}"/> of entities</returns>
internal override IEnumerable<KEMA> ApplyDeltaEntities(IEnumerable<KEMA> Entities, List<KEMA> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.TID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.TID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, KEMA>> Index_TID;
#endregion
#region Index Methods
/// <summary>
/// Find KEMA by TID field
/// </summary>
/// <param name="TID">TID value used to find KEMA</param>
/// <returns>Related KEMA entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KEMA FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find KEMA by TID field
/// </summary>
/// <param name="TID">TID value used to find KEMA</param>
/// <param name="Value">Related KEMA entity</param>
/// <returns>True if the related KEMA entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out KEMA Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find KEMA by TID field
/// </summary>
/// <param name="TID">TID value used to find KEMA</param>
/// <returns>Related KEMA entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KEMA TryFindByTID(int TID)
{
KEMA value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KEMA table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KEMA]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KEMA](
[TID] int IDENTITY NOT NULL,
[FAMILY_KEY] varchar(10) NULL,
[STREGISTRATION] varchar(15) NULL,
[EMA_PERIOD] varchar(1) NULL,
[EMA_TRAMT] money NULL,
[DELETE_FLAG] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KEMA_Index_TID] PRIMARY KEY CLUSTERED (
[TID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KEMADataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KEMADataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KEMA"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KEMA"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KEMA> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[KEMA] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KEMA data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KEMA data set</returns>
public override EduHubDataSetDataReader<KEMA> GetDataSetDataReader()
{
return new KEMADataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KEMA data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KEMA data set</returns>
public override EduHubDataSetDataReader<KEMA> GetDataSetDataReader(List<KEMA> Entities)
{
return new KEMADataReader(new EduHubDataSetLoadedReader<KEMA>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KEMADataReader : EduHubDataSetDataReader<KEMA>
{
public KEMADataReader(IEduHubDataSetReader<KEMA> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 9; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // FAMILY_KEY
return Current.FAMILY_KEY;
case 2: // STREGISTRATION
return Current.STREGISTRATION;
case 3: // EMA_PERIOD
return Current.EMA_PERIOD;
case 4: // EMA_TRAMT
return Current.EMA_TRAMT;
case 5: // DELETE_FLAG
return Current.DELETE_FLAG;
case 6: // LW_DATE
return Current.LW_DATE;
case 7: // LW_TIME
return Current.LW_TIME;
case 8: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // FAMILY_KEY
return Current.FAMILY_KEY == null;
case 2: // STREGISTRATION
return Current.STREGISTRATION == null;
case 3: // EMA_PERIOD
return Current.EMA_PERIOD == null;
case 4: // EMA_TRAMT
return Current.EMA_TRAMT == null;
case 5: // DELETE_FLAG
return Current.DELETE_FLAG == null;
case 6: // LW_DATE
return Current.LW_DATE == null;
case 7: // LW_TIME
return Current.LW_TIME == null;
case 8: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // FAMILY_KEY
return "FAMILY_KEY";
case 2: // STREGISTRATION
return "STREGISTRATION";
case 3: // EMA_PERIOD
return "EMA_PERIOD";
case 4: // EMA_TRAMT
return "EMA_TRAMT";
case 5: // DELETE_FLAG
return "DELETE_FLAG";
case 6: // LW_DATE
return "LW_DATE";
case 7: // LW_TIME
return "LW_TIME";
case 8: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "FAMILY_KEY":
return 1;
case "STREGISTRATION":
return 2;
case "EMA_PERIOD":
return 3;
case "EMA_TRAMT":
return 4;
case "DELETE_FLAG":
return 5;
case "LW_DATE":
return 6;
case "LW_TIME":
return 7;
case "LW_USER":
return 8;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
#if CORECLR
using System.Runtime.Loader;
#endif
using System.Reflection;
using System.IO;
class InstanceFieldTest : MyClass
{
public int Value;
}
class InstanceFieldTest2 : InstanceFieldTest
{
public int Value2;
}
[StructLayout(LayoutKind.Sequential)]
class InstanceFieldTestWithLayout : MyClassWithLayout
{
public int Value;
}
class GrowingBase
{
MyGrowingStruct s;
}
class InheritingFromGrowingBase : GrowingBase
{
public int x;
}
class Program
{
static void TestVirtualMethodCalls()
{
var o = new MyClass();
Assert.AreEqual(o.VirtualMethod(), "Virtual method result");
var iface = (IMyInterface)o;
Assert.AreEqual(iface.InterfaceMethod(" "), "Interface result");
Assert.AreEqual(MyClass.TestInterfaceMethod(iface, "+"), "Interface+result");
}
static void TestMovedVirtualMethods()
{
var o = new MyChildClass();
Assert.AreEqual(o.MovedToBaseClass(), "MovedToBaseClass");
Assert.AreEqual(o.ChangedToVirtual(), "ChangedToVirtual");
if (!LLILCJitEnabled)
{
o = null;
try
{
o.MovedToBaseClass();
}
catch (NullReferenceException)
{
try
{
o.ChangedToVirtual();
}
catch (NullReferenceException)
{
return;
}
}
Assert.AreEqual("NullReferenceException", "thrown");
}
}
static void TestConstrainedMethodCalls()
{
using (MyStruct s = new MyStruct())
{
((Object)s).ToString();
}
}
static void TestConstrainedMethodCalls_Unsupported()
{
MyStruct s = new MyStruct();
s.ToString();
}
static void TestInterop()
{
// Verify both intra-module and inter-module PInvoke interop
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
MyClass.GetTickCount();
}
else
{
MyClass.GetCurrentThreadId();
}
MyClass.TestInterop();
}
static void TestStaticFields()
{
MyClass.StaticObjectField = 894;
MyClass.StaticLongField = 4392854;
MyClass.StaticNullableGuidField = new Guid("0D7E505F-E767-4FEF-AEEC-3243A3005673");
MyClass.ThreadStaticStringField = "Hello";
MyClass.ThreadStaticIntField = 735;
MyClass.ThreadStaticDateTimeField = new DateTime(2011, 1, 1);
MyClass.TestStaticFields();
#if false // TODO: Enable once LDFTN is supported
Task.Run(() => {
MyClass.ThreadStaticStringField = "Garbage";
MyClass.ThreadStaticIntField = 0xBAAD;
MyClass.ThreadStaticDateTimeField = DateTime.Now;
}).Wait();
#endif
Assert.AreEqual(MyClass.StaticObjectField, 894 + 12345678 /* + 1234 */);
Assert.AreEqual(MyClass.StaticLongField, (long)(4392854 * 456 /* * 45 */));
Assert.AreEqual(MyClass.StaticNullableGuidField, null);
Assert.AreEqual(MyClass.ThreadStaticStringField, "HelloWorld");
Assert.AreEqual(MyClass.ThreadStaticIntField, 735/78);
Assert.AreEqual(MyClass.ThreadStaticDateTimeField, new DateTime(2011, 1, 1) + new TimeSpan(123));
}
static void TestPreInitializedArray()
{
var a = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 };
int sum = 0;
foreach (var e in a) sum += e;
Assert.AreEqual(sum, 1023);
}
static void TestMultiDimmArray()
{
var a = new int[2,3,4];
a[0,1,2] = a[0,0,0] + a[1,1,1];
a.ToString();
}
static void TestGenericVirtualMethod()
{
var o = new MyGeneric<String, Object>();
Assert.AreEqual(o.GenericVirtualMethod<Program, IEnumerable<String>>(),
"System.StringSystem.ObjectProgramSystem.Collections.Generic.IEnumerable`1[System.String]");
}
static void TestMovedGenericVirtualMethod()
{
var o = new MyChildGeneric<Object>();
Assert.AreEqual(o.MovedToBaseClass<WeakReference>(), typeof(List<WeakReference>).ToString());
Assert.AreEqual(o.ChangedToVirtual<WeakReference>(), typeof(List<WeakReference>).ToString());
if (!LLILCJitEnabled)
{
o = null;
try
{
o.MovedToBaseClass<WeakReference>();
}
catch (NullReferenceException)
{
try
{
o.ChangedToVirtual<WeakReference>();
}
catch (NullReferenceException)
{
return;
}
}
Assert.AreEqual("NullReferenceException", "thrown");
}
}
static void TestInstanceFields()
{
var t = new InstanceFieldTest2();
t.Value = 123;
t.Value2 = 234;
t.InstanceField = 345;
Assert.AreEqual(typeof(InstanceFieldTest).GetRuntimeField("Value").GetValue(t), 123);
Assert.AreEqual(typeof(InstanceFieldTest2).GetRuntimeField("Value2").GetValue(t), 234);
Assert.AreEqual(typeof(MyClass).GetRuntimeField("InstanceField").GetValue(t), 345);
}
static void TestInstanceFieldsWithLayout()
{
var t = new InstanceFieldTestWithLayout();
t.Value = 123;
Assert.AreEqual(typeof(InstanceFieldTestWithLayout).GetRuntimeField("Value").GetValue(t), 123);
}
static void TestInheritingFromGrowingBase()
{
var o = new InheritingFromGrowingBase();
o.x = 6780;
Assert.AreEqual(typeof(InheritingFromGrowingBase).GetRuntimeField("x").GetValue(o), 6780);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestGrowingStruct()
{
MyGrowingStruct s = MyGrowingStruct.Construct();
MyGrowingStruct.Check(ref s);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestChangingStruct()
{
MyChangingStruct s = MyChangingStruct.Construct();
s.x++;
MyChangingStruct.Check(ref s);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestChangingHFAStruct()
{
MyChangingHFAStruct s = MyChangingHFAStruct.Construct();
MyChangingHFAStruct.Check(s);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestGetType()
{
new MyClass().GetType().ToString();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestStaticBaseCSE()
{
// There should be just one call to CORINFO_HELP_READYTORUN_STATIC_BASE
// in the generated code.
s++;
s++;
Assert.AreEqual(s, 2);
s = 0;
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestIsInstCSE()
{
// There should be just one call to CORINFO_HELP_READYTORUN_ISINSTANCEOF
// in the generated code.
object o1 = (s < 1) ? (object)"foo" : (object)1;
Assert.AreEqual(o1 is string, true);
Assert.AreEqual(o1 is string, true);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestCastClassCSE()
{
// There should be just one call to CORINFO_HELP_READYTORUN_CHKCAST
// in the generated code.
object o1 = (s < 1) ? (object)"foo" : (object)1;
string str1 = (string)o1;
string str2 = (string)o1;
Assert.AreEqual(str1, str2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
static void TestRangeCheckElimination()
{
// Range checks for array accesses should be eliminated by the compiler.
int[] array = new int[5];
array[2] = 2;
Assert.AreEqual(array[2], 2);
}
#if CORECLR
class MyLoadContext : AssemblyLoadContext
{
public MyLoadContext()
{
}
public void TestMultipleLoads()
{
Assembly a = LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), "test.ni.dll"));
Assert.AreEqual(AssemblyLoadContext.GetLoadContext(a), this);
}
protected override Assembly Load(AssemblyName an)
{
throw new NotImplementedException();
}
}
static void TestMultipleLoads()
{
if (!LLILCJitEnabled) {
try
{
new MyLoadContext().TestMultipleLoads();
}
catch (FileLoadException e)
{
Assert.AreEqual(e.ToString().Contains("Native image cannot be loaded multiple times"), true);
return;
}
Assert.AreEqual("FileLoadException", "thrown");
}
}
#endif
static void TestFieldLayoutNGenMixAndMatch()
{
// This test is verifying consistent field layout when ReadyToRun images are combined with NGen images
// "ngen install /nodependencies main.exe" to exercise the interesting case
var o = new ByteChildClass(67);
Assert.AreEqual(o.ChildByte, (byte)67);
}
static void RunAllTests()
{
TestVirtualMethodCalls();
TestMovedVirtualMethods();
TestConstrainedMethodCalls();
TestConstrainedMethodCalls_Unsupported();
TestInterop();
TestStaticFields();
TestPreInitializedArray();
TestMultiDimmArray();
TestGenericVirtualMethod();
TestMovedGenericVirtualMethod();
TestInstanceFields();
TestInstanceFieldsWithLayout();
TestInheritingFromGrowingBase();
TestGrowingStruct();
TestChangingStruct();
TestChangingHFAStruct();
TestGetType();
#if CORECLR
TestMultipleLoads();
#endif
TestFieldLayoutNGenMixAndMatch();
TestStaticBaseCSE();
TestIsInstCSE();
TestCastClassCSE();
TestRangeCheckElimination();
}
static int Main()
{
// Code compiled by LLILC jit can't catch exceptions yet so the tests
// don't throw them if LLILC jit is enabled. This should be removed once
// exception catching is supported by LLILC jit.
string AltJitName = System.Environment.GetEnvironmentVariable("complus_altjitname");
LLILCJitEnabled =
((AltJitName != null) && AltJitName.ToLower().StartsWith("llilcjit") &&
((System.Environment.GetEnvironmentVariable("complus_altjit") != null) ||
(System.Environment.GetEnvironmentVariable("complus_altjitngen") != null)));
// Run all tests 3x times to exercise both slow and fast paths work
for (int i = 0; i < 3; i++)
RunAllTests();
Console.WriteLine("PASSED");
return Assert.HasAssertFired ? 1 : 100;
}
static bool LLILCJitEnabled;
static int s;
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Components
// File : CodeBlockConfigDlg.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 01/23/2009
// Note : Copyright 2006-2009, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a form that is used to configure the settings for the
// Code Block Component.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.3.3.0 11/24/2006 EFW Created the code
// 1.4.0.0 02/12/2007 EFW Added code block language filter option, default
// title option, and "Copy" image URL.
// 1.6.0.5 03/05/2008 EFW Added support for the keepSeeTags attribute.
// 1.6.0.7 04/05/2008 EFW JavaScript and XAMl are now treated as separate
// languages for proper language filter support.
// 1.8.0.0 08/15/2008 EFW Added option to allow missing source/regions
// 1.8.0.1 01/23/2009 EFW Added removeRegionMarkers option
//=============================================================================
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
namespace SandcastleBuilder.Components
{
/// <summary>
/// This form is used to configure the settings for the
/// <see cref="CodeBlockComponent"/>.
/// </summary>
internal partial class CodeBlockConfigDlg : Form
{
#region Private data members
//=====================================================================
private static string[] languages = { "none", "cs", "vbnet", "cpp",
"c", "javascript", "jscriptnet", "jsharp", "vbscript", "xml",
"xaml", "python", "sql", "pshell" };
private XElement config; // The configuration
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This is used to return the configuration information
/// </summary>
public string Configuration
{
get { return config.ToString(); }
}
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="currentConfig">The current XML configuration
/// XML fragment</param>
public CodeBlockConfigDlg(string currentConfig)
{
XElement node;
XAttribute attr;
InitializeComponent();
cboLanguage.SelectedIndex = 1;
lnkCodePlexSHFB.Links[0].LinkData = "http://SHFB.CodePlex.com";
// Load the current settings
config = XElement.Parse(currentConfig);
node = config.Element("basePath");
if(node != null)
txtBasePath.Text = node.Attribute("value").Value;
node = config.Element("languageFilter");
if(node != null)
chkLanguageFilter.Checked = (bool)node.Attribute("value");
node = config.Element("allowMissingSource");
if(node != null)
chkAllowMissingSource.Checked = (bool)node.Attribute("value");
node = config.Element("removeRegionMarkers");
if(node != null)
chkRemoveRegionMarkers.Checked = (bool)node.Attribute("value");
node = config.Element("colorizer");
txtSyntaxFile.Text = node.Attribute("syntaxFile").Value;
txtStyleFile.Text = node.Attribute("styleFile").Value;
txtCopyImageUrl.Text = node.Attribute("copyImageUrl").Value;
attr = node.Attribute("language");
if(attr != null)
for(int i = 0; i < languages.Length; i++)
if(attr.Value == languages[i])
{
cboLanguage.SelectedIndex = i;
break;
}
attr = node.Attribute("tabSize");
if(attr != null)
udcTabSize.Value = (int)attr;
attr = node.Attribute("numberLines");
if(attr != null)
chkNumberLines.Checked = (bool)attr;
attr = node.Attribute("outlining");
if(attr != null)
chkOutlining.Checked = (bool)attr;
attr = node.Attribute("keepSeeTags");
if(attr != null)
chkKeepSeeTags.Checked = (bool)attr;
attr = node.Attribute("defaultTitle");
if(attr != null)
chkDefaultTitle.Checked = (bool)attr;
}
#endregion
#region Event handlers
//=====================================================================
/// <summary>
/// Close without saving
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Go to the CodePlex home page of the Sandcastle Help File Builder
/// project.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void lnkCodePlexSHFB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
System.Diagnostics.Process.Start((string)e.Link.LinkData);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show("Unable to launch link target. " +
"Reason: " + ex.Message, "Sandcastle Help File Builder",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
/// <summary>
/// Validate the configuration and save it
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnOK_Click(object sender, EventArgs e)
{
bool isValid = true;
txtBasePath.Text = txtBasePath.Text.Trim();
txtSyntaxFile.Text = txtSyntaxFile.Text.Trim();
txtStyleFile.Text = txtStyleFile.Text.Trim();
txtCopyImageUrl.Text = txtCopyImageUrl.Text.Trim();
epErrors.Clear();
if(txtSyntaxFile.Text.Length == 0)
{
epErrors.SetError(txtSyntaxFile,
"The syntax filename is required");
isValid = false;
}
if(txtStyleFile.Text.Length == 0)
{
epErrors.SetError(txtStyleFile,
"The XSLT style filename is required");
isValid = false;
}
if(txtCopyImageUrl.Text.Length == 0)
{
epErrors.SetError(txtCopyImageUrl,
"The \"Copy\" image URL is required");
isValid = false;
}
if(!isValid)
return;
// Store the changes
config.RemoveNodes();
config.Add(
new XElement("basePath",
new XAttribute("value", txtBasePath.Text)),
new XElement("languageFilter",
new XAttribute("value", chkLanguageFilter.Checked)),
new XElement("allowMissingSource",
new XAttribute("value", chkAllowMissingSource.Checked)),
new XElement("removeRegionMarkers",
new XAttribute("value", chkRemoveRegionMarkers.Checked)),
new XElement("colorizer",
new XAttribute("syntaxFile", txtSyntaxFile.Text),
new XAttribute("styleFile", txtStyleFile.Text),
new XAttribute("copyImageUrl", txtCopyImageUrl.Text),
new XAttribute("language", languages[cboLanguage.SelectedIndex]),
new XAttribute("tabSize", (int)udcTabSize.Value),
new XAttribute("numberLines", chkNumberLines.Checked),
new XAttribute("outlining", chkOutlining.Checked),
new XAttribute("keepSeeTags", chkKeepSeeTags.Checked),
new XAttribute("defaultTitle", chkDefaultTitle.Checked)));
this.DialogResult = DialogResult.OK;
this.Close();
}
/// <summary>
/// Select the base source folder
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnSelectFolder_Click(object sender, EventArgs e)
{
using(FolderBrowserDialog dlg = new FolderBrowserDialog())
{
dlg.Description = "Select the base source folder";
dlg.SelectedPath = Directory.GetCurrentDirectory();
// If selected, set the new folder
if(dlg.ShowDialog() == DialogResult.OK)
txtBasePath.Text = dlg.SelectedPath + @"\";
}
}
/// <summary>
/// Select the syntax for style file
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void SelectFile_Click(object sender, EventArgs e)
{
Button b = sender as Button;
TextBox t;
using(OpenFileDialog dlg = new OpenFileDialog())
{
if(b == btnSelectSyntax)
{
t = txtSyntaxFile;
dlg.Title = "Select the language syntax file";
dlg.Filter = "XML files (*.xml)|*.xml|" +
"All Files (*.*)|*.*";
dlg.DefaultExt = "xml";
}
else
{
t = txtStyleFile;
dlg.Title = "Select the XSL transformation file";
dlg.Filter = "XSL files (*.xsl, *.xslt)|*.xsl;*.xslt|" +
"All Files (*.*)|*.*";
dlg.DefaultExt = "xsl";
}
dlg.InitialDirectory = Directory.GetCurrentDirectory();
// If selected, set the filename
if(dlg.ShowDialog() == DialogResult.OK)
t.Text = dlg.FileName;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace System.Xml
{
internal class Base64Decoder : IncrementalReadDecoder
{
//
// Fields
//
private byte[] _buffer;
private int _startIndex;
private int _curIndex;
private int _endIndex;
private int _bits;
private int _bitsFilled;
private static readonly String s_charsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static readonly byte[] s_mapBase64 = ConstructMapBase64();
private const int MaxValidChar = (int)'z';
private const byte Invalid = unchecked((byte)-1);
//
// IncrementalReadDecoder interface
//
internal override int DecodedCount
{
get
{
return _curIndex - _startIndex;
}
}
internal override bool IsFull
{
get
{
return _curIndex == _endIndex;
}
}
[System.Security.SecuritySafeCritical]
internal override unsafe int Decode(char[] chars, int startPos, int len)
{
if (chars == null)
{
throw new ArgumentNullException(nameof(chars));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException(nameof(startPos));
}
if (chars.Length - startPos < len)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = &chars[startPos])
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
[System.Security.SecuritySafeCritical]
internal override unsafe int Decode(string str, int startPos, int len)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (len < 0)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (startPos < 0)
{
throw new ArgumentOutOfRangeException(nameof(startPos));
}
if (str.Length - startPos < len)
{
throw new ArgumentOutOfRangeException(nameof(len));
}
if (len == 0)
{
return 0;
}
int bytesDecoded, charsDecoded;
fixed (char* pChars = str)
{
fixed (byte* pBytes = &_buffer[_curIndex])
{
Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded);
}
}
_curIndex += bytesDecoded;
return charsDecoded;
}
internal override void Reset()
{
_bitsFilled = 0;
_bits = 0;
}
internal override void SetNextOutputBuffer(Array buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(index >= 0);
Debug.Assert(buffer.Length - index >= count);
Debug.Assert((buffer as byte[]) != null);
_buffer = (byte[])buffer;
_startIndex = index;
_curIndex = index;
_endIndex = index + count;
}
//
// Private methods
//
private static byte[] ConstructMapBase64()
{
byte[] mapBase64 = new byte[MaxValidChar + 1];
for (int i = 0; i < mapBase64.Length; i++)
{
mapBase64[i] = Invalid;
}
for (int i = 0; i < s_charsBase64.Length; i++)
{
mapBase64[(int)s_charsBase64[i]] = (byte)i;
}
return mapBase64;
}
[System.Security.SecurityCritical]
private unsafe void Decode(char* pChars, char* pCharsEndPos,
byte* pBytes, byte* pBytesEndPos,
out int charsDecoded, out int bytesDecoded)
{
#if DEBUG
Debug.Assert(pCharsEndPos - pChars >= 0);
Debug.Assert(pBytesEndPos - pBytes >= 0);
#endif
// walk hex digits pairing them up and shoving the value of each pair into a byte
byte* pByte = pBytes;
char* pChar = pChars;
int b = _bits;
int bFilled = _bitsFilled;
XmlCharType xmlCharType = XmlCharType.Instance;
while (pChar < pCharsEndPos && pByte < pBytesEndPos)
{
char ch = *pChar;
// end?
if (ch == '=')
{
break;
}
pChar++;
// ignore whitespace
if (xmlCharType.IsWhiteSpace(ch))
{
continue;
}
int digit;
if (ch > 122 || (digit = s_mapBase64[ch]) == Invalid)
{
throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars)));
}
b = (b << 6) | digit;
bFilled += 6;
if (bFilled >= 8)
{
// get top eight valid bits
*pByte++ = (byte)((b >> (bFilled - 8)) & 0xFF);
bFilled -= 8;
if (pByte == pBytesEndPos)
{
goto Return;
}
}
}
if (pChar < pCharsEndPos && *pChar == '=')
{
bFilled = 0;
// ignore padding chars
do
{
pChar++;
} while (pChar < pCharsEndPos && *pChar == '=');
// ignore whitespace after the padding chars
if (pChar < pCharsEndPos)
{
do
{
if (!(xmlCharType.IsWhiteSpace(*pChar++)))
{
throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars)));
}
} while (pChar < pCharsEndPos);
}
}
Return:
_bits = b;
_bitsFilled = bFilled;
bytesDecoded = (int)(pByte - pBytes);
charsDecoded = (int)(pChar - pChars);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MachineKeySection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Configuration
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Web.Hosting;
using System.Web.Security.Cryptography;
using System.Web.Util;
using System.Xml;
/******************************************************************
* !! NOTICE !! *
* The cryptographic code in this class is a legacy code base. *
* New code should not call into these crypto APIs; use the APIs *
* provided by AspNetCryptoServiceProvider instead. *
******************************************************************/
/******************************************************************
* !! WARNING !! *
* This class contains cryptographic code. If you make changes to *
* this class, please have it reviewed by the appropriate people. *
******************************************************************/
/*
<!-- validation="[SHA1|MD5|3DES|AES|HMACSHA256|HMACSHA384|HMACSHA512|alg:algorithm_name]" decryption="[AES|EDES" -->
<machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" decryption="[AES|3DES]" validation="HMACSHA256" compatibilityMode="[Framework20SP1|Framework20SP2]" />
*/
public sealed class MachineKeySection : ConfigurationSection
{
private const string OBSOLETE_CRYPTO_API_MESSAGE = "This API exists only for backward compatibility; new framework features that require cryptographic services MUST NOT call it. New features should use the AspNetCryptoServiceProvider class instead.";
// If the default validation algorithm changes, be sure to update the _HashSize and _AutoGenValidationKeySize fields also.
internal const string DefaultValidationAlgorithm = "HMACSHA256";
internal const MachineKeyValidation DefaultValidation = MachineKeyValidation.SHA1;
internal const string DefaultDataProtectorType = "";
internal const string DefaultApplicationName = "";
private static ConfigurationPropertyCollection _properties;
private static readonly ConfigurationProperty _propValidationKey =
new ConfigurationProperty("validationKey", typeof(string), "AutoGenerate,IsolateApps", StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDecryptionKey =
new ConfigurationProperty("decryptionKey", typeof(string),"AutoGenerate,IsolateApps",StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDecryption =
new ConfigurationProperty("decryption", typeof(string), "Auto", StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propValidation =
new ConfigurationProperty("validation", typeof(string), DefaultValidationAlgorithm, StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propDataProtectorType =
new ConfigurationProperty("dataProtectorType", typeof(string), DefaultDataProtectorType, StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, null, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propApplicationName =
new ConfigurationProperty("applicationName", typeof(string), DefaultApplicationName, StdValidatorsAndConverters.WhiteSpaceTrimStringConverter, null, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty _propCompatibilityMode =
new ConfigurationProperty("compatibilityMode", typeof(MachineKeyCompatibilityMode), MachineKeyCompatibilityMode.Framework20SP1, null, null, ConfigurationPropertyOptions.None);
private static object s_initLock = new object();
private static bool s_initComplete = false;
private static MachineKeySection s_config;
private static RNGCryptoServiceProvider s_randomNumberGenerator;
private static SymmetricAlgorithm s_oSymAlgoDecryption;
private static SymmetricAlgorithm s_oSymAlgoValidation;
private static byte[] s_validationKey;
private static byte[] s_inner = null;
private static byte[] s_outer = null;
internal static bool IsDecryptionKeyAutogenerated { get { EnsureConfig(); return s_config.AutogenKey; } }
private bool _AutogenKey;
internal bool AutogenKey { get { RuntimeDataInitialize(); return _AutogenKey; } }
private byte[] _ValidationKey;
private byte[] _DecryptionKey;
private bool DataInitialized = false;
private static bool _CustomValidationTypeIsKeyed;
private static string _CustomValidationName;
private static int _IVLengthDecryption = 64;
private static int _IVLengthValidation = 64;
private static int _HashSize = HMACSHA256_HASH_SIZE;
private static int _AutoGenValidationKeySize = HMACSHA256_KEY_SIZE;
private static int _AutoGenDecryptionKeySize = 24;
private static bool _UseHMACSHA = true;
private static bool _UsingCustomEncryption = false;
private static SymmetricAlgorithm s_oSymAlgoLegacy;
private const int MD5_KEY_SIZE = 64;
private const int MD5_HASH_SIZE = 16;
private const int SHA1_KEY_SIZE = 64;
private const int HMACSHA256_KEY_SIZE = 64;
private const int HMACSHA384_KEY_SIZE = 128;
private const int HMACSHA512_KEY_SIZE = 128;
private const int SHA1_HASH_SIZE = 20;
private const int HMACSHA256_HASH_SIZE = 32;
private const int HMACSHA384_HASH_SIZE = 48;
private const int HMACSHA512_HASH_SIZE = 64;
private const string ALGO_PREFIX = "alg:";
internal byte[] ValidationKeyInternal { get { RuntimeDataInitialize(); return (byte[])_ValidationKey.Clone(); } }
internal byte[] DecryptionKeyInternal { get { RuntimeDataInitialize(); return (byte[])_DecryptionKey.Clone(); } }
internal static int HashSize { get { s_config.RuntimeDataInitialize(); return _HashSize; } }
internal static int ValidationKeySize { get { s_config.RuntimeDataInitialize(); return _AutoGenValidationKeySize; } }
static MachineKeySection()
{
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propValidationKey);
_properties.Add(_propDecryptionKey);
_properties.Add(_propValidation);
_properties.Add(_propDecryption);
_properties.Add(_propCompatibilityMode);
_properties.Add(_propDataProtectorType);
_properties.Add(_propApplicationName);
}
public MachineKeySection()
{
}
internal static MachineKeyCompatibilityMode CompatMode
{
get
{
return GetApplicationConfig().CompatibilityMode;
}
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
[ConfigurationProperty("validationKey", DefaultValue = "AutoGenerate,IsolateApps")]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string ValidationKey
{
get
{
return (string)base[_propValidationKey];
}
set
{
base[_propValidationKey] = value;
}
}
[ConfigurationProperty("decryptionKey", DefaultValue = "AutoGenerate,IsolateApps")]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string DecryptionKey
{
get
{
return (string)base[_propDecryptionKey];
}
set
{
base[_propDecryptionKey] = value;
}
}
[ConfigurationProperty("decryption", DefaultValue = "Auto")]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string Decryption {
get {
string s = GetDecryptionAttributeSkipValidation();
if (s != "Auto" && s != "AES" && s != "3DES" && s != "DES" && !s.StartsWith(ALGO_PREFIX, StringComparison.Ordinal))
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum), ElementInformation.Properties["decryption"].Source, ElementInformation.Properties["decryption"].LineNumber);
return s;
}
set {
if (value != "AES" && value != "3DES" && value != "Auto" && value != "DES" && !value.StartsWith(ALGO_PREFIX, StringComparison.Ordinal))
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum), ElementInformation.Properties["decryption"].Source, ElementInformation.Properties["decryption"].LineNumber);
base[_propDecryption] = value;
}
}
// returns the value in the 'decryption' attribute (or the default value if null) without throwing an exception if the value is malformed
internal string GetDecryptionAttributeSkipValidation() {
return (string)base[_propDecryption] ?? "Auto";
}
private bool _validationIsCached;
private string _cachedValidation;
private MachineKeyValidation _cachedValidationEnum;
[ConfigurationProperty("validation", DefaultValue = DefaultValidationAlgorithm)]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
[StringValidator(MinLength = 1)]
public string ValidationAlgorithm
{
get {
if (!_validationIsCached)
CacheValidation();
return _cachedValidation;
} set {
if (_validationIsCached && value == _cachedValidation)
return;
if (value == null)
value = DefaultValidationAlgorithm;
_cachedValidationEnum = MachineKeyValidationConverter.ConvertToEnum(value);
_cachedValidation = value;
base[_propValidation] = value;
_validationIsCached = true;
}
}
// returns the value in the 'validation' attribute (or the default value if null) without throwing an exception if the value is malformed
internal string GetValidationAttributeSkipValidation() {
return (string)base[_propValidation] ?? DefaultValidationAlgorithm;
}
private void CacheValidation()
{
_cachedValidation = GetValidationAttributeSkipValidation();
_cachedValidationEnum = MachineKeyValidationConverter.ConvertToEnum(_cachedValidation);
_validationIsCached = true;
}
public MachineKeyValidation Validation {
get {
if (_validationIsCached == false)
CacheValidation();
return _cachedValidationEnum;
} set {
if (_validationIsCached && value == _cachedValidationEnum)
return;
_cachedValidation = MachineKeyValidationConverter.ConvertFromEnum(value);
_cachedValidationEnum = value;
base[_propValidation] = _cachedValidation;
_validationIsCached = true;
}
}
[ConfigurationProperty("dataProtectorType", DefaultValue = DefaultDataProtectorType)]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
public string DataProtectorType {
get {
return (string)base[_propDataProtectorType];
}
set {
base[_propDataProtectorType] = value;
}
}
[ConfigurationProperty("applicationName", DefaultValue = DefaultApplicationName)]
[TypeConverter(typeof(WhiteSpaceTrimStringConverter))]
public string ApplicationName {
get {
return (string)base[_propApplicationName];
}
set {
base[_propApplicationName] = value;
}
}
private MachineKeyCompatibilityMode _compatibilityMode = (MachineKeyCompatibilityMode)(-1); // dummy value used to mean uninitialized
[ConfigurationProperty("compatibilityMode", DefaultValue = MachineKeyCompatibilityMode.Framework20SP1)]
public MachineKeyCompatibilityMode CompatibilityMode
{
get
{
// the compatibility mode is cached since it's queried frequently
if (_compatibilityMode < 0) {
_compatibilityMode = (MachineKeyCompatibilityMode)base[_propCompatibilityMode];
}
return _compatibilityMode;
}
set
{
base[_propCompatibilityMode] = value;
_compatibilityMode = value;
}
}
protected override void Reset(ConfigurationElement parentElement)
{
MachineKeySection parent = parentElement as MachineKeySection;
base.Reset(parentElement);
// copy the privates from the parent.
if (parent != null)
{
// _ValidationKey = parent.ValidationKeyInternal;
// _DecryptionKey = parent.DecryptionKeyInternal;
// _AutogenKey = parent.AutogenKey;
}
}
private void RuntimeDataInitialize()
{
if (DataInitialized == false)
{
byte [] bKeysRandom = null;
bool fNonHttpApp = false;
string strKey = ValidationKey;
string appName = HttpRuntime.AppDomainAppVirtualPath;
string appId = HttpRuntime.AppDomainAppId;
InitValidationAndEncyptionSizes();
if( appName == null )
{
#if !FEATURE_PAL // FEATURE_PAL does not enable cryptography
// FEATURE_PAL
appName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
if( ValidationKey.Contains( "AutoGenerate" ) ||
DecryptionKey.Contains( "AutoGenerate" ) )
{
fNonHttpApp = true;
bKeysRandom = new byte[ _AutoGenValidationKeySize + _AutoGenDecryptionKeySize ];
// Gernerate random keys
RandomNumberGenerator.GetBytes(bKeysRandom);
}
#endif // !FEATURE_PAL
}
bool fAppIdSpecific = StringUtil.StringEndsWith(strKey, ",IsolateByAppId");
if (fAppIdSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateByAppId".Length);
}
bool fAppSpecific = StringUtil.StringEndsWith(strKey, ",IsolateApps");
if (fAppSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateApps".Length);
}
if (strKey == "AutoGenerate")
{ // case sensitive
_ValidationKey = new byte[_AutoGenValidationKeySize];
if( fNonHttpApp )
{
Buffer.BlockCopy( bKeysRandom, 0, _ValidationKey, 0, _AutoGenValidationKeySize);
}
else
{
Buffer.BlockCopy(HttpRuntime.s_autogenKeys, 0, _ValidationKey, 0, _AutoGenValidationKeySize);
}
}
else
{
if (strKey.Length < 40 || (strKey.Length & 0x1) == 1)
throw new ConfigurationErrorsException(SR.GetString(SR.Unable_to_get_cookie_authentication_validation_key, strKey.Length.ToString(CultureInfo.InvariantCulture)), ElementInformation.Properties["validationKey"].Source, ElementInformation.Properties["validationKey"].LineNumber);
#pragma warning disable 618 // obsolete
_ValidationKey = HexStringToByteArray(strKey);
#pragma warning restore 618
if (_ValidationKey == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_validation_key), ElementInformation.Properties["validationKey"].Source, ElementInformation.Properties["validationKey"].LineNumber);
}
if (fAppSpecific)
{
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode( appName );
_ValidationKey[0] = (byte)(dwCode & 0xff);
_ValidationKey[1] = (byte)((dwCode & 0xff00) >> 8);
_ValidationKey[2] = (byte)((dwCode & 0xff0000) >> 16);
_ValidationKey[3] = (byte)((dwCode & 0xff000000) >> 24);
}
if (fAppIdSpecific)
{
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode( appId );
_ValidationKey[4] = (byte)(dwCode & 0xff);
_ValidationKey[5] = (byte)((dwCode & 0xff00) >> 8);
_ValidationKey[6] = (byte)((dwCode & 0xff0000) >> 16);
_ValidationKey[7] = (byte)((dwCode & 0xff000000) >> 24);
}
strKey = DecryptionKey;
fAppIdSpecific = StringUtil.StringEndsWith(strKey, ",IsolateByAppId");
if (fAppIdSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateByAppId".Length);
}
fAppSpecific = StringUtil.StringEndsWith(strKey, ",IsolateApps");
if (fAppSpecific)
{
strKey = strKey.Substring(0, strKey.Length - ",IsolateApps".Length);
}
if (strKey == "AutoGenerate")
{ // case sensitive
_DecryptionKey = new byte[_AutoGenDecryptionKeySize];
if( fNonHttpApp )
{
Buffer.BlockCopy( bKeysRandom, _AutoGenValidationKeySize, _DecryptionKey, 0, _AutoGenDecryptionKeySize);
}
else
{
Buffer.BlockCopy(HttpRuntime.s_autogenKeys, _AutoGenValidationKeySize, _DecryptionKey, 0, _AutoGenDecryptionKeySize);
}
_AutogenKey = true;
}
else
{
_AutogenKey = false;
if ((strKey.Length & 1) != 0)
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_decryption_key), ElementInformation.Properties["decryptionKey"].Source, ElementInformation.Properties["decryptionKey"].LineNumber);
#pragma warning disable 618 // obsolete
_DecryptionKey = HexStringToByteArray(strKey);
#pragma warning restore 618
if (_DecryptionKey == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_decryption_key), ElementInformation.Properties["decryptionKey"].Source, ElementInformation.Properties["decryptionKey"].LineNumber);
}
if (fAppSpecific)
{
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode(appName);
_DecryptionKey[0] = (byte)(dwCode & 0xff);
_DecryptionKey[1] = (byte)((dwCode & 0xff00) >> 8);
_DecryptionKey[2] = (byte)((dwCode & 0xff0000) >> 16);
_DecryptionKey[3] = (byte)((dwCode & 0xff000000) >> 24);
}
if (fAppIdSpecific)
{
int dwCode = StringComparer.InvariantCultureIgnoreCase.GetHashCode(appId);
_DecryptionKey[4] = (byte)(dwCode & 0xff);
_DecryptionKey[5] = (byte)((dwCode & 0xff00) >> 8);
_DecryptionKey[6] = (byte)((dwCode & 0xff0000) >> 16);
_DecryptionKey[7] = (byte)((dwCode & 0xff000000) >> 24);
}
DataInitialized = true;
}
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length)
{
// MSRC 10405: IVType.Hash has been removed; new default behavior is to use IVType.Random.
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, false, false, IVType.Random);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length, bool useValidationSymAlgo)
{
// MSRC 10405: IVType.Hash has been removed; new default behavior is to use IVType.Random.
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, useValidationSymAlgo, false, IVType.Random);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length,
bool useValidationSymAlgo, bool useLegacyMode, IVType ivType)
{
// MSRC 10405: Encryption is not sufficient to prevent a malicious user from tampering with the data, and the result of decryption can
// be used to discover information about the plaintext (such as via a padding or decryption oracle). We must sign anything that we
// encrypt to ensure that end users can't abuse our encryption routines.
// the new encrypt-then-sign behavior for everything EXCEPT Membership / MachineKey. We need to make it very clear that setting this
// to 'false' is a Very Bad Thing(tm).
return EncryptOrDecryptData(fEncrypt, buf, modifier, start, length, useValidationSymAlgo, useLegacyMode, ivType, !AppSettings.UseLegacyEncryption);
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] EncryptOrDecryptData(bool fEncrypt, byte[] buf, byte[] modifier, int start, int length,
bool useValidationSymAlgo, bool useLegacyMode, IVType ivType, bool signData)
{
/* This algorithm is used to perform encryption or decryption of a buffer, along with optional signing (for encryption)
* or signature verification (for decryption). Possible operation modes are:
*
* ENCRYPT + SIGN DATA (fEncrypt = true, signData = true)
* Input: buf represents plaintext to encrypt, modifier represents data to be appended to buf (but isn't part of the plaintext itself)
* Output: E(iv + buf + modifier) + HMAC(E(iv + buf + modifier))
*
* ONLY ENCRYPT DATA (fEncrypt = true, signData = false)
* Input: buf represents plaintext to encrypt, modifier represents data to be appended to buf (but isn't part of the plaintext itself)
* Output: E(iv + buf + modifier)
*
* VERIFY + DECRYPT DATA (fEncrypt = false, signData = true)
* Input: buf represents ciphertext to decrypt, modifier represents data to be removed from the end of the plaintext (since it's not really plaintext data)
* Input (buf): E(iv + m + modifier) + HMAC(E(iv + m + modifier))
* Output: m
*
* ONLY DECRYPT DATA (fEncrypt = false, signData = false)
* Input: buf represents ciphertext to decrypt, modifier represents data to be removed from the end of the plaintext (since it's not really plaintext data)
* Input (buf): E(iv + plaintext + modifier)
* Output: m
*
* The 'iv' in the above descriptions isn't an actual IV. Rather, if ivType = IVType.Random, we'll prepend random bytes ('iv')
* to the plaintext before feeding it to the crypto algorithms. Introducing randomness early in the algorithm prevents users
* from inspecting two ciphertexts to see if the plaintexts are related. If ivType = IVType.None, then 'iv' is simply
* an empty string. If ivType = IVType.Hash, we use a non-keyed hash of the plaintext.
*
* The 'modifier' in the above descriptions is a piece of metadata that should be encrypted along with the plaintext but
* which isn't actually part of the plaintext itself. It can be used for storing things like the user name for whom this
* plaintext was generated, the page that generated the plaintext, etc. On decryption, the modifier parameter is compared
* against the modifier stored in the crypto stream, and it is stripped from the message before the plaintext is returned.
*
* In all cases, if something goes wrong (e.g. invalid padding, invalid signature, invalid modifier, etc.), a generic exception is thrown.
*/
try {
EnsureConfig();
if (!fEncrypt && signData) {
if (start != 0 || length != buf.Length) {
// These transformations assume that we're operating on buf in its entirety and
// not on any subset of buf, so we'll just replace buf with the particular subset
// we're interested in.
byte[] bTemp = new byte[length];
Buffer.BlockCopy(buf, start, bTemp, 0, length);
buf = bTemp;
start = 0;
}
// buf actually contains E(iv + m + modifier) + HMAC(E(iv + m + modifier)), so we need to verify and strip off the signature
buf = GetUnHashedData(buf);
// At this point, buf contains only E(iv + m + modifier) if the signature check succeeded.
if (buf == null) {
// signature verification failed
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
// need to fix up again since GetUnhashedData() returned a different array
length = buf.Length;
}
if (useLegacyMode)
useLegacyMode = _UsingCustomEncryption; // only use legacy mode for custom algorithms
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ICryptoTransform cryptoTransform = GetCryptoTransform(fEncrypt, useValidationSymAlgo, useLegacyMode);
CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write);
// DevDiv Bugs 137864: Add IV to beginning of data to be encrypted.
// IVType.None is used by MembershipProvider which requires compatibility even in SP2 mode (and will set signData = false).
// MSRC 10405: If signData is set to true, we must generate an IV.
bool createIV = signData || ((ivType != IVType.None) && (CompatMode > MachineKeyCompatibilityMode.Framework20SP1));
if (fEncrypt && createIV)
{
int ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption);
byte[] iv = null;
switch (ivType) {
case IVType.Hash:
// iv := H(buf)
iv = GetIVHash(buf, ivLength);
break;
case IVType.Random:
// iv := [random]
iv = new byte[ivLength];
RandomNumberGenerator.GetBytes(iv);
break;
}
Debug.Assert(iv != null, "Invalid value for IVType: " + ivType.ToString("G"));
cs.Write(iv, 0, iv.Length);
}
cs.Write(buf, start, length);
if (fEncrypt && modifier != null)
{
cs.Write(modifier, 0, modifier.Length);
}
cs.FlushFinalBlock();
byte[] paddedData = ms.ToArray();
// At this point:
// If fEncrypt = true (encrypting), paddedData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), paddedData := iv + plaintext + modifier
byte[] bData;
cs.Close();
// In ASP.NET 2.0, we pool ICryptoTransform objects, and this returns that ICryptoTransform
// to the pool. In ASP.NET 4.0, this just disposes of the ICryptoTransform object.
ReturnCryptoTransform(fEncrypt, cryptoTransform, useValidationSymAlgo, useLegacyMode);
// DevDiv Bugs 137864: Strip IV from beginning of unencrypted data
if (!fEncrypt && createIV)
{
// strip off the first bytes that were random bits
int ivLength = (useValidationSymAlgo ? _IVLengthValidation : _IVLengthDecryption);
int bDataLength = paddedData.Length - ivLength;
if (bDataLength < 0) {
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
bData = new byte[bDataLength];
Buffer.BlockCopy(paddedData, ivLength, bData, 0, bDataLength);
}
else
{
bData = paddedData;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), bData := plaintext + modifier
if (!fEncrypt && modifier != null && modifier.Length > 0)
{
// MSRC 10405: Crypto board suggests blinding where signature failed
// to prevent timing attacks.
bool modifierCheckFailed = false;
for(int iter=0; iter<modifier.Length; iter++)
if (bData[bData.Length - modifier.Length + iter] != modifier[iter])
modifierCheckFailed = true;
if (modifierCheckFailed) {
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
byte[] bData2 = new byte[bData.Length - modifier.Length];
Buffer.BlockCopy(bData, 0, bData2, 0, bData2.Length);
bData = bData2;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier)
// If fEncrypt = false (decrypting), bData := plaintext
if (fEncrypt && signData) {
byte[] hmac = HashData(bData, null, 0, bData.Length);
byte[] bData2 = new byte[bData.Length + hmac.Length];
Buffer.BlockCopy(bData, 0, bData2, 0, bData.Length);
Buffer.BlockCopy(hmac, 0, bData2, bData.Length, hmac.Length);
bData = bData2;
}
// At this point:
// If fEncrypt = true (encrypting), bData := Enc(iv + buf + modifier) + HMAC(Enc(iv + buf + modifier))
// If fEncrypt = false (decrypting), bData := plaintext
// And we're done
return bData;
} catch {
// It's important that we don't propagate the original exception here as we don't want a production
// server which has unintentionally left YSODs enabled to leak cryptographic information.
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
}
}
private static byte[] GetIVHash(byte[] buf, int ivLength)
{
// return an IV that is computed as a hash of the buffer
int bytesToWrite = ivLength;
int bytesWritten = 0;
byte[] iv = new byte[ivLength];
// get SHA1 hash of the buffer and copy to the IV.
// if hash length is less than IV length, re-hash the hash and
// append until IV is full.
byte[] hash = buf;
while (bytesWritten < ivLength)
{
byte[] newHash = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetSHA1Hash(hash, hash.Length, newHash, newHash.Length);
Marshal.ThrowExceptionForHR(hr);
hash = newHash;
int bytesToCopy = Math.Min(_HashSize, bytesToWrite);
Buffer.BlockCopy(hash, 0, iv, bytesWritten, bytesToCopy);
bytesWritten += bytesToCopy;
bytesToWrite -= bytesToCopy;
}
return iv;
}
private static RNGCryptoServiceProvider RandomNumberGenerator {
get {
if (s_randomNumberGenerator == null) {
s_randomNumberGenerator = new RNGCryptoServiceProvider();
}
return s_randomNumberGenerator;
}
}
private static void SetInnerOuterKeys(byte[] validationKey, ref byte[] inner, ref byte[] outer) {
byte[] key = null;
if (validationKey.Length > _AutoGenValidationKeySize)
{
key = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetSHA1Hash(validationKey, validationKey.Length, key, key.Length);
Marshal.ThrowExceptionForHR(hr);
}
if (inner == null)
inner = new byte[_AutoGenValidationKeySize];
if (outer == null)
outer = new byte[_AutoGenValidationKeySize];
int i;
for (i = 0; i < _AutoGenValidationKeySize; i++) {
inner[i] = 0x36;
outer[i] = 0x5C;
}
for (i=0; i < validationKey.Length; i++) {
inner[i] ^= validationKey[i];
outer[i] ^= validationKey[i];
}
}
private static byte[] GetHMACSHA1Hash(byte[] buf, byte[] modifier, int start, int length) {
if (start < 0 || start > buf.Length)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "start"));
if (length < 0 || buf == null || (start + length) > buf.Length)
throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "length"));
byte[] hash = new byte[_HashSize];
int hr = UnsafeNativeMethods.GetHMACSHA1Hash(buf, start, length,
modifier, (modifier == null) ? 0 : modifier.Length,
s_inner, s_inner.Length, s_outer, s_outer.Length,
hash, hash.Length);
if (hr == 0)
return hash;
_UseHMACSHA = false;
return null;
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static string HashAndBase64EncodeString(string s)
{
byte[] ab;
byte[] hash;
string result;
ab = Encoding.Unicode.GetBytes(s);
hash = HashData(ab, null, 0, ab.Length);
result = Convert.ToBase64String(hash);
return result;
}
static internal void DestroyByteArray(byte[] buf)
{
if (buf == null || buf.Length < 1)
return;
for (int iter = 0; iter < buf.Length; iter++)
buf[iter] = (byte)0;
}
internal void DestroyKeys()
{
MachineKeySection.DestroyByteArray(_ValidationKey);
MachineKeySection.DestroyByteArray(_DecryptionKey);
}
static void EnsureConfig()
{
if (!s_initComplete)
{
lock (s_initLock)
{
if (!s_initComplete)
{
GetApplicationConfig(); // sets s_config field
s_config.ConfigureEncryptionObject();
s_initComplete = true;
}
}
}
}
// gets the application-level MachineKeySection
internal static MachineKeySection GetApplicationConfig() {
if (s_config == null) {
lock (s_initLock) {
if (s_config == null) {
s_config = RuntimeConfig.GetAppConfig().MachineKey;
}
}
}
return s_config;
}
// NOTE: When encoding the data, this method *may* return the same reference to the input "buf" parameter
// with the hash appended in the end if there's enough space. The "length" parameter would also be
// appropriately adjusted in those cases. This is an optimization to prevent unnecessary copying of
// buffers.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetEncodedData(byte[] buf, byte[] modifier, int start, ref int length)
{
EnsureConfig();
byte[] bHash = HashData(buf, modifier, start, length);
byte[] returnBuffer;
if (buf.Length - start - length >= bHash.Length)
{
// Append hash to end of buffer if there's space
Buffer.BlockCopy(bHash, 0, buf, start + length, bHash.Length);
returnBuffer = buf;
}
else
{
returnBuffer = new byte[length + bHash.Length];
Buffer.BlockCopy(buf, start, returnBuffer, 0, length);
Buffer.BlockCopy(bHash, 0, returnBuffer, length, bHash.Length);
start = 0;
}
length += bHash.Length;
if (s_config.Validation == MachineKeyValidation.TripleDES || s_config.Validation == MachineKeyValidation.AES) {
returnBuffer = EncryptOrDecryptData(true, returnBuffer, modifier, start, length, true);
length = returnBuffer.Length;
}
return returnBuffer;
}
// NOTE: When decoding the data, this method *may* return the same reference to the input "buf" parameter
// with the "dataLength" parameter containing the actual length of the data in the "buf" (i.e. length of actual
// data is (total length of data - hash length)). This is an optimization to prevent unnecessary copying of buffers.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetDecodedData(byte[] buf, byte[] modifier, int start, int length, ref int dataLength)
{
EnsureConfig();
if (s_config.Validation == MachineKeyValidation.TripleDES || s_config.Validation == MachineKeyValidation.AES) {
buf = EncryptOrDecryptData(false, buf, modifier, start, length, true);
if (buf == null || buf.Length < _HashSize)
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
length = buf.Length;
start = 0;
}
if (length < _HashSize || start < 0 || start >= length)
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
byte[] bHash = HashData(buf, modifier, start, length - _HashSize);
for (int iter = 0; iter < bHash.Length; iter++)
if (bHash[iter] != buf[start + length - _HashSize + iter])
throw new HttpException(SR.GetString(SR.Unable_to_validate_data));
dataLength = length - _HashSize;
return buf;
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] HashData(byte[] buf, byte[] modifier, int start, int length)
{
EnsureConfig();
if (s_config.Validation == MachineKeyValidation.MD5)
return HashDataUsingNonKeyedAlgorithm(null, buf, modifier, start, length, s_validationKey);
if (_UseHMACSHA) {
byte [] hash = GetHMACSHA1Hash(buf, modifier, start, length);
if (hash != null)
return hash;
}
if (_CustomValidationTypeIsKeyed) {
return HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm.Create(_CustomValidationName),
buf, modifier, start, length, s_validationKey);
} else {
return HashDataUsingNonKeyedAlgorithm(HashAlgorithm.Create(_CustomValidationName),
buf, modifier, start, length, s_validationKey);
}
}
private void ConfigureEncryptionObject()
{
// We suppress CS0618 since some of the algorithms we support are marked with [Obsolete].
// These deprecated algorithms are *not* enabled by default. Developers must opt-in to
// them, so we're secure by default.
#pragma warning disable 618
using (new ApplicationImpersonationContext()) {
s_validationKey = ValidationKeyInternal;
byte[] dKey = DecryptionKeyInternal;
if (_UseHMACSHA)
SetInnerOuterKeys(s_validationKey, ref s_inner, ref s_outer);
DestroyKeys();
switch (Decryption)
{
case "3DES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateTripleDES();
break;
case "DES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateDES();
break;
case "AES":
s_oSymAlgoDecryption = CryptoAlgorithms.CreateAes();
break;
case "Auto":
if (dKey.Length == 8) {
s_oSymAlgoDecryption = CryptoAlgorithms.CreateDES();
} else {
s_oSymAlgoDecryption = CryptoAlgorithms.CreateAes();
}
break;
}
if (s_oSymAlgoDecryption == null) // Shouldn't happen!
InitValidationAndEncyptionSizes();
switch(Validation)
{
case MachineKeyValidation.TripleDES:
if (dKey.Length == 8) {
s_oSymAlgoValidation = CryptoAlgorithms.CreateDES();
} else {
s_oSymAlgoValidation = CryptoAlgorithms.CreateTripleDES();
}
break;
case MachineKeyValidation.AES:
s_oSymAlgoValidation = CryptoAlgorithms.CreateAes();
break;
}
// The IV lengths should actually be equal to the block sizes rather than the key
// sizes, but we shipped with this code and unfortunately cannot change it without
// breaking back-compat.
if (s_oSymAlgoValidation != null) {
SetKeyOnSymAlgorithm(s_oSymAlgoValidation, dKey);
_IVLengthValidation = RoundupNumBitsToNumBytes(s_oSymAlgoValidation.KeySize);
}
SetKeyOnSymAlgorithm(s_oSymAlgoDecryption, dKey);
_IVLengthDecryption = RoundupNumBitsToNumBytes(s_oSymAlgoDecryption.KeySize);
InitLegacyEncAlgorithm(dKey);
DestroyByteArray(dKey);
}
#pragma warning restore 618
}
private void SetKeyOnSymAlgorithm(SymmetricAlgorithm symAlgo, byte[] dKey)
{
try {
if (dKey.Length > 8 && symAlgo is DESCryptoServiceProvider) {
byte[] bTemp = new byte[8];
Buffer.BlockCopy(dKey, 0, bTemp, 0, 8);
symAlgo.Key = bTemp;
DestroyByteArray(bTemp);
} else {
symAlgo.Key = dKey;
}
symAlgo.GenerateIV();
symAlgo.IV = new byte[symAlgo.IV.Length];
} catch (Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Bad_machine_key, e.Message), ElementInformation.Properties["decryptionKey"].Source, ElementInformation.Properties["decryptionKey"].LineNumber);
}
}
private static ICryptoTransform GetCryptoTransform(bool fEncrypt, bool useValidationSymAlgo, bool legacyMode)
{
SymmetricAlgorithm algo = (legacyMode ? s_oSymAlgoLegacy : (useValidationSymAlgo ? s_oSymAlgoValidation : s_oSymAlgoDecryption));
lock(algo)
return (fEncrypt ? algo.CreateEncryptor() : algo.CreateDecryptor());
}
private static void ReturnCryptoTransform(bool fEncrypt, ICryptoTransform ct, bool useValidationSymAlgo, bool legacyMode)
{
ct.Dispose();
}
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
static byte[] s_ahexval;
// This API is obsolete because it is insecure: invalid hex chars are silently replaced with '0',
// which can reduce the overall security of the system. But unfortunately, some code is dependent
// on this broken behavior.
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
static internal byte[] HexStringToByteArray(String str)
{
if (((uint)str.Length & 0x1) == 0x1) // must be 2 nibbles per byte
{
return null;
}
byte[] ahexval = s_ahexval; // initialize a table for faster lookups
if (ahexval == null)
{
ahexval = new byte['f' + 1];
for (int i = ahexval.Length; --i >= 0; )
{
if ('0' <= i && i <= '9')
{
ahexval[i] = (byte)(i - '0');
}
else if ('a' <= i && i <= 'f')
{
ahexval[i] = (byte)(i - 'a' + 10);
}
else if ('A' <= i && i <= 'F')
{
ahexval[i] = (byte)(i - 'A' + 10);
}
}
s_ahexval = ahexval;
}
byte[] result = new byte[str.Length / 2];
int istr = 0, ir = 0;
int n = result.Length;
while (--n >= 0)
{
int c1, c2;
try
{
c1 = ahexval[str[istr++]];
}
catch (ArgumentNullException)
{
c1 = 0;
return null;// Inavlid char
}
catch (ArgumentException)
{
c1 = 0;
return null;// Inavlid char
}
catch (IndexOutOfRangeException)
{
c1 = 0;
return null;// Inavlid char
}
try
{
c2 = ahexval[str[istr++]];
}
catch (ArgumentNullException)
{
c2 = 0;
return null;// Inavlid char
}
catch (ArgumentException)
{
c2 = 0;
return null;// Inavlid char
}
catch (IndexOutOfRangeException)
{
c2 = 0;
return null;// Inavlid char
}
result[ir++] = (byte)((c1 << 4) + c2);
}
return result;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private void InitValidationAndEncyptionSizes()
{
_CustomValidationName = ValidationAlgorithm;
_CustomValidationTypeIsKeyed = true;
switch(ValidationAlgorithm)
{
case "AES":
case "3DES":
_UseHMACSHA = true;
_HashSize = SHA1_HASH_SIZE;
_AutoGenValidationKeySize = SHA1_KEY_SIZE;
break;
case "SHA1":
_UseHMACSHA = true;
_HashSize = SHA1_HASH_SIZE;
_AutoGenValidationKeySize = SHA1_KEY_SIZE;
break;
case "MD5":
_CustomValidationTypeIsKeyed = false;
_UseHMACSHA = false;
_HashSize = MD5_HASH_SIZE;
_AutoGenValidationKeySize = MD5_KEY_SIZE;
break;
case "HMACSHA256":
_UseHMACSHA = true;
_HashSize = HMACSHA256_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA256_KEY_SIZE;
break;
case "HMACSHA384":
_UseHMACSHA = true;
_HashSize = HMACSHA384_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA384_KEY_SIZE;
break;
case "HMACSHA512":
_UseHMACSHA = true;
_HashSize = HMACSHA512_HASH_SIZE;
_AutoGenValidationKeySize = HMACSHA512_KEY_SIZE;
break;
default:
_UseHMACSHA = false;
if (!_CustomValidationName.StartsWith(ALGO_PREFIX, StringComparison.Ordinal)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum),
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
}
_CustomValidationName = _CustomValidationName.Substring(ALGO_PREFIX.Length);
HashAlgorithm alg = null;
try {
_CustomValidationTypeIsKeyed = false;
alg = HashAlgorithm.Create(_CustomValidationName);
} catch (Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum), e,
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
}
if (alg == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum),
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
_AutoGenValidationKeySize = 0;
_HashSize = 0;
_CustomValidationTypeIsKeyed = (alg is KeyedHashAlgorithm);
if (!_CustomValidationTypeIsKeyed) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_validation_enum),
ElementInformation.Properties["validation"].Source,
ElementInformation.Properties["validation"].LineNumber);
}
try {
_HashSize = RoundupNumBitsToNumBytes(alg.HashSize);
if (_CustomValidationTypeIsKeyed)
_AutoGenValidationKeySize = ((KeyedHashAlgorithm) alg).Key.Length;
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.InputBlockSize);
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.OutputBlockSize);
} catch {}
if (_HashSize < 1 || _AutoGenValidationKeySize < 1) {
// If we didn't get the hash-size or key-size, perform a hash and get the sizes
byte [] buf = new byte[10];
byte [] buf2 = new byte[512];
RandomNumberGenerator.GetBytes(buf);
RandomNumberGenerator.GetBytes(buf2);
byte [] bHash = alg.ComputeHash(buf);
_HashSize = bHash.Length;
if (_AutoGenValidationKeySize < 1) {
if (_CustomValidationTypeIsKeyed)
_AutoGenValidationKeySize = ((KeyedHashAlgorithm) alg).Key.Length;
else
_AutoGenValidationKeySize = RoundupNumBitsToNumBytes(alg.InputBlockSize);
}
alg.Clear();
}
if (_HashSize < 1)
_HashSize = HMACSHA512_HASH_SIZE;
if (_AutoGenValidationKeySize < 1)
_AutoGenValidationKeySize = HMACSHA512_KEY_SIZE;
break;
}
_AutoGenDecryptionKeySize = 0;
switch(Decryption) {
case "AES":
_AutoGenDecryptionKeySize = 24;
break;
case "3DES":
_AutoGenDecryptionKeySize = 24;
break;
case "Auto":
_AutoGenDecryptionKeySize = 24;
break;
case "DES":
if (ValidationAlgorithm == "AES" || ValidationAlgorithm == "3DES")
_AutoGenDecryptionKeySize = 24;
else
_AutoGenDecryptionKeySize = 8;
break;
default:
_UsingCustomEncryption = true;
if (!Decryption.StartsWith(ALGO_PREFIX, StringComparison.Ordinal)) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum),
ElementInformation.Properties["decryption"].Source,
ElementInformation.Properties["decryption"].LineNumber);
}
try {
s_oSymAlgoDecryption = SymmetricAlgorithm.Create(Decryption.Substring(ALGO_PREFIX.Length));
} catch(Exception e) {
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum), e,
ElementInformation.Properties["decryption"].Source,
ElementInformation.Properties["decryption"].LineNumber);
}
if (s_oSymAlgoDecryption == null)
throw new ConfigurationErrorsException(SR.GetString(SR.Wrong_decryption_enum),
ElementInformation.Properties["decryption"].Source,
ElementInformation.Properties["decryption"].LineNumber);
_AutoGenDecryptionKeySize = RoundupNumBitsToNumBytes(s_oSymAlgoDecryption.KeySize);
break;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal static int RoundupNumBitsToNumBytes(int numBits) {
if (numBits < 0)
return 0;
return (numBits / 8) + (((numBits & 7) != 0) ? 1 : 0);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static byte[] HashDataUsingNonKeyedAlgorithm(HashAlgorithm hashAlgo, byte[] buf, byte[] modifier,
int start, int length, byte[] validationKey)
{
int totalLength = length + validationKey.Length + ((modifier != null) ? modifier.Length : 0);
byte [] bAll = new byte[totalLength];
Buffer.BlockCopy(buf, start, bAll, 0, length);
if (modifier != null) {
Buffer.BlockCopy(modifier, 0, bAll, length, modifier.Length);
}
Buffer.BlockCopy(validationKey, 0, bAll, length, validationKey.Length);
if (hashAlgo != null) {
return hashAlgo.ComputeHash(bAll);
} else {
byte[] newHash = new byte[MD5_HASH_SIZE];
int hr = UnsafeNativeMethods.GetSHA1Hash(bAll, bAll.Length, newHash, newHash.Length);
Marshal.ThrowExceptionForHR(hr);
return newHash;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static byte[] HashDataUsingKeyedAlgorithm(KeyedHashAlgorithm hashAlgo, byte[] buf, byte[] modifier,
int start, int length, byte[] validationKey)
{
int totalLength = length + ((modifier != null) ? modifier.Length : 0);
byte [] bAll = new byte[totalLength];
Buffer.BlockCopy(buf, start, bAll, 0, length);
if (modifier != null) {
Buffer.BlockCopy(modifier, 0, bAll, length, modifier.Length);
}
hashAlgo.Key = validationKey;
return hashAlgo.ComputeHash(bAll);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static byte[] GetUnHashedData(byte[] bufHashed)
{
if (!VerifyHashedData(bufHashed))
return null;
byte[] buf2 = new byte[bufHashed.Length - _HashSize];
Buffer.BlockCopy(bufHashed, 0, buf2, 0, buf2.Length);
return buf2;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
[Obsolete(OBSOLETE_CRYPTO_API_MESSAGE)]
internal static bool VerifyHashedData(byte[] bufHashed)
{
EnsureConfig();
//////////////////////////////////////////////////////////////////////
// Step 1: Get the MAC: Last [HashSize] bytes
if (bufHashed.Length <= _HashSize)
return false;
byte[] bMac = HashData(bufHashed, null, 0, bufHashed.Length - _HashSize);
//////////////////////////////////////////////////////////////////////
// Step 2: Make sure the MAC has expected length
if (bMac == null || bMac.Length != _HashSize)
return false;
int lastPos = bufHashed.Length - _HashSize;
// From Tolga: To prevent a timing attack, we should verify the entire hash instead of failing
// early the first time we see a mismatched byte.
bool hashCheckFailed = false;
for (int iter = 0; iter < _HashSize; iter++)
if (bMac[iter] != bufHashed[lastPos + iter])
hashCheckFailed = true;
return !hashCheckFailed;
}
internal static bool UsingCustomEncryption {
get {
EnsureConfig();
return _UsingCustomEncryption;
}
}
private static void InitLegacyEncAlgorithm(byte [] dKey)
{
if (!_UsingCustomEncryption)
return;
s_oSymAlgoLegacy = CryptoAlgorithms.CreateAes();
try {
s_oSymAlgoLegacy.Key = dKey;
} catch {
if (dKey.Length <= 24)
throw;
byte [] buf = new byte[24];
Buffer.BlockCopy(dKey, 0, buf, 0, buf.Length);
dKey = buf;
s_oSymAlgoLegacy.Key = dKey;
}
}
// This is called as the last step of the deserialization process before the newly created section is seen by the consumer.
// We can use it to change defaults on-the-fly.
protected override void SetReadOnly() {
// Unless overridden, set <machineKey compatibilityMode="Framework45" />
ConfigUtil.SetFX45DefaultValue(this, _propCompatibilityMode, MachineKeyCompatibilityMode.Framework45);
base.SetReadOnly();
}
}
}
| |
// -------------------------------------
// Domain : IBT / Realtime.co
// Author : Nicholas Ventimiglia
// Product : Messaging and Storage
// Published : 2014
// -------------------------------------
using Windows.Web;
using UnityEngine;
#if UNITY_WSA
using Windows.Foundation;
using Windows.Storage.Streams;
using System.Threading;
using System;
using Windows.Networking.Sockets;
namespace Realtime.Messaging.Internal
{
public class WebSocketConnection : IDisposable
{
#region Delegates (4)
public delegate void OnOpenedDelegate();
public delegate void OnClosedDelegate();
public delegate void OnErrorDelegate(string error);
public delegate void OnMessageReceivedDelegate(string message);
#endregion
#region Events (4)
event OnOpenedDelegate _onOpened = delegate { };
public event OnOpenedDelegate OnOpened
{
add
{
_onOpened = (OnOpenedDelegate)Delegate.Combine(_onOpened, value);
}
remove
{
_onOpened = (OnOpenedDelegate)Delegate.Remove(_onOpened, value);
}
}
event OnClosedDelegate _onClosed = delegate { };
public event OnClosedDelegate OnClosed
{
add
{
_onClosed = (OnClosedDelegate)Delegate.Combine(_onClosed, value);
}
remove
{
_onClosed = (OnClosedDelegate)Delegate.Remove(_onClosed, value);
}
}
event OnErrorDelegate _onError = delegate { };
public event OnErrorDelegate OnError
{
add
{
_onError = (OnErrorDelegate)Delegate.Combine(_onError, value);
}
remove
{
_onError = (OnErrorDelegate)Delegate.Remove(_onError, value);
}
}
event OnMessageReceivedDelegate _onMessageReceived = delegate { };
public event OnMessageReceivedDelegate OnMessageReceived
{
add
{
_onMessageReceived = (OnMessageReceivedDelegate)Delegate.Combine(_onMessageReceived, value);
}
remove
{
_onMessageReceived = (OnMessageReceivedDelegate)Delegate.Remove(_onMessageReceived, value);
}
}
#endregion
#region Events Handles (4)
void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
{
var ev = _onMessageReceived;
if (ev == null)
return;
try
{
using (var reader = args.GetDataReader())
{
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
var read = reader.ReadString(reader.UnconsumedBufferLength);
ev(read);
}
}
catch
{
}
}
void Closed(IWebSocket sender, WebSocketClosedEventArgs args)
{
// You can add code to log or display the code and reason
// for the closure (stored in args.Code and args.Reason)
// This is invoked on another thread so use Interlocked
// to avoid races with the Start/Close/Reset methods.
var webSocket = Interlocked.Exchange(ref streamWebSocket, null);
if (webSocket != null)
{
webSocket.Dispose();
}
var ev = _onClosed;
if (ev != null)
{
ev();
}
streamWebSocket = null;
}
void RaiseError(string m)
{
var ev = _onError;
if (ev != null)
{
ev(m);
}
}
#endregion
#region Attributes (1)
private MessageWebSocket pending;
private MessageWebSocket streamWebSocket;
private DataWriter messageWriter;
#endregion
#region Methods - Public (3)
public async void Connect(string url)
{
if (pending != null)
{
pending.Dispose();
}
Uri uri;
var connectionId = Strings.RandomString(8);
var serverId = Strings.RandomNumber(1, 1000);
try
{
uri = new Uri(url);
}
catch (Exception)
{
throw new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Invalid URL: {0}", url));
}
try
{
var prefix = "https".Equals(uri.Scheme) ? "wss" : "ws";
var connectionUrl = new Uri(String.Format("{0}://{1}:{2}/broadcast/{3}/{4}/websocket", prefix, uri.DnsSafeHost, uri.Port, serverId, connectionId));
pending = new MessageWebSocket();
pending.Control.MessageType = SocketMessageType.Utf8;
pending.Closed += Closed;
pending.MessageReceived += MessageReceived;
try
{
await pending.ConnectAsync(connectionUrl);
}
catch(Exception ex)
{
WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
switch (status)
{
case WebErrorStatus.CannotConnect:
throw new Exception("Can't connect" + ex.Message);
case WebErrorStatus.NotFound:
throw new Exception("Not found" + ex.Message);
case WebErrorStatus.RequestTimeout:
throw new Exception("Request timeout" + ex.Message);
default:
throw new Exception("unknown" + ex.Message);
}
}
streamWebSocket = pending;
messageWriter = new DataWriter(pending.OutputStream);
var ev = _onOpened;
if (ev != null)
{
ev();
}
}
catch
{
throw new OrtcException(OrtcExceptionReason.InvalidArguments, String.Format("Invalid URL: {0}", url));
}
}
public void Close()
{
if (pending != null)
{
pending.Dispose();
pending = null;
}
if (streamWebSocket != null)
{
streamWebSocket.Close(1000, "Normal closure");
streamWebSocket.Dispose();
streamWebSocket = null;
}
}
public async void Send(string message)
{
if (streamWebSocket != null)
{
if (messageWriter != null)
{
try
{
message = "\"" + message + "\"";
messageWriter.WriteString(message);
await ((IAsyncOperation<uint>)messageWriter.StoreAsync());
}
catch (Exception ex)
{
RaiseError("Send failed");
Close();
}
}
}
}
#endregion
public void Dispose()
{
Close();
}
}
}
#endif
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using GitHub.App;
using GitHub.Authentication;
using GitHub.Extensions;
using GitHub.Extensions.Reactive;
using GitHub.Info;
using GitHub.Logging;
using GitHub.Models;
using GitHub.Primitives;
using GitHub.Services;
using GitHub.Validation;
using ReactiveUI;
using Serilog;
using IRecoveryCommand = ReactiveUI.Legacy.IRecoveryCommand;
using RecoveryCommand = ReactiveUI.Legacy.RecoveryCommand;
using RecoveryOptionResult = ReactiveUI.Legacy.RecoveryOptionResult;
using UserError = ReactiveUI.Legacy.UserError;
#pragma warning disable CS0618 // Type or member is obsolete
namespace GitHub.ViewModels.Dialog
{
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public abstract class LoginTabViewModel : ReactiveObject
{
static readonly ILogger log = LogManager.ForContext<LoginTabViewModel>();
CancellationTokenSource oauthCancel;
protected LoginTabViewModel(
IConnectionManager connectionManager,
IVisualStudioBrowser browser)
{
Guard.ArgumentNotNull(connectionManager, nameof(connectionManager));
Guard.ArgumentNotNull(browser, nameof(browser));
ConnectionManager = connectionManager;
UsernameOrEmailValidator = ReactivePropertyValidator.For(this, x => x.UsernameOrEmail)
.IfNullOrEmpty(Resources.UsernameOrEmailValidatorEmpty)
.IfMatch(@"\s", Resources.UsernameOrEmailValidatorSpaces);
PasswordValidator = ReactivePropertyValidator.For(this, x => x.Password)
.IfNullOrEmpty(Resources.PasswordValidatorEmpty);
canLogin = this.WhenAny(
x => x.UsernameOrEmailValidator.ValidationResult.IsValid,
x => x.PasswordValidator.ValidationResult.IsValid,
(x, y) => x.Value && y.Value).ToProperty(this, x => x.CanLogin);
Login = ReactiveCommand.CreateFromTask(LogIn, this.WhenAny(x => x.CanLogin, x => x.Value));
Login.ThrownExceptions.Subscribe(HandleError);
isLoggingIn = Login.IsExecuting.ToProperty(this, x => x.IsLoggingIn);
LoginViaOAuth = ReactiveCommand.CreateFromTask(
LogInViaOAuth,
this.WhenAnyValue(x => x.IsLoggingIn, x => !x));
LoginViaOAuth.ThrownExceptions.Subscribe(HandleError);
Reset = ReactiveCommand.CreateFromTask(Clear);
NavigateForgotPassword = new RecoveryCommand(Resources.ForgotPasswordLink, _ =>
{
browser.OpenUrl(new Uri(BaseUri, GitHubUrls.ForgotPasswordPath));
return RecoveryOptionResult.RetryOperation;
});
SignUp = ReactiveCommand.CreateFromObservable(() =>
{
browser.OpenUrl(GitHubUrls.Plans);
return Observable.Return(Unit.Default);
});
}
protected IConnectionManager ConnectionManager { get; }
protected abstract Uri BaseUri { get; }
public ReactiveCommand<Unit, Unit> SignUp { get; }
public ReactiveCommand<Unit, IConnection> Login { get; }
public ReactiveCommand<Unit, IConnection> LoginViaOAuth { get; }
public ReactiveCommand<Unit, Unit> Reset { get; }
#pragma warning disable CS0618 // Type or member is obsolete
public IRecoveryCommand NavigateForgotPassword { get; }
#pragma warning restore CS0618 // Type or member is obsolete
string usernameOrEmail;
public string UsernameOrEmail
{
get { return usernameOrEmail; }
set { this.RaiseAndSetIfChanged(ref usernameOrEmail, value); }
}
ReactivePropertyValidator usernameOrEmailValidator;
public ReactivePropertyValidator UsernameOrEmailValidator
{
get { return usernameOrEmailValidator; }
private set { this.RaiseAndSetIfChanged(ref usernameOrEmailValidator, value); }
}
string password;
public string Password
{
get { return password; }
set { this.RaiseAndSetIfChanged(ref password, value); }
}
ReactivePropertyValidator passwordValidator;
public ReactivePropertyValidator PasswordValidator
{
get { return passwordValidator; }
private set { this.RaiseAndSetIfChanged(ref passwordValidator, value); }
}
readonly ObservableAsPropertyHelper<bool> isLoggingIn;
public bool IsLoggingIn
{
get { return isLoggingIn.Value; }
}
protected ObservableAsPropertyHelper<bool> canLogin;
public bool CanLogin
{
get { return canLogin.Value; }
}
protected ObservableAsPropertyHelper<bool> canSsoLogin;
public bool CanSsoLogin
{
get { return canSsoLogin.Value; }
}
#pragma warning disable CS0618 // Type or member is obsolete
UserError error;
public UserError Error
{
get { return error; }
set { this.RaiseAndSetIfChanged(ref error, value); }
}
#pragma warning restore CS0618 // Type or member is obsolete
public void Deactivated() => oauthCancel?.Cancel();
protected abstract Task<IConnection> LogIn();
protected abstract Task<IConnection> LogInViaOAuth();
protected async Task<IConnection> LogInToHost(HostAddress hostAddress)
{
Guard.ArgumentNotNull(hostAddress, nameof(hostAddress));
if (await ConnectionManager.GetConnection(hostAddress) != null)
{
await ConnectionManager.LogOut(hostAddress);
}
return await ConnectionManager.LogIn(hostAddress, UsernameOrEmail, Password);
}
protected async Task<IConnection> LoginToHostViaOAuth(HostAddress address)
{
oauthCancel = new CancellationTokenSource();
if (await ConnectionManager.GetConnection(address) != null)
{
await ConnectionManager.LogOut(address);
}
try
{
return await ConnectionManager.LogInViaOAuth(address, oauthCancel.Token);
}
finally
{
oauthCancel.Dispose();
oauthCancel = null;
}
}
async Task Clear()
{
UsernameOrEmail = null;
Password = null;
await UsernameOrEmailValidator.ResetAsync();
await PasswordValidator.ResetAsync();
await ResetValidation();
}
protected virtual Task ResetValidation()
{
// noop
return Task.FromResult(0);
}
#pragma warning disable CS0618 // Type or member is obsolete
void HandleError(Exception ex)
{
// The Windows ERROR_OPERATION_ABORTED error code.
const int operationAborted = 995;
if (ex is HttpListenerException &&
((HttpListenerException)ex).ErrorCode == operationAborted)
{
// An Oauth listener was aborted, probably because the user closed the login
// dialog or switched between the GitHub and Enterprise tabs while listening
// for an Oauth callbacl.
return;
}
if (ex.IsCriticalException()) return;
log.Error(ex, "Error logging into '{BaseUri}' as '{UsernameOrEmail}'", BaseUri, UsernameOrEmail);
if (ex is Octokit.ForbiddenException)
{
Error = new UserError(Resources.LoginFailedForbiddenMessage, ex.Message);
}
else
{
Error = new UserError(ex.Message);
}
}
#pragma warning restore CS0618 // Type or member is obsolete
}
}
| |
using System;
using EncompassRest.Loans.Enums;
namespace EncompassRest.Loans
{
/// <summary>
/// EmDocumentLender
/// </summary>
public sealed partial class EmDocumentLender : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _id;
private DirtyValue<string?>? _lndBrchCty;
private DirtyValue<string?>? _lndBrchFax;
private DirtyValue<string?>? _lndBrchJrsdctn;
private DirtyValue<string?>? _lndBrchNm;
private DirtyValue<StringEnumValue<OrgTyp>>? _lndBrchOrgTyp;
private DirtyValue<string?>? _lndBrchPhone;
private DirtyValue<string?>? _lndBrchStCd;
private DirtyValue<string?>? _lndBrchStreetAddr1;
private DirtyValue<string?>? _lndBrchStreetAddr2;
private DirtyValue<string?>? _lndBrchTollFreePhone;
private DirtyValue<string?>? _lndBrchUrl;
private DirtyValue<string?>? _lndBrchZip;
private DirtyValue<string?>? _lndCnty;
private DirtyValue<string?>? _lndCty;
private DirtyValue<string?>? _lndFaxNum;
private DirtyValue<string?>? _lndFhaOrgntrId;
private DirtyValue<string?>? _lndFhaSpnsrId;
private DirtyValue<string?>? _lndJrsdctn;
private DirtyValue<string?>? _lndLossPayeeAdtlTxt;
private DirtyValue<string?>? _lndLossPayeeCntctEmail;
private DirtyValue<string?>? _lndLossPayeeCntctFax;
private DirtyValue<string?>? _lndLossPayeeCntctNm;
private DirtyValue<string?>? _lndLossPayeeCntctPhone;
private DirtyValue<string?>? _lndLossPayeeCty;
private DirtyValue<string?>? _lndLossPayeeJrsdctn;
private DirtyValue<string?>? _lndLossPayeeNm;
private DirtyValue<StringEnumValue<OrgTyp>>? _lndLossPayeeOrgTyp;
private DirtyValue<StringEnumValue<ScsrsClaus>>? _lndLossPayeeScsrsClausTxtDesc;
private DirtyValue<string?>? _lndLossPayeeStCd;
private DirtyValue<string?>? _lndLossPayeeStreetAddr1;
private DirtyValue<string?>? _lndLossPayeeStreetAddr2;
private DirtyValue<string?>? _lndLossPayeeZip;
private DirtyValue<string?>? _lndMersIdNum;
private DirtyValue<string?>? _lndNm;
private DirtyValue<string?>? _lndNmlsIdNum;
private DirtyValue<string?>? _lndNtryCmsnBndNumIdntfr;
private DirtyValue<string?>? _lndNtryCmsnCnty;
private DirtyValue<DateTime?>? _lndNtryCmsnExprDt;
private DirtyValue<string?>? _lndNtryCmsnNumIdntfr;
private DirtyValue<string?>? _lndNtryCmsnSt;
private DirtyValue<string?>? _lndNtryCty;
private DirtyValue<string?>? _lndNtryNm;
private DirtyValue<string?>? _lndNtryStCd;
private DirtyValue<string?>? _lndNtryStreetAddr1;
private DirtyValue<string?>? _lndNtryStreetAddr2;
private DirtyValue<string?>? _lndNtryTtlOrRank;
private DirtyValue<string?>? _lndNtryZip;
private DirtyValue<StringEnumValue<OrgTyp>>? _lndOrgTyp;
private DirtyValue<string?>? _lndPhoneNum;
private DirtyValue<string?>? _lndStCd;
private DirtyValue<string?>? _lndStreetAddr1;
private DirtyValue<string?>? _lndStreetAddr2;
private DirtyValue<string?>? _lndSvcrAdtlTxt;
private DirtyValue<string?>? _lndSvcrCntctNm;
private DirtyValue<string?>? _lndSvcrCntctPhoneNum;
private DirtyValue<string?>? _lndSvcrCntctTollFreePhoneNum;
private DirtyValue<string?>? _lndSvcrCty;
private DirtyValue<string?>? _lndSvcrDayOp;
private DirtyValue<string?>? _lndSvcrDayOpAddl;
private DirtyValue<string?>? _lndSvcrHrsOp;
private DirtyValue<string?>? _lndSvcrHrsOpAddl;
private DirtyValue<string?>? _lndSvcrJrsdctn;
private DirtyValue<string?>? _lndSvcrNm;
private DirtyValue<StringEnumValue<OrgTyp>>? _lndSvcrOrgTyp;
private DirtyValue<string?>? _lndSvcrStCd;
private DirtyValue<string?>? _lndSvcrStreetAddr1;
private DirtyValue<string?>? _lndSvcrStreetAddr2;
private DirtyValue<string?>? _lndSvcrZip;
private DirtyValue<string?>? _lndTaxIDNum;
private DirtyValue<string?>? _lndTollFreePhoneNum;
private DirtyValue<string?>? _lndUrl;
private DirtyValue<string?>? _lndVaIdNum;
private DirtyValue<string?>? _lndZip;
/// <summary>
/// EmDocumentLender Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch City [Closing.LndBrchCty]
/// </summary>
public string? LndBrchCty { get => _lndBrchCty; set => SetField(ref _lndBrchCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch FAX Number [Closing.LndBrchFax]
/// </summary>
public string? LndBrchFax { get => _lndBrchFax; set => SetField(ref _lndBrchFax, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Jurisdiction [Closing.LndBrchJrsdctn]
/// </summary>
public string? LndBrchJrsdctn { get => _lndBrchJrsdctn; set => SetField(ref _lndBrchJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Name [Closing.LndBrchNm]
/// </summary>
public string? LndBrchNm { get => _lndBrchNm; set => SetField(ref _lndBrchNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Organization Type [Closing.LndBrchOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> LndBrchOrgTyp { get => _lndBrchOrgTyp; set => SetField(ref _lndBrchOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Telephone Number [Closing.LndBrchPhone]
/// </summary>
public string? LndBrchPhone { get => _lndBrchPhone; set => SetField(ref _lndBrchPhone, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch State Code [Closing.LndBrchStCd]
/// </summary>
public string? LndBrchStCd { get => _lndBrchStCd; set => SetField(ref _lndBrchStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Street Address [Closing.LndBrchStreetAddr1]
/// </summary>
public string? LndBrchStreetAddr1 { get => _lndBrchStreetAddr1; set => SetField(ref _lndBrchStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Street Address 2 [Closing.LndBrchStreetAddr2]
/// </summary>
public string? LndBrchStreetAddr2 { get => _lndBrchStreetAddr2; set => SetField(ref _lndBrchStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Toll-Free Telephone Number [Closing.LndBrchTollFreePhone]
/// </summary>
public string? LndBrchTollFreePhone { get => _lndBrchTollFreePhone; set => SetField(ref _lndBrchTollFreePhone, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch URL [Closing.LndBrchUrl]
/// </summary>
public string? LndBrchUrl { get => _lndBrchUrl; set => SetField(ref _lndBrchUrl, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Branch Postal Code [Closing.LndBrchZip]
/// </summary>
public string? LndBrchZip { get => _lndBrchZip; set => SetField(ref _lndBrchZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender County [Closing.LndCnty]
/// </summary>
public string? LndCnty { get => _lndCnty; set => SetField(ref _lndCnty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender City [Closing.LndCty]
/// </summary>
public string? LndCty { get => _lndCty; set => SetField(ref _lndCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender FAX Number [Closing.LndFaxNum]
/// </summary>
public string? LndFaxNum { get => _lndFaxNum; set => SetField(ref _lndFaxNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender FHA Originator Identifier [Closing.LndFhaOrgntrId]
/// </summary>
public string? LndFhaOrgntrId { get => _lndFhaOrgntrId; set => SetField(ref _lndFhaOrgntrId, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender FHA Sponsor Identifier [Closing.LndFhaSpnsrId]
/// </summary>
public string? LndFhaSpnsrId { get => _lndFhaSpnsrId; set => SetField(ref _lndFhaSpnsrId, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Jurisdiction [Closing.LndJrsdctn]
/// </summary>
public string? LndJrsdctn { get => _lndJrsdctn; set => SetField(ref _lndJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Additional Text [Closing.LndLossPayeeAdtlTxt]
/// </summary>
public string? LndLossPayeeAdtlTxt { get => _lndLossPayeeAdtlTxt; set => SetField(ref _lndLossPayeeAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Contact Email Address [Closing.LndLossPayeeCntctEmail]
/// </summary>
public string? LndLossPayeeCntctEmail { get => _lndLossPayeeCntctEmail; set => SetField(ref _lndLossPayeeCntctEmail, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Contact Fax Number [Closing.LndLossPayeeCntctFax]
/// </summary>
public string? LndLossPayeeCntctFax { get => _lndLossPayeeCntctFax; set => SetField(ref _lndLossPayeeCntctFax, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Contact Name [Closing.LndLossPayeeCntctNm]
/// </summary>
public string? LndLossPayeeCntctNm { get => _lndLossPayeeCntctNm; set => SetField(ref _lndLossPayeeCntctNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Contact Telephone Number [Closing.LndLossPayeeCntctPhone]
/// </summary>
public string? LndLossPayeeCntctPhone { get => _lndLossPayeeCntctPhone; set => SetField(ref _lndLossPayeeCntctPhone, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee City [Closing.LndLossPayeeCty]
/// </summary>
public string? LndLossPayeeCty { get => _lndLossPayeeCty; set => SetField(ref _lndLossPayeeCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Jurisdiction [Closing.LndLossPayeeJrsdctn]
/// </summary>
public string? LndLossPayeeJrsdctn { get => _lndLossPayeeJrsdctn; set => SetField(ref _lndLossPayeeJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Name [Closing.LndLossPayeeNm]
/// </summary>
public string? LndLossPayeeNm { get => _lndLossPayeeNm; set => SetField(ref _lndLossPayeeNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Organization Type [Closing.LndLossPayeeOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> LndLossPayeeOrgTyp { get => _lndLossPayeeOrgTyp; set => SetField(ref _lndLossPayeeOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Successor Clause [Closing.LndLossPayeeScsrsClausTxtDesc]
/// </summary>
public StringEnumValue<ScsrsClaus> LndLossPayeeScsrsClausTxtDesc { get => _lndLossPayeeScsrsClausTxtDesc; set => SetField(ref _lndLossPayeeScsrsClausTxtDesc, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee State Code [Closing.LndLossPayeeStCd]
/// </summary>
public string? LndLossPayeeStCd { get => _lndLossPayeeStCd; set => SetField(ref _lndLossPayeeStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Street Address [Closing.LndLossPayeeStreetAddr1]
/// </summary>
public string? LndLossPayeeStreetAddr1 { get => _lndLossPayeeStreetAddr1; set => SetField(ref _lndLossPayeeStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Street Address 2 [Closing.LndLossPayeeStreetAddr2]
/// </summary>
public string? LndLossPayeeStreetAddr2 { get => _lndLossPayeeStreetAddr2; set => SetField(ref _lndLossPayeeStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Loss Payee Postal Code [Closing.LndLossPayeeZip]
/// </summary>
public string? LndLossPayeeZip { get => _lndLossPayeeZip; set => SetField(ref _lndLossPayeeZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender MERS ID No. [Closing.LndMersIdNum]
/// </summary>
public string? LndMersIdNum { get => _lndMersIdNum; set => SetField(ref _lndMersIdNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Name [Closing.LndNm]
/// </summary>
public string? LndNm { get => _lndNm; set => SetField(ref _lndNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender NMLS ID No. [Closing.LndNmlsIdNum]
/// </summary>
public string? LndNmlsIdNum { get => _lndNmlsIdNum; set => SetField(ref _lndNmlsIdNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Commission Bond Number Identifier [Closing.LndNtryCmsnBndNumIdntfr]
/// </summary>
public string? LndNtryCmsnBndNumIdntfr { get => _lndNtryCmsnBndNumIdntfr; set => SetField(ref _lndNtryCmsnBndNumIdntfr, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Commission County/Jurisdiction [Closing.LndNtryCmsnCnty]
/// </summary>
public string? LndNtryCmsnCnty { get => _lndNtryCmsnCnty; set => SetField(ref _lndNtryCmsnCnty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Commission Expiration Date [Closing.LndNtryCmsnExprDt]
/// </summary>
public DateTime? LndNtryCmsnExprDt { get => _lndNtryCmsnExprDt; set => SetField(ref _lndNtryCmsnExprDt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Commission Number Identifier [Closing.LndNtryCmsnNumIdntfr]
/// </summary>
public string? LndNtryCmsnNumIdntfr { get => _lndNtryCmsnNumIdntfr; set => SetField(ref _lndNtryCmsnNumIdntfr, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Commission State [Closing.LndNtryCmsnSt]
/// </summary>
public string? LndNtryCmsnSt { get => _lndNtryCmsnSt; set => SetField(ref _lndNtryCmsnSt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary City [Closing.LndNtryCty]
/// </summary>
public string? LndNtryCty { get => _lndNtryCty; set => SetField(ref _lndNtryCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Name [Closing.LndNtryNm]
/// </summary>
public string? LndNtryNm { get => _lndNtryNm; set => SetField(ref _lndNtryNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary State Code [Closing.LndNtryStCd]
/// </summary>
public string? LndNtryStCd { get => _lndNtryStCd; set => SetField(ref _lndNtryStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Street Address [Closing.LndNtryStreetAddr1]
/// </summary>
public string? LndNtryStreetAddr1 { get => _lndNtryStreetAddr1; set => SetField(ref _lndNtryStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Street Address 2 [Closing.LndNtryStreetAddr2]
/// </summary>
public string? LndNtryStreetAddr2 { get => _lndNtryStreetAddr2; set => SetField(ref _lndNtryStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Title Or Rank [Closing.LndNtryTtlOrRank]
/// </summary>
public string? LndNtryTtlOrRank { get => _lndNtryTtlOrRank; set => SetField(ref _lndNtryTtlOrRank, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Notary Postal Code [Closing.LndNtryZip]
/// </summary>
public string? LndNtryZip { get => _lndNtryZip; set => SetField(ref _lndNtryZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Organization Type [Closing.LndOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> LndOrgTyp { get => _lndOrgTyp; set => SetField(ref _lndOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Telephone Number [Closing.LndPhoneNum]
/// </summary>
public string? LndPhoneNum { get => _lndPhoneNum; set => SetField(ref _lndPhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender State Code [Closing.LndStCd]
/// </summary>
public string? LndStCd { get => _lndStCd; set => SetField(ref _lndStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Street Address [Closing.LndStreetAddr1]
/// </summary>
public string? LndStreetAddr1 { get => _lndStreetAddr1; set => SetField(ref _lndStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Street Address 2 [Closing.LndStreetAddr2]
/// </summary>
public string? LndStreetAddr2 { get => _lndStreetAddr2; set => SetField(ref _lndStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Miscellaneous Text Description [Closing.LndSvcrAdtlTxt]
/// </summary>
public string? LndSvcrAdtlTxt { get => _lndSvcrAdtlTxt; set => SetField(ref _lndSvcrAdtlTxt, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Contact Name [Closing.LndSvcrCntctNm]
/// </summary>
public string? LndSvcrCntctNm { get => _lndSvcrCntctNm; set => SetField(ref _lndSvcrCntctNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Contact Telephone Number [Closing.LndSvcrCntctPhoneNum]
/// </summary>
public string? LndSvcrCntctPhoneNum { get => _lndSvcrCntctPhoneNum; set => SetField(ref _lndSvcrCntctPhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Contact Toll-Free Telephone Number [Closing.LndSvcrCntctTollFreePhoneNum]
/// </summary>
public string? LndSvcrCntctTollFreePhoneNum { get => _lndSvcrCntctTollFreePhoneNum; set => SetField(ref _lndSvcrCntctTollFreePhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer City [Closing.LndSvcrCty]
/// </summary>
public string? LndSvcrCty { get => _lndSvcrCty; set => SetField(ref _lndSvcrCty, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Days of Operation [Closing.LndSvcrDayOp]
/// </summary>
public string? LndSvcrDayOp { get => _lndSvcrDayOp; set => SetField(ref _lndSvcrDayOp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Days of Operation (Additional) [Closing.LndSvcrDayOpAddl]
/// </summary>
public string? LndSvcrDayOpAddl { get => _lndSvcrDayOpAddl; set => SetField(ref _lndSvcrDayOpAddl, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Hours of Operation [Closing.LndSvcrHrsOp]
/// </summary>
public string? LndSvcrHrsOp { get => _lndSvcrHrsOp; set => SetField(ref _lndSvcrHrsOp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Hours of Operation (Additional) [Closing.LndSvcrHrsOpAddl]
/// </summary>
public string? LndSvcrHrsOpAddl { get => _lndSvcrHrsOpAddl; set => SetField(ref _lndSvcrHrsOpAddl, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Organized Under the Laws Of Jurisdiction Name [Closing.LndSvcrJrsdctn]
/// </summary>
public string? LndSvcrJrsdctn { get => _lndSvcrJrsdctn; set => SetField(ref _lndSvcrJrsdctn, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Name [Closing.LndSvcrNm]
/// </summary>
public string? LndSvcrNm { get => _lndSvcrNm; set => SetField(ref _lndSvcrNm, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Organization Type [Closing.LndSvcrOrgTyp]
/// </summary>
public StringEnumValue<OrgTyp> LndSvcrOrgTyp { get => _lndSvcrOrgTyp; set => SetField(ref _lndSvcrOrgTyp, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer State Code [Closing.LndSvcrStCd]
/// </summary>
public string? LndSvcrStCd { get => _lndSvcrStCd; set => SetField(ref _lndSvcrStCd, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Street Address [Closing.LndSvcrStreetAddr1]
/// </summary>
public string? LndSvcrStreetAddr1 { get => _lndSvcrStreetAddr1; set => SetField(ref _lndSvcrStreetAddr1, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Street Address 2 [Closing.LndSvcrStreetAddr2]
/// </summary>
public string? LndSvcrStreetAddr2 { get => _lndSvcrStreetAddr2; set => SetField(ref _lndSvcrStreetAddr2, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Servicer Postal Code [Closing.LndSvcrZip]
/// </summary>
public string? LndSvcrZip { get => _lndSvcrZip; set => SetField(ref _lndSvcrZip, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Tax ID No. [Closing.LndTaxIDNum]
/// </summary>
public string? LndTaxIDNum { get => _lndTaxIDNum; set => SetField(ref _lndTaxIDNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Toll-Free Telephone Number [Closing.LndTollFreePhoneNum]
/// </summary>
public string? LndTollFreePhoneNum { get => _lndTollFreePhoneNum; set => SetField(ref _lndTollFreePhoneNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender URL [Closing.LndUrl]
/// </summary>
public string? LndUrl { get => _lndUrl; set => SetField(ref _lndUrl, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender VA ID No. [Closing.LndVaIdNum]
/// </summary>
public string? LndVaIdNum { get => _lndVaIdNum; set => SetField(ref _lndVaIdNum, value); }
/// <summary>
/// Ellie Mae Closing Document Override - Lender Postal Code [Closing.LndZip]
/// </summary>
public string? LndZip { get => _lndZip; set => SetField(ref _lndZip, value); }
}
}
| |
// 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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.AddImport;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddUsingOrImport), Shared]
internal class CSharpAddImportCodeFixProvider : AbstractAddImportCodeFixProvider
{
/// <summary>
/// name does not exist in context
/// </summary>
private const string CS0103 = "CS0103";
/// <summary>
/// type or namespace could not be found
/// </summary>
private const string CS0246 = "CS0246";
/// <summary>
/// wrong number of type args
/// </summary>
private const string CS0305 = "CS0305";
/// <summary>
/// type does not contain a definition of method or extension method
/// </summary>
private const string CS1061 = "CS1061";
/// <summary>
/// cannot find implementation of query pattern
/// </summary>
private const string CS1935 = "CS1935";
/// <summary>
/// The non-generic type 'A' cannot be used with type arguments
/// </summary>
private const string CS0308 = "CS0308";
/// <summary>
/// 'A' is inaccessible due to its protection level
/// </summary>
private const string CS0122 = "CS0122";
/// <summary>
/// The using alias 'A' cannot be used with type arguments
/// </summary>
private const string CS0307 = "CS0307";
/// <summary>
/// 'A' is not an attribute class
/// </summary>
private const string CS0616 = "CS0616";
/// <summary>
/// ; expected.
/// </summary>
private const string CS1002 = "CS1002";
/// <summary>
/// Syntax error, 'A' expected
/// </summary>
private const string CS1003 = "CS1003";
/// <summary>
/// cannot convert from 'int' to 'string'
/// </summary>
private const string CS1503 = "CS1503";
/// <summary>
/// XML comment on 'construct' has syntactically incorrect cref attribute 'name'
/// </summary>
private const string CS1574 = "CS1574";
/// <summary>
/// Invalid type for parameter 'parameter number' in XML comment cref attribute
/// </summary>
private const string CS1580 = "CS1580";
/// <summary>
/// Invalid return type in XML comment cref attribute
/// </summary>
private const string CS1581 = "CS1581";
/// <summary>
/// XML comment has syntactically incorrect cref attribute
/// </summary>
private const string CS1584 = "CS1584";
public override ImmutableArray<string> FixableDiagnosticIds
{
get
{
return ImmutableArray.Create(
CS0103,
CS0246,
CS0305,
CS1061,
CS1935,
CS0308,
CS0122,
CS0307,
CS0616,
CS1002,
CS1003,
CS1503,
CS1574,
CS1580,
CS1581,
CS1584);
}
}
protected override bool IgnoreCase
{
get { return false; }
}
protected override bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return false;
}
return node.CanAddUsingDirectives(cancellationToken);
}
protected override bool CanAddImportForMethod(Diagnostic diagnostic, ISyntaxFactsService syntaxFacts, ref SyntaxNode node)
{
switch (diagnostic.Id)
{
case CS1061:
if (node.IsKind(SyntaxKind.ConditionalAccessExpression))
{
node = (node as ConditionalAccessExpressionSyntax).WhenNotNull;
}
else if (node.IsKind(SyntaxKind.MemberBindingExpression))
{
node = (node as MemberBindingExpressionSyntax).Name;
}
else if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
{
return true;
}
break;
case CS0122:
break;
case CS1503:
//// look up its corresponding method name
var parent = node.GetAncestor<InvocationExpressionSyntax>();
if (parent == null)
{
return false;
}
var method = parent.Expression as MemberAccessExpressionSyntax;
if (method != null)
{
node = method.Name;
}
break;
default:
return false;
}
var simpleName = node as SimpleNameSyntax;
if (!simpleName.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) &&
!simpleName.IsParentKind(SyntaxKind.MemberBindingExpression))
{
return false;
}
var memberAccess = simpleName.Parent as MemberAccessExpressionSyntax;
var memberBinding = simpleName.Parent as MemberBindingExpressionSyntax;
if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
memberAccess.IsParentKind(SyntaxKind.ElementAccessExpression) ||
memberBinding.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
memberBinding.IsParentKind(SyntaxKind.ElementAccessExpression))
{
return false;
}
if (!syntaxFacts.IsMemberAccessExpressionName(node))
{
return false;
}
return true;
}
protected override bool CanAddImportForNamespace(Diagnostic diagnostic, ref SyntaxNode node)
{
return false;
}
protected override bool CanAddImportForQuery(Diagnostic diagnostic, ref SyntaxNode node)
{
if (diagnostic.Id != CS1935)
{
return false;
}
return node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax));
}
protected override bool CanAddImportForType(Diagnostic diagnostic, ref SyntaxNode node)
{
switch (diagnostic.Id)
{
case CS0103:
case CS0246:
case CS0305:
case CS0308:
case CS0122:
case CS0307:
case CS0616:
case CS1003:
case CS1580:
case CS1581:
break;
case CS1002:
//// only lookup errors inside ParenthesizedLambdaExpression e.g., () => { ... }
if (node.Ancestors().OfType<ParenthesizedLambdaExpressionSyntax>().Any())
{
if (node is SimpleNameSyntax)
{
break;
}
else if (node is BlockSyntax || node is MemberAccessExpressionSyntax || node is BinaryExpressionSyntax)
{
var last = node.DescendantNodes().OfType<SimpleNameSyntax>().LastOrDefault();
if (!TryFindStandaloneType(ref node))
{
node = node.DescendantNodes().OfType<SimpleNameSyntax>().FirstOrDefault();
}
else
{
node = last;
}
}
}
else
{
return false;
}
break;
case CS1574:
case CS1584:
var cref = node as QualifiedCrefSyntax;
if (cref != null)
{
node = cref.Container;
}
break;
default:
return false;
}
return TryFindStandaloneType(ref node);
}
private static bool TryFindStandaloneType(ref SyntaxNode node)
{
var qn = node as QualifiedNameSyntax;
if (qn != null)
{
node = GetLeftMostSimpleName(qn);
}
var simpleName = node as SimpleNameSyntax;
return simpleName.LooksLikeStandaloneTypeName();
}
private static SimpleNameSyntax GetLeftMostSimpleName(QualifiedNameSyntax qn)
{
while (qn != null)
{
var left = qn.Left;
var simpleName = left as SimpleNameSyntax;
if (simpleName != null)
{
return simpleName;
}
qn = left as QualifiedNameSyntax;
}
return null;
}
protected override ISet<INamespaceSymbol> GetNamespacesInScope(
SemanticModel semanticModel,
SyntaxNode node,
CancellationToken cancellationToken)
{
return semanticModel.GetUsingNamespacesInScope(node);
}
protected override ITypeSymbol GetQueryClauseInfo(
SemanticModel semanticModel,
SyntaxNode node,
CancellationToken cancellationToken)
{
var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First();
if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken)))
{
return null;
}
foreach (var clause in query.Body.Clauses)
{
if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken)))
{
return null;
}
}
if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken)))
{
return null;
}
var fromClause = query.FromClause;
return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type;
}
private bool InfoBoundSuccessfully(SymbolInfo symbolInfo)
{
return InfoBoundSuccessfully(symbolInfo.Symbol);
}
private bool InfoBoundSuccessfully(QueryClauseInfo semanticInfo)
{
return InfoBoundSuccessfully(semanticInfo.OperationInfo);
}
private static bool InfoBoundSuccessfully(ISymbol operation)
{
operation = operation.GetOriginalUnreducedDefinition();
return operation != null;
}
protected override string GetDescription(INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode)
{
var root = GetCompilationUnitSyntaxNode(contextNode);
// No localization necessary
string externAliasString;
if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
{
return $"extern alias {externAliasString};";
}
string namespaceString;
if (TryGetNamespaceString(namespaceSymbol, root, false, null, out namespaceString))
{
return $"using {namespaceString};";
}
string staticNamespaceString;
if (TryGetStaticNamespaceString(namespaceSymbol, root, false, null, out staticNamespaceString))
{
return $"using static {staticNamespaceString};";
}
// If we get here then neither a namespace or an extern alias can be added.
// There is no valid string to show to the user and there is
// likely a bug that we should know about.
throw ExceptionUtilities.Unreachable;
}
protected override async Task<Document> AddImportAsync(
SyntaxNode contextNode,
INamespaceOrTypeSymbol namespaceSymbol,
Document document,
bool placeSystemNamespaceFirst,
CancellationToken cancellationToken)
{
var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var simpleUsingDirective = GetUsingDirective(root, namespaceSymbol, semanticModel, fullyQualify: false);
var externAliasUsingDirective = GetExternAliasUsingDirective(root, namespaceSymbol, semanticModel);
if (externAliasUsingDirective != null)
{
root = root.AddExterns(
externAliasUsingDirective
.WithAdditionalAnnotations(Formatter.Annotation));
}
if (simpleUsingDirective != null)
{
// Because of the way usings can be nested inside of namespace declarations,
// we need to check if the usings must be fully qualified so as not to be
// ambiguous with the containing namespace.
if (UsingsAreContainedInNamespace(contextNode))
{
// When we add usings we try and place them, as best we can, where the user
// wants them according to their settings. This means we can't just add the fully-
// qualified usings and expect the simplifier to take care of it, the usings have to be
// simplified before we attempt to add them to the document.
// You might be tempted to think that we could call
// AddUsings -> Simplifier -> SortUsings
// But this will clobber the users using settings without asking. Instead we create a new
// Document and check if our using can be simplified. Worst case we need to back out the
// fully qualified change and reapply with the simple name.
var fullyQualifiedUsingDirective = GetUsingDirective(root, namespaceSymbol, semanticModel, fullyQualify: true);
SyntaxNode newRoot = root.AddUsingDirective(
fullyQualifiedUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
var newDocument = document.WithSyntaxRoot(newRoot);
var newSemanticModel = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newUsing = newRoot
.DescendantNodes().OfType<UsingDirectiveSyntax>().Where(uds => uds.IsEquivalentTo(fullyQualifiedUsingDirective, topLevel: true)).Single();
var speculationAnalyzer = new SpeculationAnalyzer(newUsing.Name, simpleUsingDirective.Name, newSemanticModel, cancellationToken);
if (speculationAnalyzer.ReplacementChangesSemantics())
{
// Not fully qualifying the using causes to refer to a different namespace so we need to keep it as is.
return newDocument;
}
else
{
// It does not matter if it is fully qualified or simple so lets return the simple name.
return document.WithSyntaxRoot(root.AddUsingDirective(
simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation));
}
}
else
{
// simple form
return document.WithSyntaxRoot(root.AddUsingDirective(
simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation));
}
}
return document.WithSyntaxRoot(root);
}
private static ExternAliasDirectiveSyntax GetExternAliasUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel)
{
string externAliasString;
if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
{
return SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(externAliasString));
}
return null;
}
private UsingDirectiveSyntax GetUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, bool fullyQualify)
{
if (namespaceSymbol is INamespaceSymbol)
{
string namespaceString;
string externAliasString;
TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString);
if (externAliasString != null)
{
if (TryGetNamespaceString(namespaceSymbol, root, false, externAliasString, out namespaceString))
{
return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString).WithAdditionalAnnotations(Simplifier.Annotation));
}
return null;
}
if (TryGetNamespaceString(namespaceSymbol, root, fullyQualify, null, out namespaceString))
{
return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString).WithAdditionalAnnotations(Simplifier.Annotation));
}
}
if (namespaceSymbol is ITypeSymbol)
{
string staticNamespaceString;
if (TryGetStaticNamespaceString(namespaceSymbol, root, fullyQualify, null, out staticNamespaceString))
{
return SyntaxFactory.UsingDirective(
SyntaxFactory.Token(SyntaxKind.UsingKeyword),
SyntaxFactory.Token(SyntaxKind.StaticKeyword),
null,
SyntaxFactory.ParseName(staticNamespaceString).WithAdditionalAnnotations(Simplifier.Annotation),
SyntaxFactory.Token(SyntaxKind.SemicolonToken));
}
}
return null;
}
private bool UsingsAreContainedInNamespace(SyntaxNode contextNode)
{
return contextNode.GetAncestor<NamespaceDeclarationSyntax>()?.DescendantNodes().OfType<UsingDirectiveSyntax>().FirstOrDefault() != null;
}
private static bool TryGetExternAliasString(INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, out string externAliasString)
{
externAliasString = null;
var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly);
if (metadataReference == null)
{
return false;
}
var aliases = metadataReference.Properties.Aliases;
if (aliases.IsEmpty)
{
return false;
}
aliases = metadataReference.Properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray();
if (!aliases.Any())
{
return false;
}
externAliasString = aliases.First();
return ShouldAddExternAlias(aliases, root);
}
private static bool TryGetNamespaceString(INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias, out string namespaceString)
{
if (namespaceSymbol is ITypeSymbol)
{
namespaceString = null;
return false;
}
namespaceString = fullyQualify
? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
: namespaceSymbol.ToDisplayString();
if (alias != null)
{
namespaceString = alias + "::" + namespaceString;
}
return ShouldAddUsing(namespaceString, root);
}
private static bool TryGetStaticNamespaceString(INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias, out string namespaceString)
{
if (namespaceSymbol is INamespaceSymbol)
{
namespaceString = null;
return false;
}
namespaceString = fullyQualify
? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
: namespaceSymbol.ToDisplayString();
if (alias != null)
{
namespaceString = alias + "::" + namespaceString;
}
return ShouldAddStaticUsing(namespaceString, root);
}
private static bool ShouldAddExternAlias(ImmutableArray<string> aliases, CompilationUnitSyntax root)
{
var identifiers = root.DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Select(e => e.Identifier.ToString());
var externAliases = aliases.Where(a => identifiers.Contains(a));
return !externAliases.Any();
}
private static bool ShouldAddUsing(string usingDirective, CompilationUnitSyntax root)
{
var simpleUsings = root.Usings.Where(u => u.StaticKeyword.IsKind(SyntaxKind.None));
return !simpleUsings.Any(u => u.Name.ToString() == usingDirective);
}
private static bool ShouldAddStaticUsing(string usingDirective, CompilationUnitSyntax root)
{
var staticUsings = root.Usings.Where(u => u.StaticKeyword.IsKind(SyntaxKind.StaticKeyword));
return !staticUsings.Any(u => u.Name.ToString() == usingDirective);
}
private static CompilationUnitSyntax GetCompilationUnitSyntaxNode(SyntaxNode contextNode, CancellationToken cancellationToken = default(CancellationToken))
{
return (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
}
protected override bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
var leftExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression) ?? syntaxFacts.GetExpressionOfConditionalMemberAccessExpression(expression);
if (leftExpression == null)
{
if (expression.IsKind(SyntaxKind.CollectionInitializerExpression))
{
leftExpression = expression.GetAncestor<ObjectCreationExpressionSyntax>();
}
else
{
return false;
}
}
var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken);
var leftExpressionType = semanticInfo.Type;
return leftExpressionType != null && method.ReduceExtensionMethod(leftExpressionType) != null;
}
protected override IEnumerable<ITypeSymbol> GetProposedTypes(string name, List<ITypeSymbol> accessibleTypeSymbols, SemanticModel semanticModel, ISet<INamespaceSymbol> namespacesInScope)
{
if (accessibleTypeSymbols == null)
{
yield break;
}
foreach (var typeSymbol in accessibleTypeSymbols)
{
if ((typeSymbol != null) && (typeSymbol.ContainingType != null) && typeSymbol.ContainingType.IsStatic)
{
yield return typeSymbol.ContainingType;
}
}
}
internal override bool IsViableField(IFieldSymbol field, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
return IsViablePropertyOrField(field, expression, semanticModel, syntaxFacts, cancellationToken);
}
internal override bool IsViableProperty(IPropertySymbol property, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
return IsViablePropertyOrField(property, expression, semanticModel, syntaxFacts, cancellationToken);
}
private bool IsViablePropertyOrField(ISymbol propertyOrField, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
if (!propertyOrField.IsStatic)
{
return false;
}
var leftName = (expression as MemberAccessExpressionSyntax)?.Expression as SimpleNameSyntax;
if (leftName == null)
{
return false;
}
return string.Compare(propertyOrField.ContainingType.Name, leftName.Identifier.Text, this.IgnoreCase) == 0;
}
internal override bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel)
{
if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
{
var objectCreationExpressionSyntax = node.GetAncestor<ObjectCreationExpressionSyntax>();
if (objectCreationExpressionSyntax == null)
{
return false;
}
return true;
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Jovian.CascadePro
{
public interface canRender
{
string str();
}
public interface cssValue : canRender
{
}
public interface cssSelector : canRender
{
}
public class cssNamedValue : cssValue
{
string Name;
public cssNamedValue(string n)
{
Name = n.ToLower();
}
public string str()
{
return Name;
}
}
public class cssValueHexColor : cssValue
{
string Hex;
public cssValueHexColor(string h)
{
Hex = h;
}
public string str()
{
return "#" + Hex.ToUpper();
}
}
public class cssValueRGBColor : cssValue
{
string C;
public cssValueRGBColor(string c)
{
C = c;
}
public string str()
{
return "rgb" + C;
}
}
public class cssValueUnitNumber : cssValue
{
string Value;
string Unit;
public cssValueUnitNumber(string v, string un)
{
Value = v;
Unit = un;
}
public string unit()
{
if (Unit.Equals("pixel")) return "px";
if (Unit.Equals("percentage")) return "%";
if (Unit.Equals("point")) return "pt";
if (Unit.Equals("em")) return "em";
return "";
}
public string str()
{
return Value + unit();
}
}
public class cssValueURL : cssValue
{
public string Value;
public cssValueURL(string v)
{
Value = v.Substring(0, v.Length - 1).Substring(1).Trim(); ;
if (Value[0] == '"' || Value[0] == '\'') Value = Value.Substring(1);
if (Value[Value.Length - 1] == '"' || Value[Value.Length - 1] == '\'') Value = Value.Substring(0,Value.Length - 1);
}
public string str()
{
return "url(" + Value + ")";
}
}
public class cssValueCompose : cssValue
{
public cssValue Root;
public cssValue Ext;
public cssValueCompose(cssValue a, cssValue b)
{
Root = a;
Ext = b;
}
public string str()
{
return Root.str() + " " + Ext.str();
}
}
public class cssValueJoin : cssValue
{
public cssValue Root;
public cssValue Ext;
public cssValueJoin(cssValue a, cssValue b)
{
Root = a;
Ext = b;
}
public string str()
{
return Root.str() + "," + Ext.str();
}
}
public class cssProperty : canRender
{
public string Name;
public cssValue Value;
public cssProperty(string n, cssValue v)
{
Name = n;
Value = v;
}
public string str()
{
return Name + ":" + Value.str();
}
}
public class cssPropertySet : canRender
{
public List<cssProperty> Properties;
public cssPropertySet()
{
Properties = new List<cssProperty>();
}
public void Add(cssProperty p)
{
Properties.Add(p);
}
public string str()
{
string x = "";
foreach (cssProperty p in Properties)
{
x += p.str() + ";";
}
return x;
}
}
/**
*** SELECTORS
**/
public class cssSelectorClass : cssSelector
{
public string ClassName;
public bool ReWrite;
public cssSelectorClass(string cn, bool rew)
{
ClassName = cn;
ReWrite = rew;
}
public string str()
{
return "." + ClassName;
}
}
public class cssSelectorElement : cssSelector
{
public string Element;
public cssSelectorElement(string cn)
{
Element = cn;
}
public string str()
{
return Element.ToUpper();
}
}
public class cssSelectorApply : cssSelector
{
public cssSelector Base;
public string Ext;
public cssSelectorApply(cssSelector s, string e)
{
Base = s;
Ext = e;
}
public string str()
{
return Base.str() + ":" + Ext;
}
}
public class cssSelectorCompose : cssSelector
{
public cssSelector Root;
public cssSelector Ext;
public cssSelectorCompose(cssSelector a, cssSelector b)
{
Root = a;
Ext = b;
}
public string str()
{
return Root.str() + " " + Ext.str();
}
}
public class cssSelectorSet : canRender
{
public List<cssSelector> Selectors;
public cssSelectorSet()
{
Selectors = new List<cssSelector>();
}
public void Add(cssSelector s)
{
Selectors.Add(s);
}
public string str()
{
string x = "";
foreach (cssSelector p in Selectors)
{
if (x.Length > 0) x += ",";
x += p.str();
}
return x;
}
}
public class cssRule : canRender
{
public cssSelectorSet Selectors;
public cssPropertySet Properties;
public cssRule(cssSelectorSet s, cssPropertySet p)
{
Selectors = s;
Properties = p;
}
public string str()
{
return Selectors.str() + " {" + Properties.str() + "}";
}
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Security.Principal;
using System.Management.Automation.Runspaces;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Remoting;
using System.Management.Automation.Internal;
using System.Threading;
namespace System.Management.Automation
{
/// <summary>
/// This class wraps a PowerShell object. It is used to function
/// as a server side powershell
/// </summary>
internal class ServerPowerShellDriver
{
#region Private Members
private bool _extraPowerShellAlreadyScheduled;
private PowerShell _extraPowerShell; // extra PowerShell at the server to be run after localPowerShell
private PSDataCollection<PSObject> _localPowerShellOutput; // output buffer for the local PowerShell
// that is associated with this
// powershell driver
// associated with this powershell
// data structure handler object to handle all
// communications with the client
private bool[] _datasent = new bool[2]; // if the remaining data has been sent
// to the client before sending state
// information
private object _syncObject = new object(); // sync object for synchronizing sending
// data to client
private bool _noInput; // there is no input when this driver
// was created
private bool _addToHistory;
private ServerRemoteHost _remoteHost; // the server remote host instance
// associated with this powershell
#if !CORECLR // No ApartmentState In CoreCLR
private ApartmentState apartmentState; // apartment state for this powershell
#endif
private IRSPDriverInvoke _psDriverInvoker; // Handles nested invocation of PS drivers.
#endregion Private Members
#region Constructors
#if !CORECLR
/// <summary>
/// Default constructor for creating ServerPowerShellDrivers
/// </summary>
/// <param name="powershell">decoded powershell object</param>
/// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param>
/// <param name="noInput">whether there is input for this powershell</param>
/// <param name="clientPowerShellId">the client powershell id</param>
/// <param name="clientRunspacePoolId">the client runspacepool id</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="apartmentState">apartment state for this powershell</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">serialization options for the streams in this powershell</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse)
: this(powershell, extraPowerShell, noInput, clientPowerShellId, clientRunspacePoolId, runspacePoolDriver,
apartmentState, hostInfo, streamOptions, addToHistory, rsToUse, null)
{
}
#else
/// <summary>
/// Default constructor for creating ServerPowerShellDrivers
/// </summary>
/// <param name="powershell">decoded powershell object</param>
/// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param>
/// <param name="noInput">whether there is input for this powershell</param>
/// <param name="clientPowerShellId">the client powershell id</param>
/// <param name="clientRunspacePoolId">the client runspacepool id</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">serialization options for the streams in this powershell</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse)
: this(powershell, extraPowerShell, noInput, clientPowerShellId, clientRunspacePoolId, runspacePoolDriver,
hostInfo, streamOptions, addToHistory, rsToUse, null)
{
}
#endif
#if CORECLR
/// <summary>
/// Default constructor for creating ServerPowerShellDrivers
/// </summary>
/// <param name="powershell">decoded powershell object</param>
/// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param>
/// <param name="noInput">whether there is input for this powershell</param>
/// <param name="clientPowerShellId">the client powershell id</param>
/// <param name="clientRunspacePoolId">the client runspacepool id</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">serialization options for the streams in this powershell</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
/// <param name="output">
/// If not null, this is used as another source of output sent to the client.
/// </param>
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse, PSDataCollection<PSObject> output)
#else
/// <summary>
/// Default constructor for creating ServerPowerShellDrivers
/// </summary>
/// <param name="powershell">decoded powershell object</param>
/// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param>
/// <param name="noInput">whether there is input for this powershell</param>
/// <param name="clientPowerShellId">the client powershell id</param>
/// <param name="clientRunspacePoolId">the client runspacepool id</param>
/// <param name="runspacePoolDriver">runspace pool driver
/// which is creating this powershell driver</param>
/// <param name="apartmentState">apartment state for this powershell</param>
/// <param name="hostInfo">host info using which the host for
/// this powershell will be constructed</param>
/// <param name="streamOptions">serialization options for the streams in this powershell</param>
/// <param name="addToHistory">
/// true if the command is to be added to history list of the runspace. false, otherwise.
/// </param>
/// <param name="rsToUse">
/// If not null, this Runspace will be used to invoke Powershell.
/// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
/// </param>
/// <param name="output">
/// If not null, this is used as another source of output sent to the client.
/// </param>
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
bool addToHistory, Runspace rsToUse, PSDataCollection<PSObject> output)
#endif
{
InstanceId = clientPowerShellId;
RunspacePoolId = clientRunspacePoolId;
RemoteStreamOptions = streamOptions;
#if !CORECLR // No ApartmentState In CoreCLR
this.apartmentState = apartmentState;
#endif
LocalPowerShell = powershell;
_extraPowerShell = extraPowerShell;
_localPowerShellOutput = new PSDataCollection<PSObject>();
_noInput = noInput;
_addToHistory = addToHistory;
_psDriverInvoker = runspacePoolDriver;
DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, LocalPowerShell);
_remoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);
if (!noInput)
{
InputCollection = new PSDataCollection<object>();
InputCollection.ReleaseOnEnumeration = true;
InputCollection.IdleEvent += new EventHandler<EventArgs>(HandleIdleEvent);
}
RegisterPipelineOutputEventHandlers(_localPowerShellOutput);
if (LocalPowerShell != null)
{
RegisterPowerShellEventHandlers(LocalPowerShell);
_datasent[0] = false;
}
if (extraPowerShell != null)
{
RegisterPowerShellEventHandlers(extraPowerShell);
_datasent[1] = false;
}
RegisterDataStructureHandlerEventHandlers(DataStructureHandler);
// set the runspace pool and invoke this powershell
if (null != rsToUse)
{
LocalPowerShell.Runspace = rsToUse;
if (extraPowerShell != null)
{
extraPowerShell.Runspace = rsToUse;
}
}
else
{
LocalPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
if (extraPowerShell != null)
{
extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
}
}
if (output != null)
{
output.DataAdded += (sender, args) =>
{
if (_localPowerShellOutput.IsOpen)
{
var items = output.ReadAll();
foreach (var item in items)
{
_localPowerShellOutput.Add(item);
}
}
};
}
}
#endregion Constructors
#region Internal Methods
/// <summary>
/// Input collection sync object
/// </summary>
internal PSDataCollection<object> InputCollection { get; }
/// <summary>
/// Local PowerShell instance
/// </summary>
internal PowerShell LocalPowerShell { get; }
/// <summary>
/// Instance id by which this powershell driver is
/// identified. This is the same as the id of the
/// powershell on the client side
/// </summary>
internal Guid InstanceId { get; }
/// <summary>
/// Serialization options for the streams in this powershell
/// </summary>
internal RemoteStreamOptions RemoteStreamOptions { get; }
/// <summary>
/// Id of the runspace pool driver which created
/// this object. This is the same as the id of
/// the runspace pool at the client side which
/// is associated with the powershell on the
/// client side
/// </summary>
internal Guid RunspacePoolId { get; }
/// <summary>
/// ServerPowerShellDataStructureHandler associated with this
/// powershell driver
/// </summary>
internal ServerPowerShellDataStructureHandler DataStructureHandler { get; }
private PSInvocationSettings PrepInvoke(bool startMainPowerShell)
{
if (startMainPowerShell)
{
// prepare transport manager for sending and receiving data.
DataStructureHandler.Prepare();
}
PSInvocationSettings settings = new PSInvocationSettings();
#if !CORECLR // No ApartmentState In CoreCLR
settings.ApartmentState = apartmentState;
#endif
settings.Host = _remoteHost;
// Flow the impersonation policy to pipeline execution thread
// only if the current thread is impersonated (Delegation is
// also a kind of impersonation).
if (Platform.IsWindows)
{
WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent();
switch (currentThreadIdentity.ImpersonationLevel)
{
case TokenImpersonationLevel.Impersonation:
case TokenImpersonationLevel.Delegation:
settings.FlowImpersonationPolicy = true;
break;
default:
settings.FlowImpersonationPolicy = false;
break;
}
}
else
{
settings.FlowImpersonationPolicy = false;
}
settings.AddToHistory = _addToHistory;
return settings;
}
private IAsyncResult Start(bool startMainPowerShell)
{
PSInvocationSettings settings = PrepInvoke(startMainPowerShell);
if (startMainPowerShell)
{
return LocalPowerShell.BeginInvoke<object, PSObject>(InputCollection, _localPowerShellOutput, settings, null, null);
}
else
{
return _extraPowerShell.BeginInvoke<object, PSObject>(InputCollection, _localPowerShellOutput, settings, null, null);
}
}
/// <summary>
/// invokes the powershell asynchronously
/// </summary>
internal IAsyncResult Start()
{
return Start(true);
}
/// <summary>
/// Runs no command but allows the PowerShell object on the client
/// to complete. This is used for running "virtual" remote debug
/// commands that sets debugger state but doesn't run any command
/// on the server runspace.
/// </summary>
internal void RunNoOpCommand()
{
if (LocalPowerShell != null)
{
System.Threading.ThreadPool.QueueUserWorkItem(
(state) =>
{
LocalPowerShell.SetStateChanged(
new PSInvocationStateInfo(
PSInvocationState.Running, null));
LocalPowerShell.SetStateChanged(
new PSInvocationStateInfo(
PSInvocationState.Completed, null));
});
}
}
/// <summary>
/// Invokes the Main PowerShell object synchronously.
/// </summary>
internal void InvokeMain()
{
PSInvocationSettings settings = PrepInvoke(true);
Exception ex = null;
try
{
LocalPowerShell.InvokeWithDebugger(InputCollection, _localPowerShellOutput, settings, true);
}
catch (Exception e)
{
CommandProcessor.CheckForSevereException(e);
ex = e;
}
if (ex != null)
{
// Since this is being invoked asynchronously on a single pipeline thread
// any invoke failures (such as possible debugger failures) need to be
// passed back to client or the original client invoke request will hang.
string failedCommand = LocalPowerShell.Commands.Commands[0].CommandText;
LocalPowerShell.Commands.Clear();
string msg = StringUtil.Format(
RemotingErrorIdStrings.ServerSideNestedCommandInvokeFailed,
failedCommand ?? string.Empty,
ex.Message ?? string.Empty);
LocalPowerShell.AddCommand("Write-Error").AddArgument(msg);
LocalPowerShell.Invoke();
}
}
#endregion Internal Methods
#region Private Methods
private void RegisterPowerShellEventHandlers(PowerShell powerShell)
{
powerShell.InvocationStateChanged += HandlePowerShellInvocationStateChanged;
powerShell.Streams.Error.DataAdded += HandleErrorDataAdded;
powerShell.Streams.Debug.DataAdded += HandleDebugAdded;
powerShell.Streams.Verbose.DataAdded += HandleVerboseAdded;
powerShell.Streams.Warning.DataAdded += HandleWarningAdded;
powerShell.Streams.Progress.DataAdded += HandleProgressAdded;
powerShell.Streams.Information.DataAdded += HandleInformationAdded;
}
private void UnregisterPowerShellEventHandlers(PowerShell powerShell)
{
powerShell.InvocationStateChanged -= HandlePowerShellInvocationStateChanged;
powerShell.Streams.Error.DataAdded -= HandleErrorDataAdded;
powerShell.Streams.Debug.DataAdded -= HandleDebugAdded;
powerShell.Streams.Verbose.DataAdded -= HandleVerboseAdded;
powerShell.Streams.Warning.DataAdded -= HandleWarningAdded;
powerShell.Streams.Progress.DataAdded -= HandleProgressAdded;
powerShell.Streams.Information.DataAdded -= HandleInformationAdded;
}
private void RegisterDataStructureHandlerEventHandlers(ServerPowerShellDataStructureHandler dsHandler)
{
dsHandler.InputEndReceived += HandleInputEndReceived;
dsHandler.InputReceived += HandleInputReceived;
dsHandler.StopPowerShellReceived += HandleStopReceived;
dsHandler.HostResponseReceived += HandleHostResponseReceived;
dsHandler.OnSessionConnected += HandleSessionConnected;
}
private void UnregisterDataStructureHandlerEventHandlers(ServerPowerShellDataStructureHandler dsHandler)
{
dsHandler.InputEndReceived -= HandleInputEndReceived;
dsHandler.InputReceived -= HandleInputReceived;
dsHandler.StopPowerShellReceived -= HandleStopReceived;
dsHandler.HostResponseReceived -= HandleHostResponseReceived;
dsHandler.OnSessionConnected -= HandleSessionConnected;
}
private void RegisterPipelineOutputEventHandlers(PSDataCollection<PSObject> pipelineOutput)
{
pipelineOutput.DataAdded += HandleOutputDataAdded;
}
private void UnregisterPipelineOutputEventHandlers(PSDataCollection<PSObject> pipelineOutput)
{
pipelineOutput.DataAdded -= HandleOutputDataAdded;
}
/// <summary>
/// Handle state changed information from PowerShell
/// and send it to the client
/// </summary>
/// <param name="sender">sender of this event</param>
/// <param name="eventArgs">arguments describing state changed
/// information for this powershell</param>
private void HandlePowerShellInvocationStateChanged(object sender,
PSInvocationStateChangedEventArgs eventArgs)
{
PSInvocationState state = eventArgs.InvocationStateInfo.State;
switch (state)
{
case PSInvocationState.Completed:
case PSInvocationState.Failed:
case PSInvocationState.Stopped:
{
if (LocalPowerShell.RunningExtraCommands)
{
// If completed successfully then allow extra commands to run.
if (state == PSInvocationState.Completed) { return; }
// For failed or stopped state, extra commands cannot run and
// we allow this command invocation to finish.
}
// send the remaining data before sending in
// state information. This is required because
// the client side runspace pool will remove
// the association with the client side powershell
// once the powershell reaches a terminal state.
// If the association is removed, then any data
// sent to the powershell will be discarded by
// the runspace pool data structure handler on the client side
SendRemainingData();
if (state == PSInvocationState.Completed &&
(_extraPowerShell != null) &&
!_extraPowerShellAlreadyScheduled)
{
_extraPowerShellAlreadyScheduled = true;
Start(false);
}
else
{
DataStructureHandler.RaiseRemoveAssociationEvent();
// send the state change notification to the client
DataStructureHandler.SendStateChangedInformationToClient(
eventArgs.InvocationStateInfo);
UnregisterPowerShellEventHandlers(LocalPowerShell);
if (_extraPowerShell != null)
{
UnregisterPowerShellEventHandlers(_extraPowerShell);
}
UnregisterDataStructureHandlerEventHandlers(DataStructureHandler);
UnregisterPipelineOutputEventHandlers(_localPowerShellOutput);
// BUGBUG: currently the local powershell cannot
// be disposed as raising the events is
// not done towards the end. Need to fix
// powershell in order to get this enabled
//localPowerShell.Dispose();
}
}
break;
case PSInvocationState.Stopping:
{
// abort all pending host calls
_remoteHost.ServerMethodExecutor.AbortAllCalls();
}
break;
}
}
/// <summary>
/// Handles DataAdded event from the Output of the powershell
/// </summary>
/// <param name="sender">sender of this information</param>
/// <param name="e">arguments describing this event</param>
private void HandleOutputDataAdded(object sender, DataAddedEventArgs e)
{
int index = e.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if (!_datasent[indexIntoDataSent])
{
PSObject data = _localPowerShellOutput[index];
// once send the output is removed so that the same
// is not sent again by SendRemainingData() method
_localPowerShellOutput.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendOutputDataToClient(data);
}
} // lock ..
}
/// <summary>
/// Handles DataAdded event from Error of the PowerShell
/// </summary>
/// <param name="sender">sender of this event</param>
/// <param name="e">arguments describing this event</param>
private void HandleErrorDataAdded(object sender, DataAddedEventArgs e)
{
int index = e.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
ErrorRecord errorRecord = LocalPowerShell.Streams.Error[index];
// once send the error record is removed so that the same
// is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Error.RemoveAt(index);
// send the error record to the client
DataStructureHandler.SendErrorRecordToClient(errorRecord);
}
} // lock ...
}
/// <summary>
/// Handles DataAdded event from Progress of PowerShell
/// </summary>
/// <param name="sender">sender of this information, unused</param>
/// <param name="eventArgs">arguments describing this event</param>
private void HandleProgressAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
ProgressRecord data = LocalPowerShell.Streams.Progress[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Progress.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendProgressRecordToClient(data);
}
} // lock ..
}
/// <summary>
/// Handles DataAdded event from Warning of PowerShell
/// </summary>
/// <param name="sender">sender of this information, unused</param>
/// <param name="eventArgs">arguments describing this event</param>
private void HandleWarningAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
WarningRecord data = LocalPowerShell.Streams.Warning[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Warning.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendWarningRecordToClient(data);
}
} // lock ..
}
/// <summary>
/// Handles DataAdded from Verbose of PowerShell
/// </summary>
/// <param name="sender">sender of this information, unused</param>
/// <param name="eventArgs">sender of this information</param>
private void HandleVerboseAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
VerboseRecord data = LocalPowerShell.Streams.Verbose[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Verbose.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendVerboseRecordToClient(data);
}
} // lock ..
}
/// <summary>
/// Handles DataAdded from Debug of PowerShell
/// </summary>
/// <param name="sender">sender of this information, unused</param>
/// <param name="eventArgs">sender of this information</param>
private void HandleDebugAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
DebugRecord data = LocalPowerShell.Streams.Debug[index];
// once the debug message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Debug.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendDebugRecordToClient(data);
}
} // lock ..
}
/// <summary>
/// Handles DataAdded from Information of PowerShell
/// </summary>
/// <param name="sender">sender of this information, unused</param>
/// <param name="eventArgs">sender of this information</param>
private void HandleInformationAdded(object sender, DataAddedEventArgs eventArgs)
{
int index = eventArgs.Index;
lock (_syncObject)
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
if ((indexIntoDataSent == 0) && (!_datasent[indexIntoDataSent]))
{
InformationRecord data = LocalPowerShell.Streams.Information[index];
// once the Information message is sent, it is removed so that
// the same is not sent again by SendRemainingData() method
LocalPowerShell.Streams.Information.RemoveAt(index);
// send the output data to the client
DataStructureHandler.SendInformationRecordToClient(data);
}
} // lock ..
}
/// <summary>
/// Send the remaining output and error information to
/// client
/// </summary>
/// <remarks>This method should be called before
/// sending the state information. The client will
/// remove the association between a powershell and
/// runspace pool if it receives any of the terminal
/// states. Hence all the remaining data should be
/// sent before this happens. Else the data will be
/// discarded</remarks>
private void SendRemainingData()
{
int indexIntoDataSent = (!_extraPowerShellAlreadyScheduled) ? 0 : 1;
lock (_syncObject)
{
_datasent[indexIntoDataSent] = true;
}
try
{
// BUGBUG: change this code to use enumerator
// blocked on bug #108824, to be fixed by Kriscv
for (int i = 0; i < _localPowerShellOutput.Count; i++)
{
PSObject data = _localPowerShellOutput[i];
DataStructureHandler.SendOutputDataToClient(data);
}
_localPowerShellOutput.Clear();
//foreach (ErrorRecord errorRecord in localPowerShell.Error)
for (int i = 0; i < LocalPowerShell.Streams.Error.Count; i++)
{
ErrorRecord errorRecord = LocalPowerShell.Streams.Error[i];
DataStructureHandler.SendErrorRecordToClient(errorRecord);
}
LocalPowerShell.Streams.Error.Clear();
}
finally
{
lock (_syncObject)
{
// reset to original state so other pipelines can stream.
_datasent[indexIntoDataSent] = true;
}
}
}
/// <summary>
/// Stop the local powershell
/// </summary>
/// <param name="sender">sender of this event, unused</param>
/// <param name="eventArgs">unused</param>
private void HandleStopReceived(object sender, EventArgs eventArgs)
{
do // false loop
{
if (LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped ||
LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Completed ||
LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Failed ||
LocalPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping)
{
break;
}
else
{
// Ensure that the local PowerShell command is not stopped in debug mode.
bool handledByDebugger = false;
if (!LocalPowerShell.IsNested &&
_psDriverInvoker != null)
{
handledByDebugger = _psDriverInvoker.HandleStopSignal();
}
if (!handledByDebugger)
{
LocalPowerShell.Stop();
}
}
} while (false);
if (_extraPowerShell != null)
{
do // false loop
{
if (_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped ||
_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Completed ||
_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Failed ||
_extraPowerShell.InvocationStateInfo.State == PSInvocationState.Stopping)
{
break;
}
else
{
_extraPowerShell.Stop();
}
} while (false);
}
}
/// <summary>
/// Add input to the local powershell's input collection
/// </summary>
/// <param name="sender">sender of this event, unused</param>
/// <param name="eventArgs">arguments describing this event</param>
private void HandleInputReceived(object sender, RemoteDataEventArgs<object> eventArgs)
{
// This can be called in pushed runspace scenarios for error reporting (pipeline stopped).
// Ignore for noInput.
if (!_noInput && (InputCollection != null))
{
InputCollection.Add(eventArgs.Data);
}
}
/// <summary>
/// Close the input collection of the local powershell
/// </summary>
/// <param name="sender">sender of this event, unused</param>
/// <param name="eventArgs">arguments describing this event</param>
private void HandleInputEndReceived(object sender, EventArgs eventArgs)
{
// This can be called in pushed runspace scenarios for error reporting (pipeline stopped).
// Ignore for noInput.
if (!_noInput && (InputCollection != null))
{
InputCollection.Complete();
}
}
private void HandleSessionConnected(object sender, EventArgs eventArgs)
{
//Close input if its active. no need to synchronize as input stream would have already been processed
// when connect call came into PS plugin
if (InputCollection != null)
{
//TODO: Post an ETW event
InputCollection.Complete();
}
}
/// <summary>
/// Handle a host message response received
/// </summary>
/// <param name="sender">sender of this event, unused</param>
/// <param name="eventArgs">arguments describing this event</param>
private void HandleHostResponseReceived(object sender, RemoteDataEventArgs<RemoteHostResponse> eventArgs)
{
_remoteHost.ServerMethodExecutor.HandleRemoteHostResponseFromClient(eventArgs.Data);
}
/// <summary>
/// Handles the PSDataCollection idle event
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void HandleIdleEvent(object sender, EventArgs args)
{
Runspace rs = DataStructureHandler.RunspaceUsedToInvokePowerShell;
if (rs != null)
{
PSLocalEventManager events = (object)rs.Events as PSLocalEventManager;
if (events != null)
{
foreach (PSEventSubscriber subscriber in events.Subscribers)
{
// Use the synchronous version
events.DrainPendingActions(subscriber);
}
}
}
}
#endregion Private Methods
}
}
| |
#define _RESTRICT_ATTRIBUTE_ACCESS
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.VFX;
using UnityEditor.Experimental.GraphView;
using UnityEngine.Profiling;
namespace UnityEditor.VFX.UI
{
interface IVFXAnchorController
{
void Connect(VFXEdgeController edgeController);
void Disconnect(VFXEdgeController edgeController);
Direction direction { get; }
}
abstract class VFXDataAnchorController : VFXController<VFXSlot>, IVFXAnchorController, IPropertyRMProvider, IGizmoable
{
private VFXNodeController m_SourceNode;
public VFXNodeController sourceNode
{
get
{
return m_SourceNode;
}
}
public VFXCoordinateSpace space
{
get
{
return model.space;
}
set
{
model.space = value;
}
}
public bool spaceableAndMasterOfSpace
{
get
{
return model.spaceable && model.IsMasterSlot();
}
}
public bool IsSpaceInherited()
{
return model.IsSpaceInherited();
}
public override string name
{
get
{
return base.name;
}
}
VFXSlot m_MasterSlot;
public Type portType { get; set; }
public Type storageType
{
get
{
if (typeof(Texture).IsAssignableFrom(portType))
{
return typeof(Texture);
}
return portType;
}
}
public VFXDataAnchorController(VFXSlot model, VFXNodeController sourceNode, bool hidden) : base(sourceNode.viewController, model)
{
m_SourceNode = sourceNode;
m_Hidden = hidden;
m_Expanded = expandedSelf;
if (model != null)
{
portType = model.property.type;
if (model.GetMasterSlot() != null && model.GetMasterSlot() != model)
{
m_MasterSlot = model.GetMasterSlot();
viewController.RegisterNotification(m_MasterSlot, MasterSlotChanged);
}
ModelChanged(model);
}
}
void MasterSlotChanged()
{
if (m_MasterSlot == null)
return;
ModelChanged(m_MasterSlot);
}
bool m_Expanded;
protected override void ModelChanged(UnityEngine.Object obj)
{
Profiler.BeginSample("VFXDataAnchorController.ModelChanged");
if (expandedSelf != m_Expanded)
{
m_Expanded = expandedSelf;
UpdateHiddenRecursive(m_Hidden, true);
}
Profiler.BeginSample("VFXDataAnchorController.ModelChanged:UpdateInfos");
UpdateInfos();
Profiler.EndSample();
sourceNode.DataEdgesMightHaveChanged();
Profiler.BeginSample("VFXDataAnchorController.NotifyChange");
NotifyChange(AnyThing);
Profiler.EndSample();
Profiler.EndSample();
}
public override void OnDisable()
{
if (!object.ReferenceEquals(m_MasterSlot, null))
{
viewController.UnRegisterNotification(m_MasterSlot, MasterSlotChanged);
m_MasterSlot = null;
}
base.OnDisable();
}
public virtual bool HasLink()
{
return model.HasLink();
}
#if _RESTRICT_ATTRIBUTE_ACCESS
static private bool DependOnAttribute(object model)
{
return model is VFXAttributeParameter || model is Operator.AgeOverLifetime;
}
static private HashSet<IVFXSlotContainer> CollectDescendantOfAttribute(IEnumerable<VFXNodeController> allSlotContainerControllers)
{
var operatorDependOnAttribute = new HashSet<IVFXSlotContainer>();
foreach (var attributeParameter in allSlotContainerControllers.Where(o => DependOnAttribute(o.model)))
{
VFXViewController.CollectDescendantOperator(attributeParameter.model as IVFXSlotContainer, operatorDependOnAttribute);
}
return operatorDependOnAttribute;
}
static private HashSet<IVFXSlotContainer> CollectAnscestorOfSpawner(IEnumerable<VFXNodeController> allSlotContainerControllers)
{
var operatorDependOnSpawner = new HashSet<IVFXSlotContainer>();
foreach (var block in allSlotContainerControllers.Where(o => o.model is VFXBlock && (o.model as VFXBlock).GetParent().contextType == VFXContextType.kSpawner))
{
VFXViewController.CollectAncestorOperator(block.model as IVFXSlotContainer, operatorDependOnSpawner);
}
return operatorDependOnSpawner;
}
#endif
public class CanLinkCache
{
#if _RESTRICT_ATTRIBUTE_ACCESS
internal HashSet<IVFXSlotContainer> ancestorOfSpawners;
internal HashSet<IVFXSlotContainer> descendantOfAttribute;
#endif
internal HashSet<IVFXSlotContainer> localChildrenOperator = new HashSet<IVFXSlotContainer>();
internal HashSet<IVFXSlotContainer> localParentOperator = new HashSet<IVFXSlotContainer>();
}
public bool CanLinkToNode(VFXNodeController nodeController, CanLinkCache cache)
{
if (nodeController == sourceNode)
return false;
if (cache == null)
cache = new CanLinkCache();
cache.localChildrenOperator.Clear();
cache.localParentOperator.Clear();
bool result;
if (direction != Direction.Input)
{
VFXViewController.CollectAncestorOperator(sourceNode.slotContainer, cache.localParentOperator);
#if _RESTRICT_ATTRIBUTE_ACCESS
if (cache.localParentOperator.Any(o => DependOnAttribute(o)))
{
if (cache.ancestorOfSpawners == null)
cache.ancestorOfSpawners = CollectAnscestorOfSpawner(viewController.AllSlotContainerControllers);
var additionnalExcludeOperator = cache.ancestorOfSpawners;
cache.localChildrenOperator.UnionWith(additionnalExcludeOperator);
}
#endif
result = !cache.localParentOperator.Contains(nodeController.slotContainer);
}
else
{
VFXViewController.CollectDescendantOperator(sourceNode.slotContainer, cache.localChildrenOperator);
#if _RESTRICT_ATTRIBUTE_ACCESS
var contextTypeInChildren = cache.localChildrenOperator.OfType<VFXBlock>().Select(o => o.GetParent().contextType);
if (contextTypeInChildren.Any(o => o == VFXContextType.kSpawner))
{
if (cache.descendantOfAttribute == null)
cache.descendantOfAttribute = CollectDescendantOfAttribute(viewController.AllSlotContainerControllers);
var additionnalExcludeOperator = cache.descendantOfAttribute;
return !cache.localParentOperator.Contains(sourceNode.slotContainer) && !additionnalExcludeOperator.Contains(nodeController.slotContainer);
}
#endif
result = !cache.localChildrenOperator.Contains(nodeController.slotContainer);
}
return result;
}
public virtual bool CanLink(VFXDataAnchorController controller, CanLinkCache cache = null)
{
if (controller.model != null)
{
if (model.CanLink(controller.model) && controller.model.CanLink(model))
{
if (!CanLinkToNode(controller.sourceNode, cache))
return false;
return true;
}
return sourceNode.CouldLink(this, controller, cache);
}
return controller.CanLink(this, cache);
}
public virtual VFXParameter.NodeLinkedSlot CreateLinkTo(VFXDataAnchorController output)
{
var slotOutput = output != null ? output.model : null;
var slotInput = model;
sourceNode.WillCreateLink(ref slotInput, ref slotOutput);
if (slotInput != null && slotOutput != null && slotInput.Link(slotOutput))
{
return new VFXParameter.NodeLinkedSlot() {inputSlot = slotInput, outputSlot = slotOutput};
}
return new VFXParameter.NodeLinkedSlot();
}
public class Change
{
public const int hidden = 1;
}
private void UpdateHiddenRecursive(bool parentCollapsed, bool firstLevel)
{
bool changed = m_Hidden != parentCollapsed;
if (changed || firstLevel)
{
m_Hidden = parentCollapsed;
var ports = (direction == Direction.Input) ? m_SourceNode.inputPorts : m_SourceNode.outputPorts;
var children = model.children;
if (model.spaceable && model.children.Count() == 1)
{
children = children.First().children;
}
foreach (var element in children.Select(t => ports.First(u => u.model == t)))
{
element.UpdateHiddenRecursive(m_Hidden || !expandedSelf, false);
}
if (changed && !firstLevel) //Do not notify on first level as it will be done by the called
NotifyChange((int)Change.hidden);
}
}
VFXPropertyAttribute[] m_Attributes;
public virtual void UpdateInfos()
{
bool sameAttributes = (m_Attributes == null && model.property.attributes == null) || (m_Attributes != null && model.property.attributes != null && Enumerable.SequenceEqual(m_Attributes, model.property.attributes));
if (model.property.type != portType || !sameAttributes)
{
portType = model.property.type;
m_Attributes = model.property.attributes;
}
}
public bool indeterminate
{
get
{
return !m_SourceNode.viewController.CanGetEvaluatedContent(model);
}
}
public virtual object value
{
get
{
if (portType != null)
{
if (!editable)
{
VFXViewController nodeController = m_SourceNode.viewController;
try
{
Profiler.BeginSample("GetEvaluatedContent");
var evaluatedValue = nodeController.GetEvaluatedContent(model);
Profiler.EndSample();
if (evaluatedValue != null)
{
return VFXConverter.ConvertTo(evaluatedValue, storageType);
}
}
catch (System.Exception e)
{
Debug.LogError("Trying to get the value from expressions threw." + e.Message + " In anchor : " + name + " from node :" + sourceNode.title);
}
}
return VFXConverter.ConvertTo(model.value, storageType);
}
else
{
return null;
}
}
set { SetPropertyValue(VFXConverter.ConvertTo(value, storageType)); }
}
List<VFXDataEdgeController> m_Connections = new List<VFXDataEdgeController>();
public virtual void Connect(VFXEdgeController edgeController)
{
m_Connections.Add(edgeController as VFXDataEdgeController);
RefreshGizmo();
}
public virtual void Disconnect(VFXEdgeController edgeController)
{
m_Connections.Remove(edgeController as VFXDataEdgeController);
RefreshGizmo();
}
public bool connected
{
get { return m_Connections.Count > 0; }
}
public IEnumerable<VFXDataEdgeController> connections { get { return m_Connections; } }
public abstract Direction direction { get; }
public Orientation orientation { get { return Orientation.Horizontal; } }
public string path
{
get { return model.path; }
}
public object[] customAttributes
{
get
{
return new object[] {};
}
}
public VFXPropertyAttribute[] attributes
{
get { return m_Attributes; }
}
public virtual int depth
{
get
{
int depth = model.depth;
if (depth > 0)
{
if (SlotShouldSkipFirstLevel(model.GetMasterSlot()))
{
--depth;
}
}
return depth;
}
}
public virtual bool expandable
{
get { return VFXContextController.IsTypeExpandable(portType); }
}
bool IPropertyRMProvider.expandableIfShowsEverything { get { return true; } }
public virtual string iconName
{
get { return portType.Name; }
}
private bool m_Hidden;
public bool expandedInHierachy
{
get
{
return !m_Hidden || connected;
}
}
public virtual bool expandedSelf
{
get
{
return !model.collapsed;
}
}
bool IPropertyRMProvider.expanded
{
get { return expandedSelf; }
}
public bool m_Editable = true;
public void UpdateEditable()
{
m_Editable = true;
if (direction == Direction.Output)
return;
VFXSlot slot = model;
if (!slot || slot.HasLink(true))
{
m_Editable = false;
return;
}
while (slot != null)
{
if (slot.HasLink())
{
m_Editable = false;
return;
}
slot = slot.GetParent();
}
}
public virtual bool editable
{
get
{
return m_Editable;
}
}
public void SetPropertyValue(object value)
{
Undo.RecordObject(model.GetMasterSlot(), "VFXSlotValue"); // The slot value is stored on the master slot, not necessarly my own slot
model.value = value;
}
public static bool SlotShouldSkipFirstLevel(VFXSlot slot)
{
return slot.spaceable && slot.children.Count() == 1;
}
public virtual void ExpandPath()
{
if (model == null) return;
model.collapsed = false;
if (SlotShouldSkipFirstLevel(model))
{
model.children.First().collapsed = model.collapsed;
}
}
public virtual void RetractPath()
{
if (model == null) return;
model.collapsed = true;
if (SlotShouldSkipFirstLevel(model))
{
model.children.First().collapsed = model.collapsed;
}
}
void RefreshGizmo()
{
if (m_GizmoContext != null) m_GizmoContext.Unprepare();
if (model == null || model.IsMasterSlot()) return;
var parentController = sourceNode.inputPorts.FirstOrDefault(t => t.model == model.GetParent());
if (parentController != null)
{
parentController.RefreshGizmo();
}
else if (model.GetParent()) // Try with grand parent for Vector3 spacable types
{
parentController = sourceNode.inputPorts.FirstOrDefault(t => t.model == model.GetParent().GetParent());
if (parentController != null)
{
parentController.RefreshGizmo();
}
}
}
public Bounds GetGizmoBounds(VisualEffect component)
{
if (m_GizmoContext != null)
{
return VFXGizmoUtility.GetGizmoBounds(m_GizmoContext, component);
}
return new Bounds();
}
public bool gizmoNeedsComponent
{
get
{
if (!VFXGizmoUtility.HasGizmo(portType))
return false;
if (m_GizmoContext == null)
{
m_GizmoContext = new VFXDataAnchorGizmoContext(this);
}
return VFXGizmoUtility.NeedsComponent(m_GizmoContext);
}
}
public bool gizmoIndeterminate
{
get
{
if (!VFXGizmoUtility.HasGizmo(portType))
return false;
if (m_GizmoContext == null)
{
m_GizmoContext = new VFXDataAnchorGizmoContext(this);
}
return m_GizmoContext.IsIndeterminate();
}
}
VFXDataAnchorGizmoContext m_GizmoContext;
public void DrawGizmo(VisualEffect component)
{
if (VFXGizmoUtility.HasGizmo(portType))
{
if (m_GizmoContext == null)
{
m_GizmoContext = new VFXDataAnchorGizmoContext(this);
}
VFXGizmoUtility.Draw(m_GizmoContext, component);
}
}
}
class VFXUpcommingDataAnchorController : VFXDataAnchorController
{
public VFXUpcommingDataAnchorController(VFXNodeController sourceNode, bool hidden) : base(null, sourceNode, hidden)
{
}
public override void OnDisable()
{
base.OnDisable();
}
public override Direction direction
{
get
{
return Direction.Input;
}
}
public override bool editable
{
get {return true; }
}
public override bool expandedSelf
{
get
{
return false;
}
}
public override bool expandable
{
get {return false; }
}
public override bool HasLink()
{
return false;
}
public override void UpdateInfos()
{
}
public override object value
{
get
{
return null;
}
set
{
}
}
public override int depth
{
get
{
return 0;
}
}
public override string name
{
get
{
return "";
}
}
public override bool CanLink(VFXDataAnchorController controller, CanLinkCache cache = null)
{
var op = (sourceNode as VFXCascadedOperatorController);
if (op == null)
return false;
if (controller is VFXUpcommingDataAnchorController)
return false;
if (!CanLinkToNode(controller.sourceNode, cache))
return false;
return op.model.GetBestAffinityType(controller.model.property.type) != null;
}
public new VFXCascadedOperatorController sourceNode
{
get { return base.sourceNode as VFXCascadedOperatorController; }
}
public override VFXParameter.NodeLinkedSlot CreateLinkTo(VFXDataAnchorController output)
{
var slotOutput = output != null ? output.model : null;
VFXOperatorNumericCascadedUnified op = sourceNode.model;
op.AddOperand(op.GetBestAffinityType(output.model.property.type));
var slotInput = op.GetInputSlot(op.GetNbInputSlots() - 1);
if (slotInput != null && slotOutput != null && slotInput.Link(slotOutput))
{
return new VFXParameter.NodeLinkedSlot() {inputSlot = slotInput, outputSlot = slotOutput};
}
return new VFXParameter.NodeLinkedSlot();
}
}
public class VFXDataAnchorGizmoContext : VFXGizmoUtility.Context
{
// Provider
internal VFXDataAnchorGizmoContext(VFXDataAnchorController controller)
{
m_Controller = controller;
}
VFXDataAnchorController m_Controller;
public override Type portType
{
get {return m_Controller.portType; }
}
List<object> stack = new List<object>();
public override object value
{
get
{
// If the vfxwindow is hidden then Update will not be called, which in turn will not recompile the expression graph. so try recompiling it now
m_Controller.viewController.RecompileExpressionGraphIfNeeded();
stack.Clear();
foreach (var action in m_ValueBuilder)
{
action(stack);
}
return stack.First();
}
}
public override VFXCoordinateSpace space
{
get
{
return m_Controller.space;
}
}
List<Action<List<object>>> m_ValueBuilder = new List<Action<List<object>>>();
protected override void InternalPrepare()
{
var type = m_Controller.portType;
if (!type.IsValueType)
{
Debug.LogError("No support for class types in Gizmos");
return;
}
m_ValueBuilder.Clear();
m_ValueBuilder.Add(o => o.Add(m_Controller.value));
if (!m_Controller.viewController.CanGetEvaluatedContent(m_Controller.model))
{
if (m_Controller.model.HasLink(false))
{
if (VFXTypeUtility.GetComponentCount(m_Controller.model) != 0)
{
m_Indeterminate = true;
return;
}
}
BuildValue(m_Controller.model);
}
}
void BuildValue(VFXSlot slot)
{
foreach (var field in slot.property.type.GetFields())
{
VFXSlot subSlot = slot.children.FirstOrDefault<VFXSlot>(t => t.name == field.Name);
if (subSlot != null)
{
object result = null ;
if (m_Controller.viewController.CanGetEvaluatedContent(subSlot) && ( result = m_Controller.viewController.GetEvaluatedContent(subSlot)) != null)
{
m_ValueBuilder.Add(o => o.Add(m_Controller.viewController.GetEvaluatedContent(subSlot)));
}
else if (subSlot.HasLink(false) && VFXTypeUtility.GetComponentCount(subSlot) != 0) // replace by is VFXType
{
m_Indeterminate = true;
return;
}
else
{
m_ValueBuilder.Add(o => o.Add(subSlot.value));
BuildValue(subSlot);
if (m_Indeterminate) return;
}
m_ValueBuilder.Add(o => field.SetValue(o[o.Count - 2], o[o.Count - 1]));
m_ValueBuilder.Add(o => o.RemoveAt(o.Count - 1));
}
}
}
public override VFXGizmo.IProperty<T> RegisterProperty<T>(string member)
{
object result;
if (m_PropertyCache.TryGetValue(member, out result))
{
if (result is VFXGizmo.IProperty<T> )
return result as VFXGizmo.IProperty<T>;
else
return VFXGizmoUtility.NullProperty<T>.defaultProperty;
}
var controller = GetMemberController(member);
if (controller != null && controller.portType == typeof(T))
{
bool readOnly = false;
var slot = controller.model;
if (slot.HasLink(true))
readOnly = true;
else
{
slot = slot.GetParent();
while (slot != null)
{
if (slot.HasLink(false))
{
readOnly = true;
break;
}
slot = slot.GetParent();
}
}
return new VFXGizmoUtility.Property<T>(controller, !readOnly);
}
return VFXGizmoUtility.NullProperty<T>.defaultProperty;
}
VFXDataAnchorController GetMemberController(string memberPath)
{
if (string.IsNullOrEmpty(memberPath))
{
return m_Controller;
}
return GetSubMemberController(memberPath, m_Controller.model);
}
VFXDataAnchorController GetSubMemberController(string memberPath, VFXSlot slot)
{
int index = memberPath.IndexOf(separator);
if (index == -1)
{
VFXSlot subSlot = slot.children.FirstOrDefault(t => t.name == memberPath);
if (subSlot != null)
{
var subController = m_Controller.sourceNode.inputPorts.FirstOrDefault(t => t.model == subSlot);
return subController;
}
return null;
}
else
{
string memberName = memberPath.Substring(0, index);
VFXSlot subSlot = slot.children.FirstOrDefault(t => t.name == memberName);
if (subSlot != null)
{
return GetSubMemberController(memberPath.Substring(index + 1), subSlot);
}
return null;
}
}
}
}
| |
using System;
using System.Collections;
using System.Xml.Serialization;
using Utility;
namespace Data.Scans
{
/// <summary>
/// A scan is a set of scan points. Also holds a list of the settings used during its acquisition.
/// </summary>
[Serializable]
public class Scan : MarshalByRefObject
{
private ArrayList points = new ArrayList();
// this is a hashtable of the acquisitor settings used for this scan
public XmlSerializableHashtable ScanSettings = new XmlSerializableHashtable();
public Scan GetSortedScan()
{
double[] spa = ScanParameterArray;
ScanPoint[] pts = (ScanPoint[])points.ToArray(typeof(ScanPoint));
Array.Sort(spa, pts);
Scan ss = new Scan();
ss.points.AddRange(pts);
ss.ScanSettings = ScanSettings;
return ss;
}
public double MinimumScanParameter
{
get
{
return GetSortedScan().ScanParameterArray[0];
}
}
public double MaximumScanParameter
{
get
{
double[] spa = GetSortedScan().ScanParameterArray;
return spa[spa.Length - 1];
}
}
public double[] ScanParameterArray
{
get
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] = ((ScanPoint)points[i]).ScanParameter;
return temp;
}
}
public double[] GetAnalogArray(int index)
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] = (double)((ScanPoint)points[i]).Analogs[index];
return temp;
}
public double[] GetGPIBArray
{
get
{
double[] temp = new double[points.Count];
for (int i = 0; i < points.Count; i++) temp[i] = ((ScanPoint)points[i]).ScanParameter;
return temp;
}
}
public int AnalogChannelCount
{
get
{
return ((ScanPoint)points[0]).Analogs.Count;
}
}
public double[] GetTOFOnIntegralArray(int index, double startTime, double endTime)
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] =
(double)((ScanPoint)points[i]).IntegrateOn(index, startTime, endTime);
return temp;
}
public double[] GetTOFOnOverShotNoiseArray(int index, double startTime, double endTime)
{
double[] tempShot = new double[points.Count];
for (int i = 0; i < points.Count; i++)
{
tempShot[i] = (double)((ScanPoint)points[i]).FractionOfShotNoiseOn(index, startTime, endTime);
}
return tempShot;
}
public double[] GetTOFOnOverShotNoiseNormedArray(int[] index, double startTime0, double endTime0,double startTime1,double endTime1)
{
double[] tempShot = new double[points.Count];
for (int i = 0; i < points.Count; i++)
{
tempShot[i] = (double)((ScanPoint)points[i]).FractionOfShotNoiseNormedOn(index, startTime0, endTime0,startTime1,endTime1);
}
return tempShot;
}
public double[] GetTOFOffIntegralArray(int index, double startTime, double endTime)
{
double[] temp = new double[points.Count];
for (int i = 0 ; i < points.Count ; i++) temp[i] =
(double)((ScanPoint)points[i]).IntegrateOff(index, startTime, endTime);
return temp;
}
public double[] GetDifferenceIntegralArray(int index, double startTime, double endTime)
{
double[] temp = new double[points.Count];
double[] on = GetTOFOnIntegralArray(index, startTime, endTime);
double[] off = GetTOFOffIntegralArray(index, startTime, endTime);
for (int i = 0 ; i < points.Count ; i++) temp[i] = on[i] - off[i];
return temp;
}
public double[] GetMeanOnArray(int index)
{
double[] temp = new double[points.Count];
for (int i = 0; i < points.Count; i++) temp[i] =
(double)((ScanPoint)points[i]).MeanOn(index);
return temp;
}
public double[] GetMeanOffArray(int index)
{
double[] temp = new double[points.Count];
for (int i = 0; i < points.Count; i++) temp[i] =
(double)((ScanPoint)points[i]).MeanOff(index);
return temp;
}
public Shot GetGatedAverageOnShot(double lowGate, double highGate)
{
return GetAverageScanPoint(lowGate, highGate).AverageOnShot;
}
public Shot GetGatedAverageOffShot(double lowGate, double highGate)
{
return GetAverageScanPoint(lowGate, highGate).AverageOffShot;
}
private ScanPoint GetAverageScanPoint(double lowGate, double highGate)
{
Scan ss = GetSortedScan();
double scanParameterStart = ((ScanPoint)ss.points[0]).ScanParameter;
double scanParameterEnd = ((ScanPoint)ss.points[points.Count -1]).ScanParameter;
int low = (int)Math.Ceiling(ss.points.Count * (lowGate - scanParameterStart) /
(scanParameterEnd - scanParameterStart));
int high = (int)Math.Floor(ss.points.Count * (highGate - scanParameterStart) /
(scanParameterEnd - scanParameterStart));
if (low < 0) low = 0;
if (low >= ss.points.Count) low = ss.points.Count - 2;
if (high < low) high = low + 1;
if (high >= ss.points.Count) high = ss.points.Count -1;
ScanPoint temp = new ScanPoint();
for (int i = low ; i < high ; i++) temp += (ScanPoint)ss.points[i];
return temp /(high-low);
}
// Note: this only really makes sense for sorted scans!
public static Scan operator +(Scan s1, Scan s2)
{
if (s1.Points.Count == s2.Points.Count)
{
Scan temp = new Scan();
for (int i = 0 ; i < s1.Points.Count ; i++)
temp.Points.Add((ScanPoint)s1.Points[i] + (ScanPoint)s2.Points[i]);
temp.ScanSettings = s1.ScanSettings;
return temp;
}
else
{
if (s1.Points.Count == 0) return s2;
if (s2.Points.Count == 0) return s1;
return null;
}
}
public static Scan operator /(Scan s, int n)
{
Scan temp = new Scan();
foreach (ScanPoint sp in s.Points) temp.Points.Add(sp/n);
temp.ScanSettings = s.ScanSettings;
return temp;
}
public object GetSetting(string pluginType, string parameter)
{
return ScanSettings[pluginType + ":" + parameter];
}
[XmlArray]
[XmlArrayItem(Type = typeof(ScanPoint))]
public ArrayList Points
{
get { return points; }
}
}
}
| |
using System;
using System.Threading;
using System.IO;
using System.Collections.Generic;
namespace JinxNeuralNetwork
{
/// <summary>
/// Trains a NeuralNetwork through QLearning(action-reward system)
/// </summary>
public class NeuralNetworkQLearning
{
/// <summary>
///
/// </summary>
/// <param name="actionId"></param>
public delegate void OnLearningReplayAction(int actionId);
/// <summary>
///
/// </summary>
public OnLearningReplayAction onReplayAction = null;
private bool hasRecurring;
private NeuralNetwork neuralNetwork;
private string learningSessionsFile = null;
private Stream learningSessionStream = null;
private int currentSession = 0;
private bool beganSession = false;
private List<int> sessions = new List<int>();
private NeuralNetworkContext[] stackedRuntimeContext;
private NeuralNetworkFullContext[] stackedFullContext;
private NeuralNetworkPropagationState[] stackedDerivativeMemory;
private NeuralNetworkDerivativeMemory derivatives = new NeuralNetworkDerivativeMemory();
private int maxUnrollLength;
/// <summary>
/// Create new NeuralNetworkQLearning system.
/// </summary>
/// <param name="nn">NeuralNetwork to train.</param>
/// <param name="inputDat">Input data.</param>
/// <param name="targetDat">Target data.</param>
public NeuralNetworkQLearning(NeuralNetwork nn, int maxUnrollLen, string sessionsFileName)
{
neuralNetwork = nn;
learningSessionsFile = sessionsFileName;
maxUnrollLength = maxUnrollLen;
if (maxUnrollLength < 1) maxUnrollLength = 1;
//check for recurring layer, if need to stack and unroll
for (int i = 0; i < nn.hiddenLayers.Length; i++)
{
if (nn.hiddenLayers[i].recurring)
{
hasRecurring = true;
break;
}
}
derivatives.Setup(nn);
if (!hasRecurring)
{
maxUnrollLength = 1;
}
stackedRuntimeContext = new NeuralNetworkContext[maxUnrollLength];
stackedFullContext = new NeuralNetworkFullContext[maxUnrollLength];
stackedDerivativeMemory = new NeuralNetworkPropagationState[maxUnrollLength];
for (int i = 0; i < stackedRuntimeContext.Length; i++)
{
stackedRuntimeContext[i] = new NeuralNetworkContext();
stackedRuntimeContext[i].Setup(nn);
stackedFullContext[i] = new NeuralNetworkFullContext();
stackedFullContext[i].Setup(nn);
stackedDerivativeMemory[i] = new NeuralNetworkPropagationState();
stackedDerivativeMemory[i].Setup(nn, stackedRuntimeContext[i], stackedFullContext[i], derivatives);
}
/*
if (hasRecurring)
{
recurringMemoryState = new float[nn.hiddenLayers.Length][];
for (int i = 0; i < nn.hiddenLayers.Length; i++)
{
if (nn.hiddenLayers[i].recurring)
{
recurringMemoryState[i] = new float[nn.hiddenLayers[i].numberOfNeurons];
}
}
}*/
}
~NeuralNetworkQLearning() {
if (learningSessionStream != null && (learningSessionStream.CanRead || learningSessionStream.CanWrite))
learningSessionStream.Close ();
}
/// <summary>
/// Begins new learning session.
/// </summary>
public void Start()
{
learningSessionStream = File.OpenWrite (learningSessionsFile);
currentSession = 0;
SaveRecurringMemoryState ();
}
/// <summary>
/// Restarts session.
/// </summary>
public void RestartSession() {
ClearSession ();
currentSession = 0;
SaveRecurringMemoryState ();
}
/// <summary>
/// Clears current session.
/// </summary>
public void ClearSession() {
if (beganSession) {
long recurrMemorySz = 0;
float[][] hm = stackedRuntimeContext [0].hiddenRecurringData;
for (int i = 0; i < hm.Length; i++) {
if (hm [i] != null) {
recurrMemorySz += hm [i].Length * 4;
}
}
long len = learningSessionStream.Length - (currentSession * (long)(4 + neuralNetwork.inputLayer.numberOfNeurons * 4) + recurrMemorySz);
learningSessionStream.Seek(len-1, SeekOrigin.Begin);
learningSessionStream.SetLength (len);
beganSession = false;
}
}
/// <summary>
/// Clears all saved learning sessions, you must manually call RestartSession after this.
/// </summary>
public void ClearAllSessions() {
File.WriteAllBytes (learningSessionsFile, new byte[0]);
}
/// <summary>
/// Save QLearning learning session state to stream.
/// </summary>
/// <param name="s">S.</param>
public void Save(Stream s) {
Utils.IntToStream (sessions.Count, s);
for (int i = 0; i < sessions.Count; i++)
Utils.IntToStream (sessions [i], s);
}
/// <summary>
/// Load QLearning learning session state from stream.
/// </summary>
/// <param name="s">S.</param>
public void Load(Stream s) {
sessions.Clear ();
int nsession = Utils.IntFromStream (s);
for (int i = 0; i < nsession; i++)
sessions.Add(Utils.IntFromStream (s));
}
//copies c1 recurring data to c2
private void CopyRecurringState(NeuralNetworkContext c1, NeuralNetworkContext c2)
{
int i = c1.hiddenRecurringData.Length;
while (i-- > 0)
{
if (c1.hiddenRecurringData[i] == null) continue;
Array.Copy(c1.hiddenRecurringData[i], c2.hiddenRecurringData[i], c1.hiddenRecurringData[i].Length);
}
}
/// <summary>
///
/// </summary>
private void SaveRecurringMemoryState()
{
float[][] hm = stackedRuntimeContext[0].hiddenRecurringData;
for (int i = 0; i < hm.Length; i++)
{
if (hm[i] != null)
{
Utils.FloatArrayToStream (hm [i], learningSessionStream);
}
}
beganSession = true;
}
/// <summary>
///
/// </summary>
/// <returns>ID of selected action neuron.</returns>
public int Execute()
{
NeuralNetworkContext ctx = stackedRuntimeContext[0];
neuralNetwork.Execute(ctx);
//randomly select action from output result
Utils.Normalize(ctx.outputData);
int action = Utils.RandomChoice(ctx.outputData);
//save action to session
Utils.IntToStream (action, learningSessionStream);
Utils.FloatArrayToStream (ctx.inputData, learningSessionStream);
currentSession++;
return action;
}
/// <summary>
/// Finishes session with reward and starts another new session. Call 'Learn' to iterate through sessions training.
/// </summary>
/// <param name="amount"></param>
public void Reward(float reward)
{
Utils.FloatToStream (reward, learningSessionStream);
sessions.Add (currentSession);
RestartSession ();
}
/// <summary>
/// Learn from rewarded sessions with specified 'learningRate', 'iter' times.
/// </summary>
/// <param name="learningRate">Learning rate.</param>
public void Learn(float learningRate, int iter) {
//clear current session from stream and end session stream
ClearSession ();
learningSessionStream.Close ();
//begin reading session stream
learningSessionStream = File.OpenRead (learningSessionsFile);
float[] tb = stackedRuntimeContext [0].outputData;
float[][] hm = stackedRuntimeContext[0].hiddenRecurringData;
QLearningContext[] qctx = new QLearningContext[maxUnrollLength];
for (int i = 0; i < maxUnrollLength; i++) {
qctx[i] = new QLearningContext (0, new float[neuralNetwork.inputLayer.numberOfNeurons]);
}
for (int j = 0; j < iter; j++) {
learningSessionStream.Position = 0;
//training
for (int s = 0; s < sessions.Count; s++) {
//reset derivatives/context memory
derivatives.Reset ();
for (int i = 0; i < maxUnrollLength; i++) {
stackedRuntimeContext [i].Reset (true);
stackedDerivativeMemory [i].Reset ();
}
//initial memory state
for (int i = 0; i < hm.Length; i++)
{
if (hm[i] != null)
{
Utils.FloatArrayFromStream (hm [i], learningSessionStream);
}
}
int alen = sessions[s],
unrollCount = 0;
//seek ahead to load reward then back
long lpos = learningSessionStream.Position;
learningSessionStream.Seek (lpos + alen*(4+neuralNetwork.inputLayer.numberOfNeurons*4), SeekOrigin.Begin);
float rewardAmount = Utils.FloatFromStream (learningSessionStream)*learningRate;
learningSessionStream.Seek (lpos, SeekOrigin.Begin);
for (int i = 0; i < alen; i++) {
qctx[unrollCount].action = Utils.IntFromStream (learningSessionStream);
Utils.FloatArrayFromStream (qctx[unrollCount].input, learningSessionStream);
Array.Copy (qctx[unrollCount].input, stackedRuntimeContext [unrollCount].inputData, qctx[unrollCount].input.Length);
neuralNetwork.Execute_FullContext (stackedRuntimeContext [unrollCount], stackedFullContext [unrollCount]);
if (onReplayAction != null)
onReplayAction (qctx[unrollCount].action);
unrollCount++;
if (unrollCount >= maxUnrollLength || i + 1 >= alen) {
//back propagate through stacked
int tdatIndex = i;
while (unrollCount-- > 0) {
tb [qctx[unrollCount].action] = 1.0f;
neuralNetwork.ExecuteBackwards (tb, stackedRuntimeContext [unrollCount], stackedFullContext [unrollCount], stackedDerivativeMemory [unrollCount], NeuralNetworkTrainer.LOSS_TYPE_AVERAGE, -1);
tb [qctx[unrollCount].action] = 0.0f;
tdatIndex--;
}
//learn
NeuralNetworkAdaGradMemory.ApplyNoMemory (stackedDerivativeMemory [0], stackedDerivativeMemory[0].weights, stackedDerivativeMemory[0].biases, stackedDerivativeMemory[0].recurrWeights, rewardAmount);
derivatives.Reset ();
unrollCount = 0;
if (i + 1 >= alen) {
//not enough room for another full length propagation
} else {
//copy recurring state over
CopyRecurringState (stackedRuntimeContext [maxUnrollLength - 1], stackedRuntimeContext [0]);
}
} else {
//copy recurring state into next
CopyRecurringState (stackedRuntimeContext [unrollCount - 1], stackedRuntimeContext [unrollCount]);
}
}
}
}
}
/// <summary>
/// Get neural network runtime context.
/// </summary>
/// <returns></returns>
public NeuralNetworkContext GetNeuralNetworkContext()
{
return stackedRuntimeContext[0];
}
}
public class QLearningContext
{
public int action;
public float[] input;
public QLearningContext(int a, float[] i)
{
action = a;
input = new float[i.Length];
Array.Copy(i, input, i.Length);
}
}
}
| |
/*
Copyright (c) 2013 Mitch Thompson
Extended by Harald Lurger (2013) (Process to Sprites)
Standard MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
public static class TexturePackerImport{
[MenuItem("Assets/TexturePacker/Process to Sprites")]
static void ProcessToSprite(){
TextAsset txt = (TextAsset)Selection.activeObject;
string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(txt));
TexturePacker.MetaData meta = TexturePacker.GetMetaData(txt.text);
List<SpriteMetaData> sprites = TexturePacker.ProcessToSprites(txt.text);
string path = rootPath + "/" + meta.image;
sprites = MaintainSpriteOrder(path, sprites, meta.image);
TextureImporter texImp = AssetImporter.GetAtPath(path) as TextureImporter;
texImp.spritesheet = sprites.ToArray();
texImp.textureType = TextureImporterType.Sprite;
texImp.spriteImportMode = SpriteImportMode.Multiple;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate );
}
static List<SpriteMetaData> MaintainSpriteOrder(string path, List<SpriteMetaData> sprites, string imageName)
{
sprites = new List<SpriteMetaData>(sprites); // Work on a copy, method shouldn't have side-effects
List<SpriteMetaData> orderedSprites = new List<SpriteMetaData>();
Object[] existing = AssetDatabase.LoadAllAssetsAtPath(path);
for (int i = 0; i < existing.Length; ++i)
{
Sprite existingSprite = existing[i] as Sprite;
if (null != existingSprite)
{
int pickedIndex = FindSpriteFromListByName(sprites, existingSprite.name);
if (-1 != pickedIndex)
{
orderedSprites.Add(sprites[pickedIndex]);
sprites.RemoveAt(pickedIndex);
}
else
{
if (existingSprite.name != imageName) // Make sure not to add the spritesheet image itself
{
SpriteMetaData placeholder = new SpriteMetaData();
placeholder.name = existingSprite.name;
orderedSprites.Add(placeholder);
Debug.LogWarning(existingSprite.name + " removed from spritesheet. Adding blank placeholder.");
}
}
}
else
{
if (null == existing[i] as Texture2D)
Debug.LogWarning("Unexpected type " + existing[i]);
}
}
orderedSprites.AddRange(sprites);
return orderedSprites;
}
static int FindSpriteFromListByName(List<SpriteMetaData> spriteList, string name)
{
int index = -1;
for (int i = 0; i < spriteList.Count; ++i)
{
if (spriteList[i].name == name)
{
index = i;
break;
}
}
return index;
}
[MenuItem("Assets/TexturePacker/Process to Meshes")]
static Mesh[] ProcessToMeshes(){
TextAsset txt = (TextAsset)Selection.activeObject;
Quaternion rotation = Quaternion.identity;
string pref = EditorPrefs.GetString("TexturePackerImporterFacing", "back");
switch(pref){
case "back":
rotation = Quaternion.identity;
break;
case "forward":
rotation = Quaternion.LookRotation(Vector3.back);
break;
case "up":
rotation = Quaternion.LookRotation(Vector3.down, Vector3.forward);
break;
case "down":
rotation = Quaternion.LookRotation(Vector3.up, Vector3.back);
break;
case "right":
rotation = Quaternion.LookRotation(Vector3.left);
break;
case "left":
rotation = Quaternion.LookRotation(Vector3.right);
break;
}
Mesh[] meshes = TexturePacker.ProcessToMeshes(txt.text, rotation);
string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(txt));
Directory.CreateDirectory(Application.dataPath + "/" + rootPath.Substring(7, rootPath.Length-7) + "/Meshes");
Mesh[] returnMeshes = new Mesh[meshes.Length];
int i = 0;
foreach(Mesh m in meshes){
string assetPath = rootPath + "/Meshes/" + Path.GetFileNameWithoutExtension(m.name) + ".asset";
Mesh existingMesh = (Mesh)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Mesh));
if(existingMesh == null){
AssetDatabase.CreateAsset(m, assetPath);
existingMesh = (Mesh)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Mesh));
}
else{
existingMesh.triangles = new int[0];
existingMesh.colors32 = new Color32[0];
existingMesh.uv = new Vector2[0];
existingMesh.vertices = m.vertices;
existingMesh.uv = m.uv;
existingMesh.colors32 = m.colors32;
existingMesh.triangles = m.triangles;
existingMesh.RecalculateNormals();
existingMesh.RecalculateBounds();
EditorUtility.SetDirty(existingMesh);
Mesh.DestroyImmediate(m);
}
returnMeshes[i] = existingMesh;
i++;
}
return returnMeshes;
}
[MenuItem("Assets/TexturePacker/Process to Prefabs")]
static void ProcessToPrefabs(){
Mesh[] meshes = ProcessToMeshes();
TextAsset txt = (TextAsset)Selection.activeObject;
string rootPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(txt));
string prefabPath = rootPath.Substring(7, rootPath.Length-7) + "/Prefabs";
Directory.CreateDirectory(Application.dataPath + "/" + prefabPath);
prefabPath = "Assets/" + prefabPath;
//make material
TexturePacker.MetaData meta = TexturePacker.GetMetaData(txt.text);
string matPath = rootPath + "/" + (Path.GetFileNameWithoutExtension(meta.image) + ".mat");
string texturePath = rootPath + "/" + meta.image;
Material mat = (Material)AssetDatabase.LoadAssetAtPath(matPath, typeof(Material));
if(mat == null){
mat = new Material(Shader.Find("Sprites/Transparent Unlit"));
Texture2D tex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D));
if(tex == null){
EditorUtility.DisplayDialog("Error!", "Texture " + meta.image + " not found!", "Ok");
}
mat.mainTexture = tex;
AssetDatabase.CreateAsset(mat, matPath);
}
AssetDatabase.Refresh();
for(int i = 0; i < meshes.Length; i++){
string prefabFilePath = prefabPath + "/" + meshes[i].name + ".prefab";
bool createdNewPrefab = false;
Object prefab = AssetDatabase.LoadAssetAtPath(prefabFilePath, typeof(Object));
if(prefab == null){
prefab = PrefabUtility.CreateEmptyPrefab(prefabFilePath);
createdNewPrefab = true;
}
if(createdNewPrefab){
GameObject go = new GameObject(meshes[i].name, typeof(MeshRenderer), typeof(MeshFilter));
go.GetComponent<MeshFilter>().sharedMesh = meshes[i];
go.renderer.sharedMaterial = mat;
PrefabUtility.ReplacePrefab(go, prefab, ReplacePrefabOptions.ConnectToPrefab);
GameObject.DestroyImmediate(go);
}
else{
GameObject pgo = (GameObject)prefab;
pgo.renderer.sharedMaterial = mat;
pgo.GetComponent<MeshFilter>().sharedMesh = meshes[i];
EditorUtility.SetDirty(pgo);
}
}
}
//Validators
[MenuItem("Assets/TexturePacker/Process to Prefabs", true)]
[MenuItem("Assets/TexturePacker/Process to Meshes", true)]
[MenuItem("Assets/TexturePacker/Process to Sprites", true)]
static bool ValidateProcessTexturePacker(){
Object o = Selection.activeObject;
if(o == null)
return false;
if(o.GetType() == typeof(TextAsset)){
return (((TextAsset)o).text.hashtableFromJson()).IsTexturePackerTable();
}
return false;
}
//Attach 90 degree "Shadow" meshes
[MenuItem("Assets/TexturePacker/Attach Shadow Mesh")]
static void AttachShadowMesh(){
List<Mesh> meshes = new List<Mesh>();
foreach(Object o in Selection.objects){
if(o is Mesh) meshes.Add(o as Mesh);
}
foreach(Mesh m in meshes){
Vector3[] verts = new Vector3[m.vertexCount*2];
Vector2[] uvs = new Vector2[m.vertexCount*2];
Color32[] colors = new Color32[m.vertexCount*2];
int[] triangles = new int[m.triangles.Length * 2];
System.Array.Copy(m.vertices, 0, verts, m.vertexCount, m.vertexCount);
System.Array.Copy(m.uv, 0, uvs, m.vertexCount, m.vertexCount);
System.Array.Copy(m.colors32, 0, colors, m.vertexCount, m.vertexCount);
System.Array.Copy(m.triangles, 0, triangles, m.triangles.Length, m.triangles.Length);
for(int i = 0; i < m.vertexCount; i++){
verts[i].x = verts[i+m.vertexCount].x;
verts[i].y = verts[i+m.vertexCount].z;
verts[i].z = verts[i+m.vertexCount].y;
uvs[i] = uvs[i+m.vertexCount];
colors[i] = new Color32(0,0,0,64);
}
for(int i = 0; i < m.triangles.Length; i++){
triangles[i] = triangles[i + m.triangles.Length];
triangles[i + m.triangles.Length] += m.vertexCount;
}
m.vertices = verts;
m.uv = uvs;
m.colors32 = colors;
m.triangles = triangles;
m.RecalculateNormals();
m.RecalculateBounds();
EditorUtility.SetDirty(m);
}
}
//Validators
[MenuItem("Assets/TexturePacker/Attach Shadow Mesh", true)]
static bool ValidateAttachShadowMesh(){
Object[] objs = Selection.objects;
foreach(Object o in objs){
if(!(o is Mesh)){
return false;
}
}
return true;
}
//Options
[MenuItem("Assets/TexturePacker/Facing/Back")]
static void SetFacingBack(){ EditorPrefs.SetString("TexturePackerImporterFacing", "back"); }
[MenuItem("Assets/TexturePacker/Facing/Forward")]
static void SetFacingForward(){ EditorPrefs.SetString("TexturePackerImporterFacing", "forward"); }
[MenuItem("Assets/TexturePacker/Facing/Up")]
static void SetFacingUp(){ EditorPrefs.SetString("TexturePackerImporterFacing", "up"); }
[MenuItem("Assets/TexturePacker/Facing/Down")]
static void SetFacingDown(){ EditorPrefs.SetString("TexturePackerImporterFacing", "down"); }
[MenuItem("Assets/TexturePacker/Facing/Right")]
static void SetFacingRight(){ EditorPrefs.SetString("TexturePackerImporterFacing", "right"); }
[MenuItem("Assets/TexturePacker/Facing/Left")]
static void SetFacingLeft(){ EditorPrefs.SetString("TexturePackerImporterFacing", "left"); }
}
| |
using System.Text.RegularExpressions;
namespace ArgsReading;
/// <summary>
/// Helps process command-line arguments.
/// </summary>
/// <remarks>To use this class, construct an <c>ArgsReader</c> with the command-line arguments from <c>Main</c>,
/// read the supported options one at a time with <see cref="ReadFlag" /> and <see cref="ReadOption"/>,
/// read any normal arguments with <see cref="ReadArgument"/>, and finally call <see cref="VerifyComplete"/>,
/// which throws an <see cref="ArgsReaderException"/> if any unsupported options or arguments haven't been read.</remarks>
public sealed class ArgsReader
{
/// <summary>
/// Creates a reader for the specified command-line arguments.
/// </summary>
/// <param name="args">The command-line arguments from <c>Main</c>.</param>
/// <exception cref="ArgumentNullException"><c>args</c> is <c>null</c>.</exception>
public ArgsReader(IEnumerable<string> args)
{
m_args = (args ?? throw new ArgumentNullException(nameof(args))).ToList();
}
/// <summary>
/// True if short options (e.g. <c>-h</c>) should ignore case. (Default false.)
/// </summary>
public bool ShortOptionIgnoreCase { get; set; }
/// <summary>
/// True if long options (e.g. <c>--help</c>) should ignore case. (Default false.)
/// </summary>
public bool LongOptionIgnoreCase { get; set; }
/// <summary>
/// True if long options (e.g. <c>--dry-run</c>) should ignore "kebab case", i.e. allow <c>--dryrun</c>. (Default false.)
/// </summary>
public bool LongOptionIgnoreKebabCase { get; set; }
/// <summary>
/// True if <c>--</c> is ignored and all following arguments are not read as options. (Default false.)
/// </summary>
public bool NoOptionsAfterDoubleDash { get; set; }
/// <summary>
/// Reads the specified flag, returning true if it is found.
/// </summary>
/// <param name="name">The name of the specified flag.</param>
/// <returns>True if the specified flag was found on the command line.</returns>
/// <remarks><para>If the flag is found, the method returns <c>true</c> and the flag is
/// removed. If <c>ReadFlag</c> is called again with the same name, it will return <c>false</c>,
/// unless the same flag appears twice on the command line.</para>
/// <para>To support multiple names for the same flag, use a <c>|</c> to separate them,
/// e.g. use <c>help|h|?</c> to support three different names for a help flag.</para>
/// <para>Single-character names use a single hyphen, e.g. <c>-h</c>. Longer names
/// use a double hyphen, e.g. <c>--help</c>.</para></remarks>
/// <exception cref="ArgumentNullException"><c>name</c> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">One of the names is empty.</exception>
public bool ReadFlag(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException("Flag name must not be empty.", nameof(name));
var names = name.Split('|');
if (names.Length > 1)
return names.Any(ReadFlag);
var index = FindOptionArgumentIndex(name);
if (index == -1)
return false;
m_args.RemoveAt(index);
return true;
}
/// <summary>
/// Reads the value of the specified option, if any.
/// </summary>
/// <param name="name">The name of the specified option.</param>
/// <returns>The specified option if it was found on the command line; <c>null</c> otherwise.</returns>
/// <remarks><para>If the option is found, the method returns the command-line argument
/// after the option and both arguments are removed. If <c>ReadOption</c> is called again with the
/// same name, it will return <c>null</c>, unless the same option appears twice on the command line.</para>
/// <para>To support multiple names for the same option, use a vertical bar (<c>|</c>) to separate them,
/// e.g. use <c>n|name</c> to support two different names for a module option.</para>
/// <para>Single-character names use a single hyphen, e.g. <c>-n example</c>. Longer names use a
/// double hyphen, e.g. <c>--name example</c>.</para></remarks>
/// <exception cref="ArgumentNullException"><c>name</c> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">One of the names is empty.</exception>
/// <exception cref="ArgsReaderException">The argument that must follow the option is missing.</exception>
public string? ReadOption(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException("Option name must not be empty.", nameof(name));
var names = name.Split('|');
if (names.Length > 1)
return names.Select(ReadOption).FirstOrDefault(x => x != null);
var index = FindOptionArgumentIndex(name);
if (index == -1)
return null;
var value = index + 1 < m_args.Count ? m_args[index + 1] : null;
if (value == null || IsOption(value))
throw new ArgsReaderException($"Missing value after '{RenderOption(name)}'.");
m_args.RemoveAt(index);
m_args.RemoveAt(index);
return value;
}
/// <summary>
/// Reads the next non-option argument.
/// </summary>
/// <returns>The next non-option argument, or null if none remain.</returns>
/// <remarks><para>If the next argument is an option, this method throws an exception.
/// If options can appear before normal arguments, be sure to read all options before reading
/// any normal arguments.</para></remarks>
/// <exception cref="ArgsReaderException">The next argument is an option.</exception>
public string? ReadArgument()
{
if (m_args.Count == 0)
return null;
var value = m_args[0];
if (NoOptionsAfterDoubleDash && value == "--")
{
m_args.RemoveAt(0);
m_noMoreOptions = true;
return ReadArgument();
}
if (!m_noMoreOptions && IsOption(value))
throw new ArgsReaderException($"Unexpected option '{value}'.");
m_args.RemoveAt(0);
return value;
}
/// <summary>
/// Reads any remaining non-option arguments.
/// </summary>
/// <returns>The remaining non-option arguments, if any.</returns>
/// <remarks><para>If any remaining arguments are options, this method throws an exception.
/// If options can appear before normal arguments, be sure to read all options before reading
/// any normal arguments.</para></remarks>
/// <exception cref="ArgsReaderException">A remaining argument is an option.</exception>
public IReadOnlyList<string> ReadArguments()
{
var arguments = new List<string>();
while (true)
{
var argument = ReadArgument();
if (argument == null)
return arguments;
arguments.Add(argument);
}
}
/// <summary>
/// Confirms that all arguments were processed.
/// </summary>
/// <exception cref="ArgsReaderException">A command-line argument was not read.</exception>
public void VerifyComplete()
{
if (m_args.Count != 0)
throw new ArgsReaderException($"Unexpected {(IsOption(m_args[0]) ? "option" : "argument")} '{m_args[0]}'.");
}
private static bool IsOption(string value) => value.Length >= 2 && value[0] == '-' && value != "--";
private static string RenderOption(string name) => name.Length == 1 ? $"-{name}" : $"--{name}";
private bool IsOptionArgument(string optionName, string argument)
{
var renderedOption = RenderOption(optionName);
if (optionName.Length == 1)
{
return string.Equals(argument, renderedOption, ShortOptionIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
else
{
if (LongOptionIgnoreKebabCase)
{
argument = Regex.Replace(argument, @"\b-\b", "");
renderedOption = Regex.Replace(renderedOption, @"\b-\b", "");
}
return string.Equals(argument, renderedOption, LongOptionIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
}
private int FindOptionArgumentIndex(string optionName)
{
for (var index = 0; index < m_args.Count; index++)
{
var arg = m_args[index];
if (NoOptionsAfterDoubleDash && arg == "--")
break;
if (IsOptionArgument(optionName, arg))
return index;
}
return -1;
}
private readonly List<string> m_args;
private bool m_noMoreOptions;
}
| |
/*
The MIT License (MIT)
Copyright (c) 2015 Huw Bowles & Daniel Zimmermann
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 UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class AdvectedScalesFlatland : AdvectedScales
{
public float[] scales_norm;
Vector3 lastPos;
Vector3 lastForward;
Vector3 lastRight;
float motionMeasure = 0.0f;
void Start()
{
scales_norm = new float[AdvectedScalesSettings.instance.scaleCount];
// init scales to something interesting
for( int i = 0; i < AdvectedScalesSettings.instance.scaleCount; i++ )
{
float fixedZ = Mathf.Lerp( Mathf.Cos(CloudsBase.halfFov_horiz_rad), 1.0f, AdvectedScalesSettings.instance.fixedZProp ) / Mathf.Sin(getTheta(i));
float fixedR = (Mathf.Sin(8.0f*i/(float)AdvectedScalesSettings.instance.scaleCount)*AdvectedScalesSettings.instance.fixedRNoise + 1.0f);
scales_norm[i] = Mathf.Lerp( fixedZ, fixedR, AdvectedScalesSettings.instance.reInitCurvature );
}
lastPos = transform.position;
lastForward = transform.forward;
lastRight = transform.right;
}
void Update()
{
if( AdvectedScalesSettings.instance.scaleCount != scales_norm.Length || AdvectedScalesSettings.instance.reInitScales )
Start();
float dt = Mathf.Max( Time.deltaTime, 0.033f );
float vel = (transform.position - lastPos).magnitude / dt;
if( AdvectedScalesSettings.instance.clearOnTeleport && vel > 100.0f )
{
ClearAfterTeleport();
return;
}
// compute motion measures
// compute rotation of camera (heading only)
float rotRad = Vector3.Angle( transform.forward, lastForward ) * Mathf.Sign( Vector3.Cross( lastForward, transform.forward ).y ) * Mathf.Deg2Rad;
// compute motion measure
float motionMeasureRot = Mathf.Clamp01(Mathf.Abs(AdvectedScalesSettings.instance.motionMeasCoeffRot * rotRad/dt));
float motionMeasureTrans = Mathf.Clamp01(Mathf.Abs(AdvectedScalesSettings.instance.motionMeasCoeffStrafe * vel));
motionMeasure = Mathf.Max( motionMeasureRot, motionMeasureTrans );
if (!AdvectedScalesSettings.instance.useMotionMeas)
motionMeasure = 1;
// working data
float[] scales_new_norm = new float[AdvectedScalesSettings.instance.scaleCount];
////////////////////////////////
// advection
if( AdvectedScalesSettings.instance.doAdvection )
{
bool oneIn = false;
for( int i = 0; i < AdvectedScalesSettings.instance.scaleCount; i++ )
{
float theta1 = getTheta(i);
float theta0 = FindTheta0( theta1 );
float r1 = ComputeR1( theta0 );
scales_new_norm[i] = r1 / m_radius;
// detect case where no samples were taken from the old slice
oneIn = oneIn || thetaWithinView(theta0);
}
// if no samples taken, call this a teleport, reinit scales
if( !oneIn && !AdvectedScalesSettings.instance.debugFreezeAdvection )
{
ClearAfterTeleport();
}
// now clamp the scales
if( AdvectedScalesSettings.instance.clampScaleValues )
{
// clamp the values
for( int i = 0; i < AdvectedScalesSettings.instance.scaleCount; i++ )
{
// min: an inverted circle, i.e. concave instead of convex. this allows obiting
// max: the fixed z line at the highest point of the circle. this allows strafing after rotating without aliasing
scales_new_norm[i] = Mathf.Clamp( scales_new_norm[i], 0.9f*(1.0f - (Mathf.Sin(getTheta(i))-Mathf.Cos(CloudsBase.halfFov_horiz_rad))), 1.0f/Mathf.Sin(getTheta(i)) );
}
}
// limit/relax the gradients
if( AdvectedScalesSettings.instance.limitGradient )
{
RelaxGradients( scales_new_norm );
}
// all done - store the new r values
if( !AdvectedScalesSettings.instance.debugFreezeAdvection )
{
// normal path - store the scales then debug draw
for( int i = 0; i < AdvectedScalesSettings.instance.scaleCount; i++ )
{
scales_norm[i] = scales_new_norm[i];
}
Draw();
}
else
{
// for freezing advection, apply the scales temporarily and draw them, but then revert them
float[] bkp = new float[scales_norm.Length];
for( int i = 0; i < bkp.Length; i++ )
bkp[i] = scales_norm[i];
for( int i = 0; i < AdvectedScalesSettings.instance.scaleCount; i++ )
scales_norm[i] = scales_new_norm[i];
Draw();
for( int i = 0; i < AdvectedScalesSettings.instance.scaleCount; i++ )
scales_norm[i] = bkp[i];
}
}
if( !AdvectedScalesSettings.instance.debugFreezeAdvection )
{
lastPos = transform.position;
lastForward = transform.forward;
lastRight = transform.right;
}
}
// gradient relaxation
// the following is complex and I don't know how much of this could maybe be done
// in a single pass or otherwise simplified. more experimentation is needed.
//
// the two scales at the sides of the frustum are not changed by this process.
// there are two stages - the first is an inside-out scheme which starts from
// the middle and moves outwards. the second is an outside-in scheme which moves
// towards the middle from the side.
void RelaxGradients( float[] r_new )
{
// INSIDE OUT
for( int i = AdvectedScalesSettings.instance.scaleCount/2; i < AdvectedScalesSettings.instance.scaleCount-1; i++ )
{
RelaxGradient( i, i-1, r_new );
}
for( int i = AdvectedScalesSettings.instance.scaleCount/2; i >= 1; i-- )
{
RelaxGradient( i, i+1, r_new );
}
// OUTSIDE IN
for( int i = 1; i <= AdvectedScalesSettings.instance.scaleCount/2; i++ )
{
RelaxGradient( i, i-1, r_new );
}
for( int i = AdvectedScalesSettings.instance.scaleCount-2; i >= AdvectedScalesSettings.instance.scaleCount/2; i-- )
{
RelaxGradient( i, i+1, r_new );
}
}
void RelaxGradient( int i, int i1, float[] scales_new_norm )
{
float dx = m_radius*scales_new_norm[i]*Mathf.Cos(getTheta(i)) - m_radius*scales_new_norm[i1]*Mathf.Cos(getTheta(i1));
if( Mathf.Abs(dx) < 0.0001f )
{
//Debug.LogError("dx too small! " + dx);
dx = Mathf.Sign(dx) * 0.0001f;
}
float meas = ( m_radius*scales_new_norm[i]*Mathf.Sin(getTheta(i)) - m_radius*scales_new_norm[i1]*Mathf.Sin(getTheta(i1)) ) / dx;
float measClamped = Mathf.Clamp( meas, -AdvectedScalesSettings.instance.maxGradient, AdvectedScalesSettings.instance.maxGradient );
float dt = Mathf.Max( Time.deltaTime, 1.0f/30.0f );
scales_new_norm[i] = Mathf.Lerp( m_radius*scales_new_norm[i], (measClamped*dx + m_radius*scales_new_norm[i1]*Mathf.Sin(getTheta(i1))) / Mathf.Sin(getTheta(i)), motionMeasure*AdvectedScalesSettings.instance.alphaGradient * 30.0f * dt ) / m_radius;
}
// reset scales to a fixed-z layout
void ClearAfterTeleport()
{
Debug.Log( "Teleport event, resetting layout" );
for( int i = 0; i < AdvectedScalesSettings.instance.scaleCount; i++ )
{
scales_norm[i] = Mathf.Cos( CloudsBase.halfFov_horiz_rad ) / Mathf.Sin( getTheta(i) );
}
lastPos = transform.position;
lastForward = transform.forward;
lastRight = transform.right;
}
public Vector3 View( float theta ) { float r = sampleR(theta); return r*Mathf.Cos(theta)*Vector3.right + r*Mathf.Sin(theta)*Vector3.forward; }
public float getTheta( int i ) { return 2.0f * CloudsBase.halfFov_horiz_rad * (float)i/(float)(AdvectedScalesSettings.instance.scaleCount-1) - CloudsBase.halfFov_horiz_rad + Mathf.PI/2.0f; }
bool thetaWithinView( float theta ) { return Mathf.Abs( theta - Mathf.PI/2.0f ) <= CloudsBase.halfFov_horiz_rad; }
Vector3 GetRay( float theta )
{
Quaternion q = Quaternion.AngleAxis( theta * Mathf.Rad2Deg, -Vector3.up );
return q * transform.right;
}
// note that theta for the center of the screen is PI/2. its really incovenient that angles are computed from the X axis, but
// the view direction is down the Z axis. we adopted this scheme as it made a bunch of the math simpler (i think!)
//
// Z axis (theta = PI/2)
// |
// frust. \ | /
// \ | /
// \ | / \ theta
// \|/ |
// ----------------------- X axis (theta = 0)
//
// for theta within the view, we sample the scale from the sample slice directly
// for theta outside the view, we compute a linear extension from the last point on
// the sample slice, to the corresponding scale at the side of the new camera position
// frustum. this is a linear approximation to how the sample slice needs to be extended
// when the frustum moves. if you rotate the camera fast then you will see the linear
// segments.
public float sampleR( float theta )
{
// move theta from [pi/2 - halfFov, pi/2 + halfFov] to [0,1]
float s = (theta - (Mathf.PI/2.0f-CloudsBase.halfFov_horiz_rad))/(2.0f*CloudsBase.halfFov_horiz_rad);
if( s < -0.001f || s > 1.001f )
{
// determine which side we're on. s<0 is right side as angles increase anti-clockwise
bool rightSide = s < 0f;
int lastIndex = rightSide ? 0 : AdvectedScalesSettings.instance.scaleCount-1;
// the start and end position of the extension
Vector3 pos_slice_end, pos_extrapolated;
pos_slice_end = lastPos
+ m_radius * scales_norm[lastIndex] * Mathf.Cos( getTheta(lastIndex) ) * lastRight
+ m_radius * scales_norm[lastIndex] * Mathf.Sin( getTheta(lastIndex) ) * lastForward;
float theta_edge = getTheta(lastIndex);
// we always nudge scale back to default val (scale return). to compute how much we're nudging
// the scale, we find our how far we're extending it, and we do this in radians.
Vector3 extrapolatedDir = transform.forward * Mathf.Sin(theta_edge) + transform.right * Mathf.Cos(theta_edge);
float angleSubtended = Vector3.Angle( pos_slice_end - transform.position, extrapolatedDir ) * Mathf.Deg2Rad;
float lerpAlpha = Mathf.Clamp01( motionMeasure*AdvectedScalesSettings.instance.alphaScaleReturnPerRadian*angleSubtended );
float r_extrap = Mathf.Lerp( sampleR(theta_edge), m_radius, lerpAlpha );
// now compute actual pos
pos_extrapolated = transform.position
+ transform.forward * r_extrap * Mathf.Sin(theta_edge)
+ transform.right * r_extrap * Mathf.Cos(theta_edge);
// now intersect ray with extension to find scale.
Vector3 rayExtent = lastPos
+ Mathf.Cos( theta ) * lastRight
+ Mathf.Sin( theta ) * lastForward;
Vector2 inter; bool found;
found = IntersectLineSegments(
new Vector2( pos_slice_end.x, pos_slice_end.z ),
new Vector2( pos_extrapolated.x, pos_extrapolated.z ),
new Vector2( lastPos.x, lastPos.z ),
new Vector2( rayExtent.x, rayExtent.z ),
out inter
);
// no unique intersection point - shouldnt happen
if( !found )
return sampleR(theta_edge);
// the intersection point between the ray for the query theta and the linear extension
Vector3 pt = new Vector3( inter.x, 0f, inter.y );
// make flatland
Vector3 offset = pt - lastPos;
offset.y = 0f;
return offset.magnitude;
}
s = Mathf.Clamp01( s );
// get from 0 to rCount-1
s *= (float)(AdvectedScalesSettings.instance.scaleCount-1);
int i0 = Mathf.FloorToInt(s);
int i1 = Mathf.CeilToInt(s);
float result = m_radius * Mathf.Lerp( scales_norm[i0], scales_norm[i1], Mathf.Repeat(s, 1.0f) );
return result;
}
public override float MiddleScaleValue {
get {
return sampleR(Mathf.PI/2.0f);
}
}
// this assumes that sampleR, lastPos, etc all return values from the PREVIOUS frame!
Vector3 ComputePos0_world( float theta )
{
float r0 = sampleR( theta );
return lastPos
+ r0 * Mathf.Cos(theta) * lastRight
+ r0 * Mathf.Sin(theta) * lastForward;
}
// solver. after the camera has moved, for a particular ray scale at angle theta1, we can find the angle to the corresponding
// sample before the camera move theta0 using an iterative computation - fixed point iteration.
// we previously published a paper titled Iterative Image Warping about using FPI for very similar use cases:
// http://www.disneyresearch.com/wp-content/uploads/Iterative-Image-Warping-Paper.pdf
float FindTheta0( float theta1 )
{
// just guess the source position is the current pos (basically, that the camera hasn't moved)
float theta0 = theta1;
// N iterations of FPI. compute where our guess would get us, and then update our guess with the error.
// we could monitor the iteration to ensure convergence etc but the advection seems to be really well behaved for 2 or more iterations.
for( int i = 0; i < AdvectedScalesSettings.instance.advectionIters; i++ )
{
theta0 += theta1 - ComputeTheta1(theta0);
}
return theta0;
}
// input: theta0 is angle before camera moved, which specifies a specific point on the sample slice P
// output: theta1 gives angle after camera moved to the sample slice point P
// this is the opposite to what we want - we will know the angle afterwards theta1 and want to compute
// the angle before theta0. however we invert this using FPI.
float ComputeTheta1( float theta0 )
{
Vector3 pos0 = ComputePos0_world( theta0 );
// end position, removing foward motion of cam, in local space
Vector3 pos1_local = transform.InverseTransformPoint( pos0 );
float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward);
if( !AdvectedScalesSettings.instance.advectionCompensatesForwardPin )
pos1_local += pullInCam * Vector3.forward;
else
pos1_local += pullInCam * pos1_local.normalized * sampleR(theta0) / sampleR(Mathf.PI/2.0f);
return Mathf.Atan2( pos1_local.z, pos1_local.x );
}
// for an angle theta0 specifying a point on the sample slice before the camera moves,
// we can compute a radius to this point by computing the distance to the new camera
// position. this completes the advection computation
float ComputeR1( float theta0 )
{
Vector3 pos0 = ComputePos0_world( theta0 );
// end position, removing forward motion of cam
Vector3 pos1 = transform.position;
float pullInCam = Vector3.Dot(transform.position-lastPos, transform.forward);
if( !AdvectedScalesSettings.instance.advectionCompensatesForwardPin )
pos1 -= pullInCam * transform.forward;
Vector3 offset = pos0 - pos1;
if( AdvectedScalesSettings.instance.advectionCompensatesForwardPin )
offset += pullInCam * offset.normalized * sampleR(theta0) / sampleR(Mathf.PI/2.0f);
return offset.magnitude;
}
void Draw()
{
Quaternion q;
for( int i = 1; i < AdvectedScalesSettings.instance.scaleCount; i++ )
{
float prevTheta = getTheta(i-1);
float thisTheta = getTheta(i);
prevTheta = Mathf.PI/2.0f + (prevTheta-Mathf.PI/2.0f) * 1.2f;
thisTheta = Mathf.PI/2.0f + (thisTheta-Mathf.PI/2.0f) * 1.2f;
q = Quaternion.AngleAxis( prevTheta * Mathf.Rad2Deg, -Vector3.up );
Vector3 prevRd = q * transform.right;
q = Quaternion.AngleAxis( thisTheta * Mathf.Rad2Deg, -Vector3.up );
Vector3 thisRd = q * transform.right;
float scale = AdvectedScalesSettings.instance.debugDrawScale * 1.0f;
float scalePrev = sampleR( prevTheta );
float scaleThis = sampleR( thisTheta );
float meas = scaleThis*Mathf.Sin(thisTheta) - scalePrev*Mathf.Sin(prevTheta);
float dx = Mathf.Cos(thisTheta)*scaleThis - Mathf.Cos(prevTheta)*scalePrev;
meas /= dx;
meas *= 5.0f;
Color newCol = Color.white * Mathf.Abs(meas);
newCol.a = 1; newCol.b = 0;
newCol = Color.white;
if( !thetaWithinView(thisTheta) || !thetaWithinView(prevTheta) )
newCol *= 0.5f;
Debug.DrawLine( transform.position + prevRd * (scalePrev /*-integrateForward*/) * scale, transform.position + thisRd * (scaleThis /*-integrateForward*/) * scale, newCol );
if( AdvectedScalesSettings.instance.debugDrawAdvectionGuides )
{
scale = AdvectedScalesSettings.instance.debugDrawScale * 1.0f;
Color fadeRed = Color.red;
fadeRed.a = 0.25f;
Debug.DrawLine( transform.position + prevRd * m_radius * scale, transform.position + thisRd * m_radius * scale, fadeRed );
scale = Mathf.Cos(CloudsBase.halfFov_horiz_rad) / Mathf.Sin(thisTheta);
Debug.DrawLine( transform.position + prevRd * m_radius * scale, transform.position + thisRd * m_radius * scale, fadeRed );
}
}
}
// loosely based on http://ideone.com/PnPJgb
// performance of this is very bad, lots of temp things being constructed. i should really just inline the code
// above but leaving like this for now.
static bool IntersectLineSegments(Vector2 A, Vector2 B, Vector2 C, Vector2 D, out Vector2 intersect )
{
Vector2 r = B - A;
Vector2 s = D - C;
float rxs = r.x * s.y - r.y * s.x;
if( Mathf.Abs(rxs) <= Mathf.Epsilon )
{
// Lines are parallel or collinear - this is useless for us
intersect = Vector2.zero;
return false;
}
Vector2 CmA = C - A;
float CmAxs = CmA.x * s.y - CmA.y * s.x;
float t = CmAxs / rxs;
intersect = Vector2.Lerp( A, B, t );
return true;
}
}
| |
/*
* 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.Events
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Ignite events.
/// </summary>
internal sealed class Events : PlatformTarget, IEvents
{
/// <summary>
/// Opcodes.
/// </summary>
private enum Op
{
RemoteQuery = 1,
RemoteListen = 2,
StopRemoteListen = 3,
WaitForLocal = 4,
LocalQuery = 5,
// ReSharper disable once UnusedMember.Local
RecordLocal = 6,
EnableLocal = 8,
DisableLocal = 9,
GetEnabledEvents = 10
}
/** Map from user func to local wrapper, needed for invoke/unsubscribe. */
private readonly Dictionary<object, Dictionary<int, LocalHandledEventFilter>> _localFilters
= new Dictionary<object, Dictionary<int, LocalHandledEventFilter>>();
/** Cluster group. */
private readonly IClusterGroup _clusterGroup;
/** Async instance. */
private readonly Lazy<Events> _asyncInstance;
/// <summary>
/// Initializes a new instance of the <see cref="Events" /> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="clusterGroup">Cluster group.</param>
public Events(IUnmanagedTarget target, Marshaller marsh, IClusterGroup clusterGroup)
: base(target, marsh)
{
Debug.Assert(clusterGroup != null);
_clusterGroup = clusterGroup;
_asyncInstance = new Lazy<Events>(() => new Events(this));
}
/// <summary>
/// Initializes a new async instance.
/// </summary>
/// <param name="events">The events.</param>
private Events(Events events) : base(UU.EventsWithAsync(events.Target), events.Marshaller)
{
_clusterGroup = events.ClusterGroup;
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup
{
get { return _clusterGroup; }
}
/** */
private Ignite Ignite
{
get { return (Ignite) ClusterGroup.Ignite; }
}
/// <summary>
/// Gets the asynchronous instance.
/// </summary>
private Events AsyncInstance
{
get { return _asyncInstance.Value; }
}
/** <inheritDoc /> */
public ICollection<T> RemoteQuery<T>(IEventFilter<T> filter, TimeSpan? timeout = null, params int[] types)
where T : IEvent
{
IgniteArgumentCheck.NotNull(filter, "filter");
return DoOutInOp((int) Op.RemoteQuery,
writer =>
{
writer.Write(filter);
writer.WriteLong((long) (timeout == null ? 0 : timeout.Value.TotalMilliseconds));
WriteEventTypes(types, writer);
},
reader => ReadEvents<T>(reader));
}
/** <inheritDoc /> */
public Task<ICollection<T>> RemoteQueryAsync<T>(IEventFilter<T> filter, TimeSpan? timeout = null,
params int[] types) where T : IEvent
{
AsyncInstance.RemoteQuery(filter, timeout, types);
// ReSharper disable once RedundantTypeArgumentsOfMethod (won't compile in VS2010)
return GetFuture<ICollection<T>>((futId, futTyp) => UU.TargetListenFutureForOperation(AsyncInstance.Target,
futId, futTyp, (int) Op.RemoteQuery), convertFunc: ReadEvents<T>).Task;
}
/** <inheritDoc /> */
public ICollection<T> RemoteQuery<T>(IEventFilter<T> filter, TimeSpan? timeout = null,
IEnumerable<int> types = null) where T : IEvent
{
return RemoteQuery(filter, timeout, TypesToArray(types));
}
/** <inheritDoc /> */
public Task<ICollection<T>> RemoteQueryAsync<T>(IEventFilter<T> filter, TimeSpan? timeout = null,
IEnumerable<int> types = null) where T : IEvent
{
return RemoteQueryAsync(filter, timeout, TypesToArray(types));
}
/** <inheritDoc /> */
public Guid? RemoteListen<T>(int bufSize = 1, TimeSpan? interval = null, bool autoUnsubscribe = true,
IEventFilter<T> localListener = null, IEventFilter<T> remoteFilter = null, params int[] types)
where T : IEvent
{
IgniteArgumentCheck.Ensure(bufSize > 0, "bufSize", "should be > 0");
IgniteArgumentCheck.Ensure(interval == null || interval.Value.TotalMilliseconds > 0, "interval", "should be null or >= 0");
return DoOutInOp((int) Op.RemoteListen,
writer =>
{
writer.WriteInt(bufSize);
writer.WriteLong((long) (interval == null ? 0 : interval.Value.TotalMilliseconds));
writer.WriteBoolean(autoUnsubscribe);
writer.WriteBoolean(localListener != null);
if (localListener != null)
{
var listener = new RemoteListenEventFilter(Ignite, e => localListener.Invoke((T) e));
writer.WriteLong(Ignite.HandleRegistry.Allocate(listener));
}
writer.WriteBoolean(remoteFilter != null);
if (remoteFilter != null)
writer.Write(remoteFilter);
WriteEventTypes(types, writer);
},
reader => Marshaller.StartUnmarshal(reader).ReadGuid());
}
/** <inheritDoc /> */
public Guid? RemoteListen<T>(int bufSize = 1, TimeSpan? interval = null, bool autoUnsubscribe = true,
IEventFilter<T> localListener = null, IEventFilter<T> remoteFilter = null, IEnumerable<int> types = null)
where T : IEvent
{
return RemoteListen(bufSize, interval, autoUnsubscribe, localListener, remoteFilter, TypesToArray(types));
}
/** <inheritDoc /> */
public void StopRemoteListen(Guid opId)
{
DoOutOp((int) Op.StopRemoteListen, writer =>
{
Marshaller.StartMarshal(writer).WriteGuid(opId);
});
}
/** <inheritDoc /> */
public IEvent WaitForLocal(params int[] types)
{
return WaitForLocal<IEvent>(null, types);
}
/** <inheritDoc /> */
public Task<IEvent> WaitForLocalAsync(params int[] types)
{
return WaitForLocalAsync<IEvent>(null, types);
}
/** <inheritDoc /> */
public IEvent WaitForLocal(IEnumerable<int> types)
{
return WaitForLocal(TypesToArray(types));
}
/** <inheritDoc /> */
public Task<IEvent> WaitForLocalAsync(IEnumerable<int> types)
{
return WaitForLocalAsync<IEvent>(null, TypesToArray(types));
}
/** <inheritDoc /> */
public T WaitForLocal<T>(IEventFilter<T> filter, params int[] types) where T : IEvent
{
long hnd = 0;
try
{
return WaitForLocal0(filter, ref hnd, types);
}
finally
{
if (filter != null)
Ignite.HandleRegistry.Release(hnd);
}
}
/** <inheritDoc /> */
public Task<T> WaitForLocalAsync<T>(IEventFilter<T> filter, params int[] types) where T : IEvent
{
long hnd = 0;
try
{
AsyncInstance.WaitForLocal0(filter, ref hnd, types);
// ReSharper disable once RedundantTypeArgumentsOfMethod (won't compile in VS2010)
var fut = GetFuture<T>((futId, futTyp) => UU.TargetListenFutureForOperation(AsyncInstance.Target, futId,
futTyp, (int) Op.WaitForLocal), convertFunc: reader => (T) EventReader.Read<IEvent>(reader));
if (filter != null)
{
// Dispose handle as soon as future ends.
fut.Task.ContinueWith(x => Ignite.HandleRegistry.Release(hnd));
}
return fut.Task;
}
catch (Exception)
{
Ignite.HandleRegistry.Release(hnd);
throw;
}
}
/** <inheritDoc /> */
public T WaitForLocal<T>(IEventFilter<T> filter, IEnumerable<int> types) where T : IEvent
{
return WaitForLocal(filter, TypesToArray(types));
}
/** <inheritDoc /> */
public Task<T> WaitForLocalAsync<T>(IEventFilter<T> filter, IEnumerable<int> types) where T : IEvent
{
return WaitForLocalAsync(filter, TypesToArray(types));
}
/** <inheritDoc /> */
public ICollection<IEvent> LocalQuery(params int[] types)
{
return DoOutInOp((int) Op.LocalQuery,
writer => WriteEventTypes(types, writer),
reader => ReadEvents<IEvent>(reader));
}
/** <inheritDoc /> */
public ICollection<IEvent> LocalQuery(IEnumerable<int> types)
{
return LocalQuery(TypesToArray(types));
}
/** <inheritDoc /> */
public void RecordLocal(IEvent evt)
{
throw new NotImplementedException("IGNITE-1410");
}
/** <inheritDoc /> */
public void LocalListen<T>(IEventListener<T> listener, params int[] types) where T : IEvent
{
IgniteArgumentCheck.NotNull(listener, "listener");
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
foreach (var type in types)
LocalListen(listener, type);
}
/** <inheritDoc /> */
public void LocalListen<T>(IEventListener<T> listener, IEnumerable<int> types) where T : IEvent
{
LocalListen(listener, TypesToArray(types));
}
/** <inheritDoc /> */
public bool StopLocalListen<T>(IEventListener<T> listener, params int[] types) where T : IEvent
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
return false;
var success = false;
// Should do this inside lock to avoid race with subscription
// ToArray is required because we are going to modify underlying dictionary during enumeration
foreach (var filter in GetLocalFilters(listener, types).ToArray())
success |= UU.EventsStopLocalListen(Target, filter.Handle);
return success;
}
}
/** <inheritDoc /> */
public bool StopLocalListen<T>(IEventListener<T> listener, IEnumerable<int> types) where T : IEvent
{
return StopLocalListen(listener, TypesToArray(types));
}
/** <inheritDoc /> */
public void EnableLocal(IEnumerable<int> types)
{
EnableLocal(TypesToArray(types));
}
/** <inheritDoc /> */
public void EnableLocal(params int[] types)
{
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
DoOutOp((int)Op.EnableLocal, writer => WriteEventTypes(types, writer));
}
/** <inheritDoc /> */
public void DisableLocal(params int[] types)
{
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
DoOutOp((int)Op.DisableLocal, writer => WriteEventTypes(types, writer));
}
/** <inheritDoc /> */
public void DisableLocal(IEnumerable<int> types)
{
DisableLocal(TypesToArray(types));
}
/** <inheritDoc /> */
public ICollection<int> GetEnabledEvents()
{
return DoInOp((int)Op.GetEnabledEvents, reader => ReadEventTypes(reader));
}
/** <inheritDoc /> */
public bool IsEnabled(int type)
{
return UU.EventsIsEnabled(Target, type);
}
/// <summary>
/// Waits for the specified events.
/// </summary>
/// <typeparam name="T">Type of events.</typeparam>
/// <param name="filter">Optional filtering predicate. Event wait will end as soon as it returns false.</param>
/// <param name="handle">The filter handle, if applicable.</param>
/// <param name="types">Types of the events to wait for.
/// If not provided, all events will be passed to the filter.</param>
/// <returns>Ignite event.</returns>
private T WaitForLocal0<T>(IEventFilter<T> filter, ref long handle, params int[] types) where T : IEvent
{
if (filter != null)
handle = Ignite.HandleRegistry.Allocate(new LocalEventFilter
{
InvokeFunc = stream => InvokeLocalFilter(stream, filter)
});
var hnd = handle;
return DoOutInOp((int)Op.WaitForLocal,
writer =>
{
if (filter != null)
{
writer.WriteBoolean(true);
writer.WriteLong(hnd);
}
else
writer.WriteBoolean(false);
WriteEventTypes(types, writer);
},
reader => EventReader.Read<T>(Marshaller.StartUnmarshal(reader)));
}
/// <summary>
/// Reads events from a binary stream.
/// </summary>
/// <typeparam name="T">Event type.</typeparam>
/// <param name="reader">Reader.</param>
/// <returns>Resulting list or null.</returns>
private ICollection<T> ReadEvents<T>(IBinaryStream reader) where T : IEvent
{
return ReadEvents<T>(Marshaller.StartUnmarshal(reader));
}
/// <summary>
/// Reads events from a binary reader.
/// </summary>
/// <typeparam name="T">Event type.</typeparam>
/// <param name="binaryReader">Reader.</param>
/// <returns>Resulting list or null.</returns>
private static ICollection<T> ReadEvents<T>(BinaryReader binaryReader) where T : IEvent
{
var count = binaryReader.GetRawReader().ReadInt();
if (count == -1)
return null;
var result = new List<T>(count);
for (var i = 0; i < count; i++)
result.Add(EventReader.Read<T>(binaryReader));
return result;
}
/// <summary>
/// Gets local filters by user listener and event type.
/// </summary>
/// <param name="listener">Listener.</param>
/// <param name="types">Types.</param>
/// <returns>Collection of local listener wrappers.</returns>
[SuppressMessage("ReSharper", "InconsistentlySynchronizedField",
Justification = "This private method should be always called within a lock on localFilters")]
private IEnumerable<LocalHandledEventFilter> GetLocalFilters(object listener, int[] types)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
return Enumerable.Empty<LocalHandledEventFilter>();
if (types.Length == 0)
return filters.Values;
return types.Select(type =>
{
LocalHandledEventFilter filter;
return filters.TryGetValue(type, out filter) ? filter : null;
}).Where(x => x != null);
}
/// <summary>
/// Adds an event listener for local events.
/// </summary>
/// <typeparam name="T">Type of events.</typeparam>
/// <param name="listener">Predicate that is called on each received event.</param>
/// <param name="type">Event type for which this listener will be notified</param>
private void LocalListen<T>(IEventListener<T> listener, int type) where T : IEvent
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
{
filters = new Dictionary<int, LocalHandledEventFilter>();
_localFilters[listener] = filters;
}
LocalHandledEventFilter localFilter;
if (!filters.TryGetValue(type, out localFilter))
{
localFilter = CreateLocalListener(listener, type);
filters[type] = localFilter;
}
UU.EventsLocalListen(Target, localFilter.Handle, type);
}
}
/// <summary>
/// Creates a user filter wrapper.
/// </summary>
/// <typeparam name="T">Event object type.</typeparam>
/// <param name="listener">Listener.</param>
/// <param name="type">Event type.</param>
/// <returns>Created wrapper.</returns>
private LocalHandledEventFilter CreateLocalListener<T>(IEventListener<T> listener, int type) where T : IEvent
{
var result = new LocalHandledEventFilter(
stream => InvokeLocalListener(stream, listener),
unused =>
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (_localFilters.TryGetValue(listener, out filters))
{
filters.Remove(type);
if (filters.Count == 0)
_localFilters.Remove(listener);
}
}
});
result.Handle = Ignite.HandleRegistry.Allocate(result);
return result;
}
/// <summary>
/// Invokes local filter using data from specified stream.
/// </summary>
/// <typeparam name="T">Event object type.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="listener">The listener.</param>
/// <returns>Filter invocation result.</returns>
private bool InvokeLocalFilter<T>(IBinaryStream stream, IEventFilter<T> listener) where T : IEvent
{
var evt = EventReader.Read<T>(Marshaller.StartUnmarshal(stream));
return listener.Invoke(evt);
}
/// <summary>
/// Invokes local filter using data from specified stream.
/// </summary>
/// <typeparam name="T">Event object type.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="listener">The listener.</param>
/// <returns>Filter invocation result.</returns>
private bool InvokeLocalListener<T>(IBinaryStream stream, IEventListener<T> listener) where T : IEvent
{
var evt = EventReader.Read<T>(Marshaller.StartUnmarshal(stream));
return listener.Invoke(evt);
}
/// <summary>
/// Writes the event types.
/// </summary>
/// <param name="types">Types.</param>
/// <param name="writer">Writer.</param>
private static void WriteEventTypes(int[] types, IBinaryRawWriter writer)
{
if (types != null && types.Length == 0)
types = null; // empty array means no type filtering
writer.WriteIntArray(types);
}
/// <summary>
/// Writes the event types.
/// </summary>
/// <param name="reader">Reader.</param>
private int[] ReadEventTypes(IBinaryStream reader)
{
return Marshaller.StartUnmarshal(reader).ReadIntArray();
}
/// <summary>
/// Converts types enumerable to array.
/// </summary>
private static int[] TypesToArray(IEnumerable<int> types)
{
if (types == null)
return null;
return types as int[] ?? types.ToArray();
}
/// <summary>
/// Local user filter wrapper.
/// </summary>
private class LocalEventFilter : IInteropCallback
{
/** */
public Func<IBinaryStream, bool> InvokeFunc;
/** <inheritdoc /> */
public int Invoke(IBinaryStream stream)
{
return InvokeFunc(stream) ? 1 : 0;
}
}
/// <summary>
/// Local user filter wrapper with handle.
/// </summary>
private class LocalHandledEventFilter : Handle<Func<IBinaryStream, bool>>, IInteropCallback
{
/** */
public long Handle;
/** <inheritdoc /> */
public int Invoke(IBinaryStream stream)
{
return Target(stream) ? 1 : 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalHandledEventFilter"/> class.
/// </summary>
/// <param name="invokeFunc">The invoke function.</param>
/// <param name="releaseAction">The release action.</param>
public LocalHandledEventFilter(
Func<IBinaryStream, bool> invokeFunc, Action<Func<IBinaryStream, bool>> releaseAction)
: base(invokeFunc, releaseAction)
{
// No-op.
}
}
}
}
| |
#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RabbitLink.Internals;
using RabbitLink.Internals.Actions;
using RabbitLink.Internals.Queues;
using RabbitLink.Logging;
using RabbitMQ.Client;
#endregion
namespace RabbitLink.Topology.Internal
{
internal class LinkTopologyConfig : ILinkTopologyConfig
{
private readonly IActionInvoker<IModel> _invoker;
private readonly ILinkLogger _logger;
public LinkTopologyConfig(ILinkLogger logger, IActionInvoker<IModel> invoker)
{
_invoker = invoker ?? throw new ArgumentNullException(nameof(invoker));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task Bind(ILinkExchange destination, ILinkExchange source, string routingKey = null,
IDictionary<string, object> arguments = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (routingKey == null)
routingKey = string.Empty;
if (arguments == null)
arguments = new Dictionary<string, object>();
await _invoker
.InvokeAsync(model => model.ExchangeBind(destination.Name, source.Name, routingKey, arguments))
.ConfigureAwait(false);
_logger.Debug(
$"Bound destination exchange {destination.Name} to source exchange {source.Name} with routing key {routingKey} and arguments: {string.Join(", ", arguments.Select(x => $"{x.Key} = {x.Value}"))}");
}
public async Task Unbind(ILinkExchange destination, ILinkExchange source, string routingKey = null,
IDictionary<string, object> arguments = null)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (routingKey == null)
routingKey = string.Empty;
if (arguments == null)
arguments = new Dictionary<string, object>();
await _invoker
.InvokeAsync(model => model.ExchangeUnbind(destination.Name, source.Name, routingKey, arguments))
.ConfigureAwait(false);
_logger.Debug(
$"Unbound destination exchange {destination.Name} to source exchange {source.Name} with routing key {routingKey} and arguments: {string.Join(", ", arguments.Select(x => $"{x.Key} = {x.Value}"))}");
}
public async Task Bind(ILinkQueue queue, ILinkExchange exchange, string routingKey = null,
IDictionary<string, object> arguments = null)
{
if (exchange == null)
throw new ArgumentNullException(nameof(exchange));
if (queue == null)
throw new ArgumentNullException(nameof(queue));
if (routingKey == null)
routingKey = string.Empty;
if (arguments == null)
arguments = new Dictionary<string, object>();
await _invoker
.InvokeAsync(model => model.QueueBind(queue.Name, exchange.Name, routingKey, arguments))
.ConfigureAwait(false);
_logger.Debug(
$"Bound queue {queue.Name} from exchange {exchange.Name} with routing key {routingKey} and arguments: {string.Join(", ", arguments.Select(x => $"{x.Key} = {x.Value}"))}");
}
public async Task Unbind(ILinkQueue queue, ILinkExchange exchange, string routingKey = null,
IDictionary<string, object> arguments = null)
{
if (exchange == null)
throw new ArgumentNullException(nameof(exchange));
if (queue == null)
throw new ArgumentNullException(nameof(queue));
if (routingKey == null)
routingKey = string.Empty;
if (arguments == null)
arguments = new Dictionary<string, object>();
await _invoker
.InvokeAsync(model => model.QueueUnbind(queue.Name, exchange.Name, routingKey, arguments))
.ConfigureAwait(false);
_logger.Debug(
$"Unbound queue {queue.Name} from exchange {exchange.Name} with routing key {routingKey} and arguments: {string.Join(", ", arguments.Select(x => $"{x.Key} = {x.Value}"))}");
}
#region Exchange
public async Task<ILinkExchange> ExchangeDeclare(
string name,
LinkExchangeType type,
bool durable = true,
bool autoDelete = false,
string alternateExchange = null,
bool delayed = false
)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
string exchangeType;
switch (type)
{
case LinkExchangeType.Direct:
exchangeType = ExchangeType.Direct;
break;
case LinkExchangeType.Fanout:
exchangeType = ExchangeType.Fanout;
break;
case LinkExchangeType.Headers:
exchangeType = ExchangeType.Headers;
break;
case LinkExchangeType.Topic:
exchangeType = ExchangeType.Topic;
break;
default:
throw new ArgumentOutOfRangeException(nameof(type));
}
var arguments = new Dictionary<string, object>();
if (!string.IsNullOrWhiteSpace(alternateExchange))
{
arguments.Add("alternate-exchange", alternateExchange!);
}
if (delayed)
{
arguments.Add("x-delayed-type", exchangeType);
exchangeType = "x-delayed-message";
}
await _invoker
.InvokeAsync(model => model.ExchangeDeclare(name, exchangeType, durable, autoDelete, arguments))
.ConfigureAwait(false);
_logger.Debug(
$"Declared exchange \"{name}\", type: {exchangeType}, durable: {durable}, autoDelete: {autoDelete}, arguments: {string.Join(", ", arguments.Select(x => $"{x.Key} = {x.Value}"))}");
return new LinkExchange(name);
}
public async Task<ILinkExchange> ExchangeDeclarePassive(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
await _invoker
.InvokeAsync(model => model.ExchangeDeclarePassive(name))
.ConfigureAwait(false);
_logger.Debug($"Declared exchange passive: \"{name}\"");
return new LinkExchange(name);
}
public Task<ILinkExchange> ExchangeDeclareDefault()
{
_logger.Debug("Declared default exchange");
return Task.FromResult((ILinkExchange) new LinkExchange(""));
}
public async Task ExchangeDelete(ILinkExchange exchange, bool ifUnused = false)
{
if (exchange == null)
throw new ArgumentNullException(nameof(exchange));
await _invoker
.InvokeAsync(model => model.ExchangeDelete(exchange.Name, ifUnused))
.ConfigureAwait(false);
_logger.Debug($"Deleted exchange \"{exchange.Name}\", unused: {ifUnused}");
}
#endregion
#region Queue
public async Task<ILinkQueue> QueueDeclareExclusiveByServer()
{
var queue = await _invoker
.InvokeAsync(model => model.QueueDeclare())
.ConfigureAwait(false);
_logger.Debug($"Declared exclusive queue with name from server: \"{queue.QueueName}\"");
return new LinkQueue(queue.QueueName, true);
}
public async Task<ILinkQueue> QueueDeclareExclusive(
bool autoDelete = true,
TimeSpan? messageTtl = null,
TimeSpan? expires = null,
byte? maxPriority = null,
int? maxLength = null,
int? maxLengthBytes = null,
string deadLetterExchange = null,
string deadLetterRoutingKey = null
)
{
return await QueueDeclare(
$"exclusive-{Guid.NewGuid():N}", false, true, autoDelete, messageTtl, expires, maxPriority,
maxLength,
maxLengthBytes, deadLetterExchange, deadLetterRoutingKey
)
.ConfigureAwait(false);
}
public async Task<ILinkQueue> QueueDeclareExclusive(
string prefix,
bool autoDelete = true,
TimeSpan? messageTtl = null,
TimeSpan? expires = null,
byte? maxPriority = null,
int? maxLength = null,
int? maxLengthBytes = null,
string deadLetterExchange = null,
string deadLetterRoutingKey = null
)
{
if (string.IsNullOrWhiteSpace(prefix))
throw new ArgumentNullException(nameof(prefix));
return await QueueDeclare(
$"{prefix}-exclusive-{Guid.NewGuid():N}", false, true, autoDelete, messageTtl, expires, maxPriority,
maxLength, maxLengthBytes, deadLetterExchange, deadLetterRoutingKey
)
.ConfigureAwait(false);
}
public async Task<ILinkQueue> QueueDeclarePassive(string name)
{
var queue = await _invoker
.InvokeAsync(model => model.QueueDeclarePassive(name))
.ConfigureAwait(false);
return new LinkQueue(queue.QueueName, false);
}
public async Task<ILinkQueue> QueueDeclare(
string name,
bool durable = true,
bool exclusive = false,
bool autoDelete = false,
TimeSpan? messageTtl = null,
TimeSpan? expires = null,
byte? maxPriority = null,
int? maxLength = null,
int? maxLengthBytes = null,
string deadLetterExchange = null,
string deadLetterRoutingKey = null
)
{
var arguments = new Dictionary<string, object>();
if (messageTtl != null)
{
if (messageTtl.Value.TotalMilliseconds < 0 || messageTtl.Value.TotalMilliseconds > long.MaxValue)
throw new ArgumentOutOfRangeException(nameof(messageTtl),
"Must be greater or equal 0 and less than Int64.MaxValue");
arguments.Add("x-message-ttl", (long) messageTtl.Value.TotalMilliseconds);
}
if (expires != null)
{
if (expires.Value.TotalMilliseconds <= 0 || expires.Value.TotalMilliseconds > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(expires),
"Total milliseconds must be greater than 0 and less than Int32.MaxValue");
arguments.Add("x-expires", (int) expires.Value.TotalMilliseconds);
}
if (maxPriority != null)
{
arguments.Add("x-max-priority", maxPriority.Value);
}
if (maxLength != null)
{
if (maxLength <= 0)
throw new ArgumentOutOfRangeException(nameof(maxLength), "Must be greater than 0");
arguments.Add("x-max-length", maxLength.Value);
}
if (maxLengthBytes != null)
{
if (maxLengthBytes <= 0)
throw new ArgumentOutOfRangeException(nameof(maxLengthBytes), "Must be greater than 0");
arguments.Add("x-max-length-bytes", maxLengthBytes.Value);
}
if (deadLetterExchange != null)
{
arguments.Add("x-dead-letter-exchange", deadLetterExchange);
}
if (deadLetterRoutingKey != null)
{
arguments.Add("x-dead-letter-routing-key", deadLetterRoutingKey);
}
var queue = await _invoker
.InvokeAsync(model => model.QueueDeclare(name, durable, exclusive, autoDelete, arguments))
.ConfigureAwait(false);
_logger.Debug(
$"Declared queue \"{queue.QueueName}\", durable: {durable}, exclusive: {exclusive}, autoDelete: {autoDelete}, arguments: {string.Join(", ", arguments.Select(x => $"{x.Key} = {x.Value}"))}");
return new LinkQueue(queue.QueueName, exclusive);
}
public async Task QueueDelete(ILinkQueue queue, bool ifUnused = false, bool ifEmpty = false)
{
if (queue == null)
throw new ArgumentNullException(nameof(queue));
await _invoker
.InvokeAsync(model => model.QueueDelete(queue.Name, ifUnused, ifEmpty))
.ConfigureAwait(false);
_logger.Debug($"Deleted queue \"{queue.Name}\", unused: {ifUnused}, empty: {ifEmpty}");
}
public async Task QueuePurge(ILinkQueue queue)
{
if (queue == null)
throw new ArgumentNullException(nameof(queue));
await _invoker
.InvokeAsync(model => model.QueuePurge(queue.Name))
.ConfigureAwait(false);
_logger.Debug($"Purged queue \"{queue.Name}\"");
}
#endregion
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Google.Protobuf.Reflection
{
/// <summary>
/// Describes a .proto file, including everything defined within.
/// IDescriptor is implemented such that the File property returns this descriptor,
/// and the FullName is the same as the Name.
/// </summary>
public sealed class FileDescriptor : IDescriptor
{
// Prevent linker failures when using IL2CPP with the well-known types.
static FileDescriptor()
{
ForceReflectionInitialization<Syntax>();
ForceReflectionInitialization<NullValue>();
ForceReflectionInitialization<Field.Types.Cardinality>();
ForceReflectionInitialization<Field.Types.Kind>();
ForceReflectionInitialization<Value.KindOneofCase>();
}
private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
{
SerializedData = descriptorData;
DescriptorPool = pool;
Proto = proto;
Dependencies = new ReadOnlyCollection<FileDescriptor>((FileDescriptor[]) dependencies.Clone());
PublicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies);
pool.AddPackage(Package, this);
MessageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
(message, index) =>
new MessageDescriptor(message, this, null, index, generatedCodeInfo.NestedTypes[index]));
EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
(enumType, index) =>
new EnumDescriptor(enumType, this, null, index, generatedCodeInfo.NestedEnums[index]));
Services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
(service, index) =>
new ServiceDescriptor(service, this, index));
}
/// <summary>
/// Computes the full name of a descriptor within this file, with an optional parent message.
/// </summary>
internal string ComputeFullName(MessageDescriptor parent, string name)
{
if (parent != null)
{
return parent.FullName + "." + name;
}
if (Package.Length > 0)
{
return Package + "." + name;
}
return name;
}
/// <summary>
/// Extracts public dependencies from direct dependencies. This is a static method despite its
/// first parameter, as the value we're in the middle of constructing is only used for exceptions.
/// </summary>
private static IList<FileDescriptor> DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies)
{
var nameToFileMap = new Dictionary<string, FileDescriptor>();
foreach (var file in dependencies)
{
nameToFileMap[file.Name] = file;
}
var publicDependencies = new List<FileDescriptor>();
for (int i = 0; i < proto.PublicDependency.Count; i++)
{
int index = proto.PublicDependency[i];
if (index < 0 || index >= proto.Dependency.Count)
{
throw new DescriptorValidationException(@this, "Invalid public dependency index.");
}
string name = proto.Dependency[index];
FileDescriptor file = nameToFileMap[name];
if (file == null)
{
if (!allowUnknownDependencies)
{
throw new DescriptorValidationException(@this, "Invalid public dependency: " + name);
}
// Ignore unknown dependencies.
}
else
{
publicDependencies.Add(file);
}
}
return new ReadOnlyCollection<FileDescriptor>(publicDependencies);
}
/// <value>
/// The descriptor in its protocol message representation.
/// </value>
internal FileDescriptorProto Proto { get; }
/// <value>
/// The file name.
/// </value>
public string Name => Proto.Name;
/// <summary>
/// The package as declared in the .proto file. This may or may not
/// be equivalent to the .NET namespace of the generated classes.
/// </summary>
public string Package => Proto.Package;
/// <value>
/// Unmodifiable list of top-level message types declared in this file.
/// </value>
public IList<MessageDescriptor> MessageTypes { get; }
/// <value>
/// Unmodifiable list of top-level enum types declared in this file.
/// </value>
public IList<EnumDescriptor> EnumTypes { get; }
/// <value>
/// Unmodifiable list of top-level services declared in this file.
/// </value>
public IList<ServiceDescriptor> Services { get; }
/// <value>
/// Unmodifiable list of this file's dependencies (imports).
/// </value>
public IList<FileDescriptor> Dependencies { get; }
/// <value>
/// Unmodifiable list of this file's public dependencies (public imports).
/// </value>
public IList<FileDescriptor> PublicDependencies { get; }
/// <value>
/// The original serialized binary form of this descriptor.
/// </value>
public ByteString SerializedData { get; }
/// <value>
/// Implementation of IDescriptor.FullName - just returns the same as Name.
/// </value>
string IDescriptor.FullName => Name;
/// <value>
/// Implementation of IDescriptor.File - just returns this descriptor.
/// </value>
FileDescriptor IDescriptor.File => this;
/// <value>
/// Pool containing symbol descriptors.
/// </value>
internal DescriptorPool DescriptorPool { get; }
/// <summary>
/// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types.
/// </summary>
/// <param name="name">The unqualified type name to look for.</param>
/// <typeparam name="T">The type of descriptor to look for</typeparam>
/// <returns>The type's descriptor, or null if not found.</returns>
public T FindTypeByName<T>(String name)
where T : class, IDescriptor
{
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.IndexOf('.') != -1)
{
return null;
}
if (Package.Length > 0)
{
name = Package + "." + name;
}
T result = DescriptorPool.FindSymbol<T>(name);
if (result != null && result.File == this)
{
return result;
}
return null;
}
/// <summary>
/// Builds a FileDescriptor from its protocol buffer representation.
/// </summary>
/// <param name="descriptorData">The original serialized descriptor data.
/// We have only limited proto2 support, so serializing FileDescriptorProto
/// would not necessarily give us this.</param>
/// <param name="proto">The protocol message form of the FileDescriptor.</param>
/// <param name="dependencies">FileDescriptors corresponding to all of the
/// file's dependencies, in the exact order listed in the .proto file. May be null,
/// in which case it is treated as an empty array.</param>
/// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param>
/// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param>
/// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not
/// a valid descriptor. This can occur for a number of reasons, such as a field
/// having an undefined type or because two messages were defined with the same name.</exception>
private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
{
// Building descriptors involves two steps: translating and linking.
// In the translation step (implemented by FileDescriptor's
// constructor), we build an object tree mirroring the
// FileDescriptorProto's tree and put all of the descriptors into the
// DescriptorPool's lookup tables. In the linking step, we look up all
// type references in the DescriptorPool, so that, for example, a
// FieldDescriptor for an embedded message contains a pointer directly
// to the Descriptor for that message's type. We also detect undefined
// types in the linking step.
if (dependencies == null)
{
dependencies = new FileDescriptor[0];
}
DescriptorPool pool = new DescriptorPool(dependencies);
FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo);
// Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we
// need.
if (dependencies.Length != proto.Dependency.Count)
{
throw new DescriptorValidationException(
result,
"Dependencies passed to FileDescriptor.BuildFrom() don't match " +
"those listed in the FileDescriptorProto.");
}
result.CrossLink();
return result;
}
private void CrossLink()
{
foreach (MessageDescriptor message in MessageTypes)
{
message.CrossLink();
}
foreach (ServiceDescriptor service in Services)
{
service.CrossLink();
}
}
/// <summary>
/// Creates a descriptor for generated code.
/// </summary>
/// <remarks>
/// This method is only designed to be used by the results of generating code with protoc,
/// which creates the appropriate dependencies etc. It has to be public because the generated
/// code is "external", but should not be called directly by end users.
/// </remarks>
public static FileDescriptor FromGeneratedCode(
byte[] descriptorData,
FileDescriptor[] dependencies,
GeneratedClrTypeInfo generatedCodeInfo)
{
FileDescriptorProto proto;
try
{
proto = FileDescriptorProto.Parser.ParseFrom(descriptorData);
}
catch (InvalidProtocolBufferException e)
{
throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
}
try
{
// When building descriptors for generated code, we allow unknown
// dependencies by default.
return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo);
}
catch (DescriptorValidationException e)
{
throw new ArgumentException($"Invalid embedded descriptor for \"{proto.Name}\".", e);
}
}
/// <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()
{
return $"FileDescriptor for {Name}";
}
/// <summary>
/// Returns the file descriptor for descriptor.proto.
/// </summary>
/// <remarks>
/// This is used for protos which take a direct dependency on <c>descriptor.proto</c>, typically for
/// annotations. While <c>descriptor.proto</c> is a proto2 file, it is built into the Google.Protobuf
/// runtime for reflection purposes. The messages are internal to the runtime as they would require
/// proto2 semantics for full support, but the file descriptor is available via this property. The
/// C# codegen in protoc automatically uses this property when it detects a dependency on <c>descriptor.proto</c>.
/// </remarks>
/// <value>
/// The file descriptor for <c>descriptor.proto</c>.
/// </value>
public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorReflection.Descriptor; } }
/// <summary>
/// The (possibly empty) set of custom options for this file.
/// </summary>
public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
/// <summary>
/// Performs initialization for the given generic type argument.
/// </summary>
/// <remarks>
/// This method is present for the sake of AOT compilers. It allows code (whether handwritten or generated)
/// to make calls into the reflection machinery of this library to express an intention to use that type
/// reflectively (e.g. for JSON parsing and formatting). The call itself does almost nothing, but AOT compilers
/// attempting to determine which generic type arguments need to be handled will spot the code path and act
/// accordingly.
/// </remarks>
/// <typeparam name="T">The type to force initialization for.</typeparam>
public static void ForceReflectionInitialization<T>() => ReflectionUtil.ForceInitialize<T>();
}
}
| |
using NUnit.Framework;
using UnityEngine;
using Plugins.CountlySDK.Models;
using Plugins.CountlySDK;
using Plugins.CountlySDK.Enums;
using Plugins.CountlySDK.Services;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Collections.Specialized;
namespace Tests
{
public class ConsentTests
{
private readonly string _serverUrl = "https://xyz.com/";
private readonly string _appKey = "772c091355076ead703f987fee94490";
/// <summary>
/// Assert an array of consent against the expected value.
/// </summary>
/// <param name="expectedValue"> an expected values of consents</param>
/// <param name="consents"> an array consents</param>
public void AssertConsentArray(Consents[] consents, bool expectedValue)
{
foreach (Consents consent in consents) {
Assert.AreEqual(expectedValue, Countly.Instance.Consents.CheckConsentInternal(consent));
}
}
/// <summary>
/// Assert all consents against the expected value.
/// </summary>
/// <param name="expectedValue">an expected values of consents</param>
public void AssertConsentAll(bool expectedValue)
{
Consents[] consents = System.Enum.GetValues(typeof(Consents)).Cast<Consents>().ToArray();
AssertConsentArray(consents, expectedValue);
}
/// <summary>
/// Case: if 'RequiresConsent' isn't set in the configuration during initialization.
/// Result: All features should work.
/// </summary>
[Test]
public void TestDefaultStateOfConsents()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
AssertConsentAll(expectedValue: true);
}
/// <summary>
/// Case: if 'RequiresConsent' isn't set in the configuration during initialization.
/// Result: Consent request should not send.
/// </summary>
[Test]
public void TestConsentsRequest_RequiresConsent_IsFalse()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
Assert.AreEqual(1, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
CountlyRequestModel requestModel = Countly.Instance.Consents._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
Assert.IsNull(collection["consent"]);
Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear();
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Sessions });
Assert.AreEqual(0, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear();
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Sessions });
Assert.AreEqual(0, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
}
/// <summary>
/// It validates the initial consent request that generates after SDK initialization
/// </summary>
[Test]
public void TestConsentRequest()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events, Consents.Clicks, Consents.StarRating, Consents.Views, Consents.Users, Consents.Push, Consents.RemoteConfig, Consents.Location, Consents.Feedback, Consents.Sessions });
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
CountlyRequestModel requestModel = Countly.Instance.Consents._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
JObject consentObj = JObject.Parse(collection.Get("consent"));
Assert.AreEqual(11, consentObj.Count);
Assert.IsTrue(consentObj.GetValue("push").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("users").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("views").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("clicks").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("events").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("crashes").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("sessions").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("location").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("feedback").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("star-rating").ToObject<bool>());
Assert.IsTrue(consentObj.GetValue("remote-config").ToObject<bool>());
}
/// <summary>
/// It validates the consent request when consent of a specific feature is given/removed multiple times.
/// </summary>
[Test]
public void TestConsentRequest_WithConsentIsGivenorRemovedMultipleTimes()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Clear();
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events });
Assert.AreEqual(1, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
CountlyRequestModel requestModel = Countly.Instance.Consents._requestCountlyHelper._requestRepo.Dequeue();
NameValueCollection collection = HttpUtility.ParseQueryString(requestModel.RequestData);
JObject json = JObject.Parse(collection["consent"]);
Assert.AreEqual(2, json.Count);
Assert.IsTrue(json.GetValue("crashes").ToObject<bool>());
Assert.IsTrue(json.GetValue("events").ToObject<bool>());
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Crashes, Consents.Views });
Assert.AreEqual(1, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
requestModel = Countly.Instance.Consents._requestCountlyHelper._requestRepo.Dequeue();
collection = HttpUtility.ParseQueryString(requestModel.RequestData);
json = JObject.Parse(collection["consent"]);
Assert.AreEqual(1, json.Count);
Assert.IsTrue(json.GetValue("views").ToObject<bool>());
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Views });
Assert.AreEqual(0, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Crashes, Consents.Views });
requestModel = Countly.Instance.Consents._requestCountlyHelper._requestRepo.Dequeue();
collection = HttpUtility.ParseQueryString(requestModel.RequestData);
json = JObject.Parse(collection["consent"]);
Assert.AreEqual(2, json.Count);
Assert.IsFalse(json.GetValue("crashes").ToObject<bool>());
Assert.IsFalse(json.GetValue("views").ToObject<bool>());
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Events, Consents.Views });
requestModel = Countly.Instance.Consents._requestCountlyHelper._requestRepo.Dequeue();
collection = HttpUtility.ParseQueryString(requestModel.RequestData);
json = JObject.Parse(collection["consent"]);
Assert.AreEqual(1, json.Count);
Assert.IsFalse(json.GetValue("events").ToObject<bool>());
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Crashes });
Assert.AreEqual(0, Countly.Instance.CrashReports._requestCountlyHelper._requestRepo.Count);
}
/// <summary>
/// Case: if 'RequiresConsent' is set in the configuration and no consent is given during initialization.
/// Result: All features shouldn't work.
/// </summary>
[Test]
public void TestConsentDefaultValuesWithRequiresConsentTrue()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
AssertConsentAll(expectedValue: false);
}
/// <summary>
/// Case: If 'RequiresConsent' isn't set in the configuration and consents change before and after initialization.
/// Result: All features should work.
/// </summary>
[Test]
public void TestConsentDefaultValuesWithRequiresConsentFalse()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
};
string groupA = "GroupA";
configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events });
configuration.CreateConsentGroup(groupA, new Consents[] { Consents.Sessions, Consents.Location });
configuration.GiveConsentToGroup(new string[] { groupA });
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
AssertConsentAll(expectedValue: true);
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Crashes, Consents.Location });
AssertConsentAll(expectedValue: true);
Countly.Instance.Consents.RemoveConsentOfGroup(new string[] { groupA });
AssertConsentAll(expectedValue: true);
Countly.Instance.Consents.RemoveAllConsent();
AssertConsentAll(expectedValue: true);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and consents are given to a consent group named 'GroupA" during initialization.
/// Result: Only Consents of group 'GroupA' should work.
/// </summary>
[Test]
public void TestConsentsGivenDuringInit()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true
};
string groupA = "GroupA";
configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events });
configuration.CreateConsentGroup(groupA, new Consents[] { Consents.Sessions, Consents.Location });
configuration.GiveConsentToGroup(new string[] { groupA });
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
AssertConsentArray(new Consents[] { Consents.Events, Consents.Crashes, Consents.Sessions, Consents.Location }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Users, Consents.Clicks, Consents.StarRating, Consents.RemoteConfig }, false);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration. Consents are given or removed using 'GiveConsentAll' and 'RemoveAllConsent' after initialization.
/// </summary>
[Test]
public void TestGiveAndRemoveAllConsent()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true
};
Countly.Instance.Init(configuration);
/// All consent shouldn't work.
Assert.IsNotNull(Countly.Instance.Consents);
AssertConsentAll(expectedValue: false);
/// All consent should work.
Countly.Instance.Consents.GiveConsentAll();
AssertConsentAll(expectedValue: true);
/// All consents shouldn't work
Countly.Instance.Consents.RemoveAllConsent();
AssertConsentAll(expectedValue: false);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and consents are given using multiple groups during initialization.
/// </summary>
[Test]
public void TestConfigGiveConsents()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
string groupA = "GroupA";
string groupB = "GroupB";
string groupC = "GroupC";
configuration.RequiresConsent = true;
configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Events });
configuration.CreateConsentGroup(groupA, new Consents[] { Consents.Sessions, Consents.Location });
configuration.CreateConsentGroup(groupB, new Consents[] { Consents.RemoteConfig, Consents.Users, Consents.Location });
configuration.CreateConsentGroup(groupC, new Consents[] { Consents.StarRating });
configuration.GiveConsentToGroup(new string[] { groupA, groupC });
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
AssertConsentArray(new Consents[] { Consents.Events, Consents.Crashes, Consents.Sessions, Consents.Location, Consents.StarRating }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Users, Consents.Clicks, Consents.RemoteConfig }, false);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and individual consents are given to multiple features after initialization.
/// </summary>
[Test]
public void TestGiveIndividualConsents()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
// Only Events and Crashes features should work
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.Events, Consents.Crashes });
AssertConsentArray(new Consents[] { Consents.Events, Consents.Crashes }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Users, Consents.Clicks, Consents.RemoteConfig, Consents.Sessions, Consents.Location, Consents.StarRating }, false);
// Only Events, Crashes, and StarRating features should work
Countly.Instance.Consents.GiveConsent(new Consents[] { Consents.StarRating });
AssertConsentArray(new Consents[] { Consents.Events, Consents.Crashes, Consents.StarRating }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Users, Consents.Clicks, Consents.RemoteConfig, Consents.Sessions, Consents.Location }, false);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and individual consents are given to multiple features during initialization and removed a few consents after initialization.
/// </summary>
[Test]
public void TestRemovalIndividualConsents()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
configuration.GiveConsent(new Consents[] { Consents.Crashes, Consents.Views, Consents.StarRating, Consents.Events, Consents.Users });
Countly.Instance.Init(configuration);
AssertConsentArray(new Consents[] { Consents.Events, Consents.Crashes, Consents.StarRating, Consents.Views, Consents.Users }, true);
AssertConsentArray(new Consents[] { Consents.Clicks, Consents.RemoteConfig, Consents.Sessions, Consents.Location }, false);
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Views, Consents.Users });
AssertConsentArray(new Consents[] { Consents.Events, Consents.Crashes, Consents.StarRating }, true);
AssertConsentArray(new Consents[] { Consents.Clicks, Consents.RemoteConfig, Consents.Sessions, Consents.Location, Consents.Views, Consents.Users }, false);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and consents are given to multiple groups during and after initialization.
/// </summary>
[Test]
public void TestGiveConsentToGroup()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
string groupA = "GroupA";
string groupB = "GroupB";
configuration.CreateConsentGroup(groupA, new Consents[] { Consents.Sessions, Consents.Location });
configuration.CreateConsentGroup(groupB, new Consents[] { Consents.RemoteConfig, Consents.Users });
configuration.GiveConsentToGroup(new string[] { groupA });
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
AssertConsentArray(new Consents[] { Consents.Sessions, Consents.Location }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Users, Consents.Clicks, Consents.RemoteConfig, Consents.Events, Consents.Crashes, Consents.StarRating }, false);
Countly.Instance.Consents.GiveConsentToGroup(new string[] { groupB });
AssertConsentArray(new Consents[] { Consents.Sessions, Consents.Location, Consents.Users, Consents.RemoteConfig, }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Clicks, Consents.Events, Consents.Crashes, Consents.StarRating }, false);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and consents are removed of multiple groups after initialization.
/// </summary>
[Test]
public void TestRemoveConsentOfGroup()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
string groupA = "GroupA";
string groupB = "GroupB";
configuration.CreateConsentGroup(groupA, new Consents[] { Consents.Clicks, Consents.Views });
configuration.CreateConsentGroup(groupB, new Consents[] { Consents.RemoteConfig, Consents.Users });
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Consents);
Countly.Instance.Consents.GiveConsentAll();
AssertConsentAll(expectedValue: true);
Countly.Instance.Consents.RemoveConsentOfGroup(new string[] { groupA });
AssertConsentArray(new Consents[] { Consents.Sessions, Consents.Location, Consents.Users, Consents.RemoteConfig, Consents.Events, Consents.Crashes, Consents.StarRating }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Clicks }, false);
Countly.Instance.Consents.RemoveConsentOfGroup(new string[] { groupB });
AssertConsentArray(new Consents[] { Consents.Sessions, Consents.Location, Consents.Events, Consents.Crashes, Consents.StarRating }, true);
AssertConsentArray(new Consents[] { Consents.Views, Consents.Clicks, Consents.Users, Consents.RemoteConfig }, false);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration, the user's location is given and the location consent is given during initialization, and location consent gets removed after initialization.
/// Result: User's location should reset to the default value.
/// </summary>
[Test]
public void TestLocationConsentChangedListener()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
string city = "Houston";
string countryCode = "us";
string latitude = "29.634933";
string longitude = "-95.220255";
string ipAddress = "10.2.33.12";
configuration.SetLocation(countryCode, city, latitude + "," + longitude, ipAddress);
configuration.GiveConsent(new Consents[] { Consents.Location, Consents.RemoteConfig });
Countly.Instance.Init(configuration);
Assert.IsNotNull(Countly.Instance.Location);
Assert.AreEqual(Countly.Instance.Location.City, "Houston");
Assert.AreEqual(Countly.Instance.Location.CountryCode, "us");
Assert.IsFalse(Countly.Instance.Location.IsLocationDisabled);
Assert.AreEqual(Countly.Instance.Location.IPAddress, "10.2.33.12");
Assert.AreEqual(Countly.Instance.Location.Location, "29.634933,-95.220255");
Assert.IsNotNull(Countly.Instance.Consents);
Assert.IsTrue(Countly.Instance.Consents.CheckConsentInternal(Consents.Location));
Countly.Instance.Consents.RemoveConsent(new Consents[] { Consents.Location });
Assert.IsFalse(Countly.Instance.Consents.CheckConsentInternal(Consents.Location));
Assert.IsNull(Countly.Instance.Location.City);
Assert.IsNull(Countly.Instance.Location.Location);
Assert.IsNull(Countly.Instance.Location.IPAddress);
Assert.IsNull(Countly.Instance.Location.CountryCode);
Assert.IsFalse(Countly.Instance.Location.IsLocationDisabled);
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and consent of a specific feature is given multiple times after initialization.
/// Result: 'ConsentChanged' should call with distinct modified consents list on listeners. There shouldn't any duplicates entries.
/// </summary>
[Test]
public void TestListenerOnMultipleConsentOfSameFeature()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
ConsentTestHelperClass listener = new ConsentTestHelperClass();
CountlyLogHelper logHelper = new CountlyLogHelper(configuration);
ConsentCountlyService consentCountlyService = new ConsentCountlyService(configuration, logHelper, null, null);
consentCountlyService.LockObj = new object();
consentCountlyService.Listeners = new List<AbstractBaseService> { listener };
consentCountlyService.GiveConsent(new Consents[] { Consents.Location, Consents.RemoteConfig, Consents.RemoteConfig, Consents.Events });
Assert.IsTrue(listener.Validate(0, new Consents[] { Consents.Location, Consents.RemoteConfig, Consents.Events }, true));
consentCountlyService.RemoveConsent(new Consents[] { Consents.Location, Consents.Location, Consents.StarRating, Consents.Events });
Assert.AreEqual(2, listener.DeltaConsentsList[1].updatedConsents.Count);
Assert.IsTrue(listener.Validate(1, new Consents[] { Consents.Location, Consents.Events }, false));
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and individual consents are given and removed to multiple features after initialization.
/// Result: 'ConsentChanged' should call with a modified consents list on listeners.
/// </summary>
[Test]
public void TestListenerOnConsentChanged()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
ConsentTestHelperClass listener = new ConsentTestHelperClass();
CountlyLogHelper logHelper = new CountlyLogHelper(configuration);
ConsentCountlyService consentCountlyService = new ConsentCountlyService(configuration, logHelper, null, null);
consentCountlyService.LockObj = new object();
consentCountlyService.Listeners = new List<AbstractBaseService> { listener };
consentCountlyService.GiveConsent(new Consents[] { Consents.Location, Consents.RemoteConfig, Consents.Events });
Assert.IsTrue(listener.Validate(0, new Consents[] { Consents.Location, Consents.RemoteConfig, Consents.Events }, true));
consentCountlyService.GiveConsent(new Consents[] { Consents.Location, Consents.StarRating });
Assert.IsTrue(listener.Validate(1, new Consents[] { Consents.StarRating }, true));
consentCountlyService.RemoveConsent(new Consents[] { Consents.Location, Consents.StarRating });
Assert.IsTrue(listener.Validate(2, new Consents[] { Consents.Location, Consents.StarRating }, false));
consentCountlyService.RemoveConsent(new Consents[] { Consents.Events, Consents.StarRating });
Assert.IsTrue(listener.Validate(3, new Consents[] { Consents.Events }, false));
}
/// <summary>
/// Case: If 'RequiresConsent' is set in the configuration and consents are given and removed to multiple groups after initialization.
/// Result: 'ConsentChanged' should call with a modified consents list on listeners.
/// </summary>
[Test]
public void TestListenerOnConsentGroups()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
string groupA = "GroupA";
string groupB = "GroupB";
configuration.CreateConsentGroup(groupA, new Consents[] { Consents.Clicks, Consents.Views });
ConsentTestHelperClass listener = new ConsentTestHelperClass();
CountlyLogHelper logHelper = new CountlyLogHelper(configuration);
ConsentCountlyService consentCountlyService = new ConsentCountlyService(configuration, logHelper, null, null);
consentCountlyService.LockObj = new object();
consentCountlyService.Listeners = new List<AbstractBaseService> { listener };
consentCountlyService.GiveConsentToGroup(new string[] { groupA });
Assert.IsTrue(listener.Validate(0, new Consents[] { Consents.Clicks, Consents.Views }, true));
consentCountlyService.GiveConsentToGroup(new string[] { groupB });
Assert.AreEqual(1, listener.DeltaConsentsList.Count);
consentCountlyService.RemoveConsentOfGroup(new string[] { groupA });
Assert.IsTrue(listener.Validate(1, new Consents[] { Consents.Clicks, Consents.Views }, false));
consentCountlyService.GiveConsent(new Consents[] { Consents.Push, Consents.Views });
Assert.IsTrue(listener.Validate(2, new Consents[] { Consents.Push, Consents.Views }, true));
consentCountlyService.GiveConsentToGroup(new string[] { groupA });
Assert.IsTrue(listener.Validate(3, new Consents[] { Consents.Clicks }, true));
}
/// <summary>
/// Case:
/// step 1: If 'RequiresConsent' is set in the configuration, consents are given to an individual group 'GroupA' after initialization.
/// Result: 'ConsentChanged' should call with a modified consents list containing consents of 'GroupA' on listeners.
/// step 2: Remove consents of all features.
/// Result: 'ConsentChanged' should call with a modified consents list containing consents of 'GroupA' on listeners.
/// step 2: Give consents to all features.
/// Result: 'ConsentChanged' should call with a modified consents list containing all consents on listeners.
/// </summary>
[Test]
public void TestListenerOnAllConsentRemovalAndGiven()
{
CountlyConfiguration configuration = new CountlyConfiguration {
AppKey = _appKey,
ServerUrl = _serverUrl,
RequiresConsent = true,
};
string groupA = "GroupA";
configuration.CreateConsentGroup(groupA, new Consents[] { Consents.Clicks, Consents.Views });
ConsentTestHelperClass listener = new ConsentTestHelperClass();
CountlyLogHelper logHelper = new CountlyLogHelper(configuration);
ConsentCountlyService consentCountlyService = new ConsentCountlyService(configuration, logHelper, null, null);
consentCountlyService.LockObj = new object();
consentCountlyService.Listeners = new List<AbstractBaseService> { listener };
consentCountlyService.GiveConsentToGroup(new string[] { groupA });
Assert.IsTrue(listener.Validate(0, new Consents[] { Consents.Clicks, Consents.Views }, true));
consentCountlyService.RemoveAllConsent();
Assert.IsTrue(listener.Validate(1, new Consents[] { Consents.Clicks, Consents.Views }, false));
consentCountlyService.GiveConsentAll();
Consents[] consents = System.Enum.GetValues(typeof(Consents)).Cast<Consents>().ToArray();
Assert.IsTrue(listener.Validate(2, consents, true));
}
[TearDown]
public void End()
{
Countly.Instance.ClearStorage();
Object.DestroyImmediate(Countly.Instance);
}
private class ConsentTestHelperClass : AbstractBaseService
{
internal List<DeltaConsents> DeltaConsentsList { get; private set; }
internal ConsentTestHelperClass() : base(null, null, null)
{
DeltaConsentsList = new List<DeltaConsents>();
}
internal override void ConsentChanged(List<Consents> updatedConsents, bool newConsentValue, ConsentChangedAction action)
{
DeltaConsents deltaConsents;
deltaConsents.value = newConsentValue;
deltaConsents.updatedConsents = updatedConsents;
DeltaConsentsList.Add(deltaConsents);
}
internal bool Validate(int callIndex, Consents[] calledConsents, bool targetValue)
{
if (callIndex < 0 || callIndex > DeltaConsentsList.Count - 1) {
return false;
}
DeltaConsents deltaConsents = DeltaConsentsList[callIndex];
if (deltaConsents.value != targetValue || deltaConsents.updatedConsents.Count != calledConsents.Length) {
return false;
}
foreach (Consents consent in calledConsents) {
if (!deltaConsents.updatedConsents.Contains(consent)) {
return false;
}
}
return true;
}
internal struct DeltaConsents
{
internal bool value;
internal List<Consents> updatedConsents;
}
}
}
}
| |
// Copyright (c) "Neo4j"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using FluentAssertions;
using Microsoft.Reactive.Testing;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;
using Moq;
using Neo4j.Driver.Internal;
using Neo4j.Driver.Internal.Result;
using Neo4j.Driver.Tests;
using Neo4j.Driver.TestUtil;
using Xunit;
using Xunit.Abstractions;
using static Microsoft.Reactive.Testing.ReactiveTest;
using static Neo4j.Driver.Reactive.Internal.InternalRxResultTests.RxResultUtil;
using static Neo4j.Driver.Reactive.Utils;
using Record = Neo4j.Driver.Internal.Result.Record;
namespace Neo4j.Driver.Reactive.Internal
{
public static class InternalRxResultTests
{
public class Streaming : AbstractRxTest
{
[Fact]
public void ShouldReturnKeys()
{
var cursor = CreateResultCursor(3, 0);
var result = new RxResult(Observable.Return(cursor));
VerifyKeys(result, "key01", "key02", "key03");
}
[Fact]
public void ShouldReturnKeysAfterRecords()
{
var keys = new[] {"key01", "key02", "key03"};
var cursor = CreateResultCursor(3, 0);
var result = new RxResult(Observable.Return(cursor));
VerifyRecords(result, keys, 0);
VerifyKeys(result, keys);
}
[Fact]
public void ShouldReturnKeysAfterSummary()
{
var keys = new[] {"key01", "key02", "key03"};
var cursor = CreateResultCursor(3, 0);
var result = new RxResult(Observable.Return(cursor));
VerifySummary(result);
VerifyKeys(result, keys);
}
[Fact]
public void ShouldReturnKeysRepeatable()
{
var cursor = CreateResultCursor(3, 0);
var result = new RxResult(Observable.Return(cursor));
VerifyKeys(result, "key01", "key02", "key03");
VerifyKeys(result, "key01", "key02", "key03");
VerifyKeys(result, "key01", "key02", "key03");
VerifyKeys(result, "key01", "key02", "key03");
}
[Fact]
public void ShouldReturnRecords()
{
var keys = new[] {"key01", "key02", "key03"};
var cursor = CreateResultCursor(3, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyRecords(result, keys, 5);
}
[Fact]
public void ShouldNotReturnRecordsIfRecordsIsAlreadyObserved()
{
var keys = new[] {"key01", "key02", "key03"};
var cursor = CreateResultCursor(3, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyRecords(result, keys, 5);
VerifyResultConsumedError(result.Records());
}
[Fact]
public void ShouldReturnSummary()
{
var cursor = CreateResultCursor(3, 0, "my query");
var result = new RxResult(Observable.Return(cursor));
VerifySummary(result, "my query");
}
[Fact]
public void ShouldNotReturnRecordsIfSummaryIsObserved()
{
var cursor = CreateResultCursor(3, 0, "my query");
var result = new RxResult(Observable.Return(cursor));
VerifySummary(result, "my query");
VerifyResultConsumedError(result.Records());
}
[Fact]
public void ShouldReturnSummaryRepeatable()
{
var cursor = CreateResultCursor(3, 0, "my query");
var result = new RxResult(Observable.Return(cursor));
VerifySummary(result, "my query");
VerifySummary(result, "my query");
VerifySummary(result, "my query");
VerifySummary(result, "my query");
}
[Fact]
public void ShouldReturnKeysRecordsAndSummary()
{
var keys = new[] {"key01", "key02", "key03"};
var cursor = CreateResultCursor(3, 5, "my query");
var result = new RxResult(Observable.Return(cursor));
VerifyKeys(result, keys);
VerifyRecords(result, keys, 5);
VerifySummary(result, "my query");
}
[Fact]
public void ShouldReturnRecordsAndSummary()
{
var keys = new[] {"key01", "key02", "key03"};
var cursor = CreateResultCursor(3, 5, "my query");
var result = new RxResult(Observable.Return(cursor));
VerifyRecords(result, keys, 5);
VerifySummary(result, "my query");
}
[Fact]
public void ShouldReturnsKeysAndSummary()
{
var keys = new[] {"key01", "key02", "key03"};
var cursor = CreateResultCursor(3, 5, "my query");
var result = new RxResult(Observable.Return(cursor));
VerifyKeys(result, keys);
VerifySummary(result, "my query");
}
[Fact]
public void ShouldNotAllowConcurrentRecordObservers()
{
var cursor = CreateResultCursor(3, 20, "my query", 1000);
var result = new RxResult(Observable.Return(cursor));
result.Records()
.Merge(result.Records())
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0, MatchesException<ClientException>()));
}
}
public class CursorKeysErrors : AbstractRxTest
{
public CursorKeysErrors(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void ShouldErrorOnKeys()
{
var exc = new ClientException("some error");
var cursor = CreateFailingResultCursor(exc);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Keys(), exc);
}
[Fact]
public void ShouldErrorOnKeysRepeatable()
{
var exc = new ClientException("some error");
var cursor = CreateFailingResultCursor(exc);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Keys(), exc);
VerifyError(result.Keys(), exc);
VerifyError(result.Keys(), exc);
}
[Fact]
public void ShouldErrorOnRecords()
{
var exc = new ClientException("some error");
var cursor = CreateFailingResultCursor(exc);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Records(), exc);
}
[Fact]
public void ShouldErrorOnRecordsRepeatable()
{
var exc = new ClientException("some error");
var cursor = CreateFailingResultCursor(exc);
var result = new RxResult(Observable.Return(cursor), new TestLogger(Output.WriteLine));
VerifyError(result.Records(), exc);
VerifyResultConsumedError(result.Records());
VerifyResultConsumedError(result.Records());
}
[Fact]
public void ShouldErrorOnSummary()
{
var exc = new ClientException("some error");
var cursor = CreateFailingResultCursor(exc);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Consume(), exc);
}
[Fact]
public void ShouldErrorOnSummaryRepeatable()
{
var exc = new ClientException("some error");
var cursor = CreateFailingResultCursor(exc);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Consume(), exc);
VerifyError(result.Consume(), exc);
VerifyError(result.Consume(), exc);
}
[Fact]
public void ShouldErrorOnKeysRecordsAndButNotOnSummary()
{
var exc = new ClientException("some error");
var cursor = CreateFailingResultCursor(exc);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Keys(), exc);
VerifyError(result.Records(), exc);
VerifyNoError(result.Consume());
}
}
public class CursorFetchErrors : AbstractRxTest
{
[Fact]
public void ShouldReturnKeys()
{
var failure = new AuthenticationException("unauthenticated");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyKeys(result, "key01", "key02");
}
[Fact]
public void ShouldErrorOnRecords()
{
var keys = new[] {"key01", "key02"};
var failure = new DatabaseException("code", "message");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyRecordsAndError(result, keys, 5, failure);
}
[Fact]
public void ShouldErrorOnRecordsRepeatable()
{
var keys = new[] {"key01", "key02"};
var failure1 = new DatabaseException("code", "message");
var cursor = CreateFailingResultCursor(failure1, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyRecordsAndError(result, keys, 5, failure1);
VerifyResultConsumedError(result.Records());
VerifyResultConsumedError(result.Records());
}
[Fact]
public void ShouldErrorOnSummary()
{
var failure = new DatabaseException("code", "message");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Consume(), failure);
}
[Fact]
public void ShouldErrorOnSummaryRepeatable()
{
var failure = new DatabaseException("code", "message");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Consume(), failure);
VerifyError(result.Consume(), failure);
VerifyError(result.Consume(), failure);
}
[Fact]
public void ShouldErrorOnRecordsAndSummary()
{
var keys = new[] {"key01", "key02"};
var failure = new DatabaseException("code", "message");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyRecordsAndError(result, keys, 5, failure);
VerifyNoError(result.Consume());
}
}
public class CursorSummaryErrors : AbstractRxTest
{
[Fact]
public void ShouldReturnKeys()
{
var failure = new AuthenticationException("unauthenticated");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyKeys(result, "key01", "key02");
}
[Fact]
public void ShouldReturnRecords()
{
var keys = new[] {"key01", "key02"};
var failure = new DatabaseException("code", "message");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyRecordsAndError(result, keys, 5, failure);
}
[Fact]
public void ShouldErrorOnSummary()
{
var failure = new ClientException("some error");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Consume(), failure);
}
[Fact]
public void ShouldErrorOnSummaryRepeatable()
{
var failure = new ClientException("some error");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Consume(), failure);
VerifyError(result.Consume(), failure);
}
[Fact]
public void ShouldReturnKeysEvenAfterFailedSummary()
{
var failure = new AuthenticationException("unauthenticated");
var cursor = CreateFailingResultCursor(failure, 2, 5);
var result = new RxResult(Observable.Return(cursor));
VerifyError(result.Consume(), failure);
VerifyKeys(result, "key01", "key02");
}
}
internal static class RxResultUtil
{
public static IEnumerable<IRecord> CreateRecords(string[] fields, int recordCount, int delayMs = 0)
{
for (var i = 1; i <= recordCount; i++)
{
if (delayMs > 0)
{
Thread.Sleep(delayMs);
}
yield return new Record(fields,
Enumerable.Range(1, fields.Length).Select(f => $"{i:D3}_{f:D2}").Cast<object>().ToArray());
}
}
public static IInternalResultCursor CreateResultCursor(int keyCount, int recordCount,
string query = "fake", int delayMs = 0)
{
var fields = Enumerable.Range(1, keyCount).Select(f => $"key{f:D2}").ToArray();
var summaryBuilder =
new SummaryBuilder(new Query(query), new ServerInfo(new Uri("bolt://localhost")));
return new ListBasedRecordCursor(fields, () => CreateRecords(fields, recordCount, delayMs),
() => summaryBuilder.Build());
}
public static void VerifyKeys(IRxResult result, params string[] keys)
{
result.Keys()
.WaitForCompletion()
.AssertEqual(
OnNext(0, MatchesKeys(keys)),
OnCompleted<string[]>(0));
}
public static void VerifyRecords(IRxResult result, string[] keys, int recordsCount)
{
result.Records()
.WaitForCompletion()
.AssertEqual(
Enumerable.Range(1, recordsCount).Select(r =>
OnNext(0,
MatchesRecord(keys,
Enumerable.Range(1, keys.Length).Select(f => $"{r:D3}_{f:D2}").Cast<object>()
.ToArray())))
.Concat(new[] {OnCompleted<IRecord>(0)}));
}
public static void VerifyRecordsAndError(IRxResult result, string[] keys, int recordsCount,
Exception failure)
{
result.Records()
.WaitForCompletion()
.AssertEqual(
Enumerable.Range(1, recordsCount).Select(r =>
OnNext(0,
MatchesRecord(keys,
Enumerable.Range(1, keys.Length).Select(f => $"{r:D3}_{f:D2}").Cast<object>()
.ToArray())))
.Concat(new[] {OnError<IRecord>(0, failure)}));
}
public static void VerifySummary(IRxResult result, string query = "fake")
{
result.Consume()
.WaitForCompletion()
.AssertEqual(
OnNext(0,
MatchesSummary(new {Query = new Query(query)},
opts => opts.ExcludingMissingMembers())),
OnCompleted<IResultSummary>(0));
}
public static void VerifyError<T>(IObservable<T> observable, Exception exc)
{
observable.WaitForCompletion()
.AssertEqual(
OnError<T>(0, exc));
}
public static void VerifyResultConsumedError<T>(IObservable<T> observable)
{
observable.WaitForCompletion()
.AssertEqual(
OnError<T>(0,
MatchesException<ResultConsumedException>(e =>
e.Message.StartsWith("Streaming has already started and/or finished"))));
}
public static void VerifyNoError<T>(IObservable<T> observable)
{
observable
.WaitForCompletion()
.Should()
.NotContain(e => e.Value.Kind == NotificationKind.OnError).And
.Contain(e => e.Value.Kind == NotificationKind.OnCompleted);
}
public static IInternalResultCursor CreateFailingResultCursor(Exception exc)
{
var cursor = new Mock<IInternalResultCursor>();
cursor.Setup(x => x.KeysAsync()).ThrowsAsync(exc ?? throw new ArgumentNullException(nameof(exc)));
return cursor.Object;
}
public static IInternalResultCursor CreateFailingResultCursor(Exception exc, int keyCount,
int recordCount)
{
var keys = Enumerable.Range(1, keyCount).Select(f => $"key{f:D2}").ToArray();
IEnumerable<IRecord> GenerateRecords()
{
for (var r = 1; r <= recordCount; r++)
{
yield return new Record(keys,
Enumerable.Range(1, keyCount).Select(f => $"{r:D3}_{f:D2}").Cast<object>().ToArray());
}
throw exc;
}
return new ListBasedRecordCursor(keys, GenerateRecords);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor.Management
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AlertRuleIncidentsOperations operations.
/// </summary>
internal partial class AlertRuleIncidentsOperations : IServiceOperations<MonitorManagementClient>, IAlertRuleIncidentsOperations
{
/// <summary>
/// Initializes a new instance of the AlertRuleIncidentsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AlertRuleIncidentsOperations(MonitorManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorManagementClient
/// </summary>
public MonitorManagementClient Client { get; private set; }
/// <summary>
/// Gets an incident associated to an alert rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='incidentName'>
/// The name of the incident to retrieve.
/// </param>
/// <param name='customHeaders'>
/// 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="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Incident>> GetWithHttpMessagesAsync(string resourceGroupName, string ruleName, string incidentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (incidentName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "incidentName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-01";
// 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("ruleName", ruleName);
tracingParameters.Add("incidentName", incidentName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents/{incidentName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{incidentName}", System.Uri.EscapeDataString(incidentName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Incident>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Incident>(_responseContent, 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>
/// Gets a list of incidents associated to an alert rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<Incident>>> ListByAlertRuleWithHttpMessagesAsync(string resourceGroupName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-01";
// 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("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByAlertRule", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await 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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, 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<IEnumerable<Incident>>();
_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 = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Incident>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class SessionMessageHeaderEncoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 1;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private SessionMessageHeaderEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public SessionMessageHeaderEncoder()
{
_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 IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public SessionMessageHeaderEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public SessionMessageHeaderEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public SessionMessageHeaderEncoder LeadershipTermId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int ClusterSessionIdEncodingOffset()
{
return 8;
}
public static int ClusterSessionIdEncodingLength()
{
return 8;
}
public static long ClusterSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ClusterSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ClusterSessionIdMaxValue()
{
return 9223372036854775807L;
}
public SessionMessageHeaderEncoder ClusterSessionId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int TimestampEncodingOffset()
{
return 16;
}
public static int TimestampEncodingLength()
{
return 8;
}
public static long TimestampNullValue()
{
return -9223372036854775808L;
}
public static long TimestampMinValue()
{
return -9223372036854775807L;
}
public static long TimestampMaxValue()
{
return 9223372036854775807L;
}
public SessionMessageHeaderEncoder Timestamp(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
SessionMessageHeaderDecoder writer = new SessionMessageHeaderDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace SpritesAndBones.Editor
{
// Editor window for replacing all sprites in animation clips
public class ReplaceSpritesInClip : EditorWindow
{
// The original sprite's text you want to replace
private string originalSpriteText = "";
// The sprite's text you want to change to
private string replaceSpriteText = "";
// Bool to track if the button was pushed
private bool changeAllSprites = false;
private static int columnWidth = 300;
// Sprites of the clip
private Sprite[] sprites;
// Animation clips selected to change
private List<AnimationClip> animationClips;
// Current scroll position
private Vector2 scrollPos = Vector2.zero;
// Re-initialize animation clips on creation
public ReplaceSpritesInClip()
{
animationClips = new List<AnimationClip>();
}
// On changing the selection update the animation clips to change
private void OnSelectionChange()
{
if (Selection.objects.Length > 1)
{
Debug.Log("Length? " + Selection.objects.Length);
animationClips.Clear();
foreach (Object o in Selection.objects)
{
if (o is AnimationClip) animationClips.Add((AnimationClip)o);
}
}
else if (Selection.activeObject is AnimationClip)
{
animationClips.Clear();
animationClips.Add((AnimationClip)Selection.activeObject);
}
else
{
animationClips.Clear();
}
this.Repaint();
}
[MenuItem("Window/Animation Replace Sprites")]
private static void Init()
{
GetWindow(typeof(ReplaceSpritesInClip));
}
public void OnGUI()
{
// Make sure there is at least one animation clip selected
if (animationClips.Count > 0)
{
scrollPos = GUILayout.BeginScrollView(scrollPos, GUIStyle.none);
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Animation Clip:", GUILayout.Width(columnWidth));
if (animationClips.Count == 1)
{
animationClips[0] = ((AnimationClip)EditorGUILayout.ObjectField(
animationClips[0],
typeof(AnimationClip),
true,
GUILayout.Width(columnWidth))
);
}
else
{
GUILayout.Label("Multiple Anim Clips: " + animationClips.Count, GUILayout.Width(columnWidth));
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(20);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Sprites:");
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Original Sprite Text:", GUILayout.Width(columnWidth));
GUILayout.Label("Replacement Sprite Text:", GUILayout.Width(columnWidth));
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
originalSpriteText = EditorGUILayout.TextField(originalSpriteText, GUILayout.Width(columnWidth));
replaceSpriteText = EditorGUILayout.TextField(replaceSpriteText, GUILayout.Width(columnWidth));
if (GUILayout.Button("Replace All Sprites"))
{
changeAllSprites = true;
}
EditorGUILayout.EndHorizontal();
// Iterate through the animation clips
foreach (AnimationClip clip in animationClips)
{
// Iterate through the bindings for the current animation clip
foreach (var binding in AnimationUtility.GetObjectReferenceCurveBindings(clip))
{
// If the binding is a sprite type then get the keyframes
if (binding.propertyName == "m_Sprite")
{
// Get the keyframes for this sprite
ObjectReferenceKeyframe[] keyframes = AnimationUtility.GetObjectReferenceCurve(clip, binding);
// Show the sprite's path and the keyframes length for this binding
EditorGUILayout.LabelField(binding.path + "/" + binding.propertyName + ", Keys: " + keyframes.Length);
// Loop through the keyframes to change the sprite
for (int i = 0; i < keyframes.Length; i++)
{
// If the button is pushed then change the sprite
if (changeAllSprites)
{
// The keyframe's value is the sprite
Sprite keyframeSprite = (Sprite)keyframes[i].value;
// If the sprite exists get the name of the sprite
if (keyframeSprite != null)
{
string spriteName = keyframeSprite.name;
// Replace the text in the sprite's name to the replacement text
string newSpriteName = spriteName.Replace(originalSpriteText, replaceSpriteText);
Debug.Log(newSpriteName);
// Get all the sprites in the project
GetAllSprites();
// Make sure we have at least one sprite
if (sprites.Length > 0)
{
// Loop through all the sprites to get the one matching the new sprite name
foreach (Sprite sprite in sprites)
{
if (sprite != null && sprite.name == newSpriteName)
{
// Cache the time for this keyframe
float timeForKey = keyframes[i].time;
// Create a new ObjectReferenceKeyframe for the sprite
keyframes[i] = new ObjectReferenceKeyframe();
// set the time
keyframes[i].time = timeForKey;
// set reference for the sprite you want
keyframes[i].value = sprite;
// Set the new keyframes to the binding of the animation clip
AnimationUtility.SetObjectReferenceCurve(clip, binding, keyframes);
Debug.Log("Sprite changed to " + sprite.name);
// Break the loop since we already found it
break;
}
}
}
}
}
// Show the sprite in the editor window
EditorGUILayout.ObjectField(keyframes[i].value, typeof(Sprite), false);
}
}
}
}
// Reset the button if pushed
changeAllSprites = false;
GUILayout.Space(40);
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("Please select an Animation Clip");
}
}
private void OnInspectorUpdate()
{
this.Repaint();
}
// Get all the sprites in the project
private void GetAllSprites()
{
// Possible file extensions for the sprite images
string[] extensions = new string[] { ".png", ".psd", ".jpg", ".bmp" };
// Get all the files with those extensions
string[] files = AssetDatabase.GetAllAssetPaths().Where(x => extensions.Contains(System.IO.Path.GetExtension(x))).ToArray();
// Create a sprite list and add sprites to this list
List<Sprite> spriteList = new List<Sprite>();
foreach (string filename in files)
{
Object[] objects = AssetDatabase.LoadAllAssetRepresentationsAtPath(filename);
spriteList.AddRange(objects.Select(x => (x as Sprite)).ToList());
}
// Convert the list to an array for this window to use
sprites = spriteList.ToArray();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
private partial class WorkCoordinator
{
private const int MinimumDelayInMS = 50;
private readonly Registration _registration;
private readonly LogAggregator _logAggregator;
private readonly IAsynchronousOperationListener _listener;
private readonly IOptionService _optionService;
private readonly CancellationTokenSource _shutdownNotificationSource;
private readonly CancellationToken _shutdownToken;
private readonly SimpleTaskQueue _eventProcessingQueue;
// points to processor task
private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor;
private readonly SemanticChangeProcessor _semanticChangeProcessor;
public WorkCoordinator(
IAsynchronousOperationListener listener,
IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
Registration registration)
{
_logAggregator = new LogAggregator();
_registration = registration;
_listener = listener;
_optionService = _registration.GetService<IOptionService>();
_optionService.OptionChanged += OnOptionChanged;
// event and worker queues
_shutdownNotificationSource = new CancellationTokenSource();
_shutdownToken = _shutdownNotificationSource.Token;
_eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default);
var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS);
var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS);
var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS);
_documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor(
listener, analyzerProviders, _registration,
activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken);
var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS);
var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS);
_semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken);
// if option is on
if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
}
public int CorrelationId
{
get { return _registration.CorrelationId; }
}
public void Shutdown(bool blockingShutdown)
{
_optionService.OptionChanged -= OnOptionChanged;
// detach from the workspace
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
// cancel any pending blocks
_shutdownNotificationSource.Cancel();
_documentAndProjectWorkerProcessor.Shutdown();
SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator);
if (blockingShutdown)
{
var shutdownTask = Task.WhenAll(
_eventProcessingQueue.LastScheduledTask,
_documentAndProjectWorkerProcessor.AsyncProcessorTask,
_semanticChangeProcessor.AsyncProcessorTask);
shutdownTask.Wait(TimeSpan.FromSeconds(5));
if (!shutdownTask.IsCompleted)
{
SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId);
}
}
}
private void OnOptionChanged(object sender, OptionChangedEventArgs e)
{
// if solution crawler got turned off or on.
if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler)
{
var value = (bool)e.Value;
if (value)
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
else
{
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
}
SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value);
return;
}
// TODO: remove this once prototype is done
// it is here just because it was convenient to add per workspace option change monitoring
// for incremental analyzer
if (e.Option == Diagnostics.InternalDiagnosticsOptions.UseDiagnosticEngineV2)
{
_documentAndProjectWorkerProcessor.ChangeDiagnosticsEngine((bool)e.Value);
}
ReanalyzeOnOptionChange(sender, e);
}
private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e)
{
// otherwise, let each analyzer decide what they want on option change
ISet<DocumentId> set = null;
foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers)
{
if (analyzer.NeedsReanalysisOnOptionChanged(sender, e))
{
set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet();
this.Reanalyze(analyzer, set);
}
}
}
public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority = false)
{
var asyncToken = _listener.BeginAsyncOperation("Reanalyze");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(analyzer, documentIds, highPriority), _shutdownToken).CompletesAsyncOperation(asyncToken);
SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds, highPriority);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
// guard us from cancellation
try
{
ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged"));
}
catch (OperationCanceledException oce)
{
if (NotOurShutdownToken(oce))
{
throw;
}
// it is our cancellation, ignore
}
catch (AggregateException ae)
{
ae = ae.Flatten();
// If we had a mix of exceptions, don't eat it
if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) ||
ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken))
{
// We had a cancellation with a different token, so don't eat it
throw;
}
// it is our cancellation, ignore
}
}
private bool NotOurShutdownToken(OperationCanceledException oce)
{
return oce.CancellationToken == _shutdownToken;
}
private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken)
{
SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind);
// TODO: add telemetry that record how much it takes to process an event (max, min, average and etc)
switch (args.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
ProcessSolutionEvent(args, asyncToken);
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectRemoved:
ProcessProjectEvent(args, asyncToken);
break;
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
ProcessDocumentEvent(args, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnDocumentOpened(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnDocumentClosed(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.DocumentAdded:
EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.DocumentRemoved:
EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken);
break;
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
// If an additional file has changed we need to reanalyze the entire project.
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.ProjectAdded:
OnProjectAdded(e.NewSolution.GetProject(e.ProjectId));
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.ProjectRemoved:
EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
OnSolutionAdded(e.NewSolution);
EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.SolutionRemoved:
EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionCleared:
EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnSolutionAdded(Solution solution)
{
// first make sure full solution analysis is on.
_optionService.SetOptions(solution.Workspace.Options.WithChangedOption(RuntimeOptions.FullSolutionAnalysis, true));
var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(solution);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnProjectAdded(Project project)
{
var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(project);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken)
{
// document changed event is the special one.
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null)
{
// we are shutting down
_shutdownToken.ThrowIfCancellationRequested();
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var currentMember = GetSyntaxPath(changedMember);
// call to this method is serialized. and only this method does the writing.
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(document.Id, document.Project.Language, invocationReasons,
isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem")));
// enqueue semantic work planner
if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
// must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later.
// due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual.
_semanticChangeProcessor.Enqueue(document, currentMember);
}
}
private SyntaxPath GetSyntaxPath(SyntaxNode changedMember)
{
// using syntax path might be too expansive since it will be created on every keystroke.
// but currently, we have no other way to track a node between two different tree (even for incrementally parsed one)
if (changedMember == null)
{
return null;
}
return new SyntaxPath(changedMember);
}
private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons)
{
foreach (var documentId in project.DocumentIds)
{
var document = project.GetDocument(documentId);
await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority)
{
var solution = _registration.CurrentSolution;
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
if (document == null)
{
continue;
}
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze;
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, document.Project.Language, invocationReasons,
isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem")));
}
}
private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
// TODO: Async version for GetXXX methods?
foreach (var addedProject in solutionChanges.GetAddedProjects())
{
await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedProject in solutionChanges.GetRemovedProjects())
{
await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges)
{
await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false);
foreach (var addedDocumentId in projectChanges.GetAddedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId))
.ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedDocumentId in projectChanges.GetRemovedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges)
{
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
// TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document?
var projectConfigurationChange = InvocationReasons.Empty;
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged);
}
if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() ||
projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() ||
!object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) ||
!object.Equals(oldProject.AssemblyName, newProject.AssemblyName) ||
!object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged);
}
if (!projectConfigurationChange.IsEmpty)
{
await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument)
{
var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>();
if (differenceService != null)
{
var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false);
if (differenceResult != null)
{
await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false);
}
}
}
private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons)
{
var document = solution.GetDocument(documentId);
return EnqueueWorkItemAsync(document, invocationReasons);
}
private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons)
{
var project = solution.GetProject(projectId);
return EnqueueWorkItemAsync(project, invocationReasons);
}
private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons)
{
foreach (var projectId in solution.ProjectIds)
{
await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId)
{
var oldProject = oldSolution.GetProject(projectId);
var newProject = newSolution.GetProject(projectId);
await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false);
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId)
{
var oldProject = oldSolution.GetProject(documentId.ProjectId);
var newProject = newSolution.GetProject(documentId.ProjectId);
await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers)
{
var solution = _registration.CurrentSolution;
var list = new List<WorkItem>();
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, EmptyAsyncToken.Instance));
}
}
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Xunit;
namespace System
{
public static partial class PlatformDetection
{
public static Version OSXVersion => throw new PlatformNotSupportedException();
public static bool IsSuperUser => throw new PlatformNotSupportedException();
public static bool IsOpenSUSE => false;
public static bool IsUbuntu => false;
public static bool IsDebian => false;
public static bool IsDebian8 => false;
public static bool IsUbuntu1404 => false;
public static bool IsUbuntu1604 => false;
public static bool IsUbuntu1704 => false;
public static bool IsUbuntu1710 => false;
public static bool IsTizen => false;
public static bool IsNotFedoraOrRedHatFamily => true;
public static bool IsFedora => false;
public static bool IsWindowsNanoServer => (IsNotWindowsIoTCore && GetInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase));
public static bool IsWindowsServerCore => GetInstallationType().Equals("Server Core", StringComparison.OrdinalIgnoreCase);
public static int WindowsVersion => GetWindowsVersion();
public static bool IsMacOsHighSierraOrHigher { get; } = false;
public static Version ICUVersion => new Version(0, 0, 0, 0);
public static bool IsRedHatFamily => false;
public static bool IsNotRedHatFamily => true;
public static bool IsRedHatFamily6 => false;
public static bool IsRedHatFamily7 => false;
public static bool IsNotRedHatFamily6 => true;
public static bool IsWindows10Version1607OrGreater =>
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393;
public static bool IsWindows10Version1703OrGreater =>
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063;
public static bool IsWindows10Version1709OrGreater =>
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16299;
// Windows OneCoreUAP SKU doesn't have httpapi.dll
public static bool IsNotOneCoreUAP =>
File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll"));
public static bool IsWindowsIoTCore
{
get
{
int productType = GetWindowsProductType();
if ((productType == PRODUCT_IOTUAPCOMMERCIAL) ||
(productType == PRODUCT_IOTUAP))
{
return true;
}
return false;
}
}
public static bool IsWindows => true;
public static bool IsWindows7 => GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1;
public static bool IsWindows8x => GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3);
public static bool IsNetfx462OrNewer()
{
if (!IsFullFramework)
{
return false;
}
Version net462 = new Version(4, 6, 2);
Version runningVersion = GetFrameworkVersion();
return runningVersion != null && runningVersion >= net462;
}
public static bool IsNetfx470OrNewer()
{
if (!IsFullFramework)
{
return false;
}
Version net470 = new Version(4, 7, 0);
Version runningVersion = GetFrameworkVersion();
return runningVersion != null && runningVersion >= net470;
}
public static bool IsNetfx471OrNewer()
{
if (!IsFullFramework)
{
return false;
}
Version net471 = new Version(4, 7, 1);
Version runningVersion = GetFrameworkVersion();
return runningVersion != null && runningVersion >= net471;
}
private static Version GetFrameworkVersion()
{
string[] descriptionArray = RuntimeInformation.FrameworkDescription.Split(' ');
if (descriptionArray.Length < 3)
return null;
if (!Version.TryParse(descriptionArray[2], out Version actualVersion))
return null;
foreach (Range currentRange in FrameworkRanges)
{
if (currentRange.IsInRange(actualVersion))
return currentRange.FrameworkVersion;
}
return null;
}
public static string GetDistroVersionString() { return "ProductType=" + GetWindowsProductType() + "InstallationType=" + GetInstallationType(); }
private static int s_isInAppContainer = -1;
public static bool IsInAppContainer
{
// This actually checks whether code is running in a modern app.
// Currently this is the only situation where we run in app container.
// If we want to distinguish the two cases in future,
// EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token.
get
{
if (s_isInAppContainer != -1)
return s_isInAppContainer == 1;
if (!IsWindows || IsWindows7)
{
s_isInAppContainer = 0;
return false;
}
byte[] buffer = new byte[0];
uint bufferSize = 0;
try
{
int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer);
switch (result)
{
case 15703: // APPMODEL_ERROR_NO_APPLICATION
s_isInAppContainer = 0;
break;
case 0: // ERROR_SUCCESS
case 122: // ERROR_INSUFFICIENT_BUFFER
// Success is actually insufficent buffer as we're really only looking for
// not NO_APPLICATION and we're not actually giving a buffer here. The
// API will always return NO_APPLICATION if we're not running under a
// WinRT process, no matter what size the buffer is.
s_isInAppContainer = 1;
break;
default:
throw new InvalidOperationException($"Failed to get AppId, result was {result}.");
}
}
catch (Exception e)
{
// We could catch this here, being friendly with older portable surface area should we
// desire to use this method elsewhere.
if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal))
{
// API doesn't exist, likely pre Win8
s_isInAppContainer = 0;
}
else
{
throw;
}
}
return s_isInAppContainer == 1;
}
}
private static int s_isWindowsElevated = -1;
public static bool IsWindowsAndElevated
{
get
{
if (s_isWindowsElevated != -1)
return s_isWindowsElevated == 1;
if (!IsWindows || IsInAppContainer)
{
s_isWindowsElevated = 0;
return false;
}
IntPtr processToken;
Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken));
try
{
uint tokenInfo;
uint returnLength;
Assert.True(GetTokenInformation(
processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength));
s_isWindowsElevated = tokenInfo == 0 ? 0 : 1;
}
finally
{
CloseHandle(processToken);
}
return s_isWindowsElevated == 1;
}
}
private static string GetInstallationType()
{
string key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion";
string value = "";
try
{
value = (string)Registry.GetValue(key, "InstallationType", defaultValue: "");
}
catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is PlatformNotSupportedException /* UAP */)
{
}
return value;
}
private static int GetWindowsProductType()
{
Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out int productType));
return productType;
}
private static int GetWindowsMinorVersion()
{
RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
Assert.Equal(0, RtlGetVersion(out osvi));
return (int)osvi.dwMinorVersion;
}
private static int GetWindowsBuildNumber()
{
RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
Assert.Equal(0, RtlGetVersion(out osvi));
return (int)osvi.dwBuildNumber;
}
private const uint TokenElevation = 20;
private const uint STANDARD_RIGHTS_READ = 0x00020000;
private const uint TOKEN_QUERY = 0x0008;
private const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY;
[DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)]
private static extern bool GetTokenInformation(
IntPtr TokenHandle,
uint TokenInformationClass,
out uint TokenInformation,
uint TokenInformationLength,
out uint ReturnLength);
private const int PRODUCT_IOTUAP = 0x0000007B;
private const int PRODUCT_IOTUAPCOMMERCIAL = 0x00000083;
[DllImport("kernel32.dll", SetLastError = false)]
private static extern bool GetProductInfo(
int dwOSMajorVersion,
int dwOSMinorVersion,
int dwSpMajorVersion,
int dwSpMinorVersion,
out int pdwReturnedProductType
);
[DllImport("ntdll.dll")]
private static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation);
[StructLayout(LayoutKind.Sequential)]
private struct RTL_OSVERSIONINFOEX
{
internal uint dwOSVersionInfoSize;
internal uint dwMajorVersion;
internal uint dwMinorVersion;
internal uint dwBuildNumber;
internal uint dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal string szCSDVersion;
}
private static int GetWindowsVersion()
{
RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
Assert.Equal(0, RtlGetVersion(out osvi));
return (int)osvi.dwMajorVersion;
}
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
// The process handle does NOT need closing
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetCurrentProcess();
}
}
| |
// 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: Abstract base class for all Streams. Provides
** default implementations of asynchronous reads & writes, in
** terms of the synchronous reads & writes (and vice versa).
**
**
===========================================================*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace System.IO {
[Serializable]
[ComVisible(true)]
#if FEATURE_REMOTING
public abstract class Stream : MarshalByRefObject, IDisposable {
#else // FEATURE_REMOTING
public abstract class Stream : IDisposable {
#endif // FEATURE_REMOTING
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int _DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
[NonSerialized]
private ReadWriteTask _activeReadWriteTask;
[NonSerialized]
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead {
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek {
[Pure]
get;
}
[ComVisible(false)]
public virtual bool CanTimeout {
[Pure]
get {
return false;
}
}
public abstract bool CanWrite {
[Pure]
get;
}
public abstract long Length {
get;
}
public abstract long Position {
get;
set;
}
[ComVisible(false)]
public virtual int ReadTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
set {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
}
[ComVisible(false)]
public virtual int WriteTimeout {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
set {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
}
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task CopyToAsync(Stream destination)
{
return CopyToAsync(destination, _DefaultCopyBufferSize);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task CopyToAsync(Stream destination, Int32 bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
ValidateCopyToArguments(destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Contract.Requires(destination != null);
Contract.Requires(bufferSize > 0);
Contract.Requires(CanRead);
Contract.Requires(destination.CanWrite);
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
{
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
CopyTo(destination, _DefaultCopyBufferSize);
}
public void CopyTo(Stream destination, int bufferSize)
{
ValidateCopyToArguments(destination, bufferSize);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
destination.Write(buffer, 0, read);
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup starting in V2.
public virtual void Close()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
/* These are correct, but we'd have to fix PipeStream & NetworkStream very carefully.
Contract.Ensures(CanRead == false);
Contract.Ensures(CanWrite == false);
Contract.Ensures(CanSeek == false);
*/
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public abstract void Flush();
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
Contract.Ensures(Contract.Result<WaitHandle>() != null);
return new ManualResetEvent(false);
}
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
[HostProtection(ExternalThreading = true)]
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanRead) __Error.ReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync();
}
else
{
semaphore.Wait();
}
// Create the task to asynchronously do a Read. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Read.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Read and return the number of bytes read
return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
var readTask = _activeReadWriteTask;
if (readTask == null)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
else if (readTask != asyncResult)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
else if (!readTask._isRead)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
FinishTrackingAsyncOperation();
}
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task<int> ReadAsync(Byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndRead())
{
// If the Stream does not override Begin/EndRead, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<Int32>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
}
private struct ReadWriteParameters // struct for arguments to Read and Write calls
{
internal byte[] Buffer;
internal int Offset;
internal int Count;
}
[HostProtection(ExternalThreading=true)]
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
[HostProtection(ExternalThreading = true)]
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanWrite) __Error.WriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
}
else
{
semaphore.Wait(); // synchronously wait here
}
// Create the task to asynchronously do a Write. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Write.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Contract.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Write
thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Contract.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
// preconditions in async methods that await.
Contract.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
Contract.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) => {
Contract.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Contract.Requires(readWriteTask != null);
Contract.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
// two interlocked operations. However, if ReadWriteTask is ever changed to use
// a cancellation token, this should be changed to use Start.
_activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
readWriteTask.m_taskScheduler = TaskScheduler.Default;
readWriteTask.ScheduleAndStart(needsProtection: false);
}
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
Contract.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult==null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
else if (writeTask != asyncResult)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
else if (writeTask._isRead)
{
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Contract.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
FinishTrackingAsyncOperation();
}
}
// Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
// A single instance of this task serves four purposes:
// 1. The work item scheduled to run the Read / Write operation
// 2. The state holding the arguments to be passed to Read / Write
// 3. The IAsyncResult returned from BeginRead / BeginWrite
// 4. The completion action that runs to invoke the user-provided callback.
// This last item is a bit tricky. Before the AsyncCallback is invoked, the
// IAsyncResult must have completed, so we can't just invoke the handler
// from within the task, since it is the IAsyncResult, and thus it's not
// yet completed. Instead, we use AddCompletionAction to install this
// task as its own completion handler. That saves the need to allocate
// a separate completion handler, it guarantees that the task will
// have completed by the time the handler is invoked, and it allows
// the handler to be invoked synchronously upon the completion of the
// task. This all enables BeginRead / BeginWrite to be implemented
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
internal byte [] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
private ExecutionContext _context;
internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
{
_stream = null;
_buffer = null;
}
[SecuritySafeCritical] // necessary for EC.Capture
[MethodImpl(MethodImplOptions.NoInlining)]
public ReadWriteTask(
bool isRead,
bool apm,
Func<object,int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
Contract.Requires(function != null);
Contract.Requires(stream != null);
Contract.Requires(buffer != null);
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// Store the arguments
_isRead = isRead;
_apm = apm;
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
// If a callback was provided, we need to:
// - Store the user-provided handler
// - Capture an ExecutionContext under which to invoke the handler
// - Add this task as its own completion handler so that the Invoke method
// will run the callback when this task completes.
if (callback != null)
{
_callback = callback;
_context = ExecutionContext.Capture(ref stackMark,
ExecutionContext.CaptureOptions.OptimizeDefaultCase | ExecutionContext.CaptureOptions.IgnoreSyncCtx);
base.AddCompletionAction(this);
}
}
[SecurityCritical] // necessary for CoreCLR
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
var callback = rwc._callback;
rwc._callback = null;
callback(rwc);
}
[SecurityCritical] // necessary for CoreCLR
private static ContextCallback s_invokeAsyncCallback;
[SecuritySafeCritical] // necessary for ExecutionContext.Run
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
else
{
_context = null;
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
using(context) ExecutionContext.Run(context, invokeAsyncCallback, this, true);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task WriteAsync(Byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
[System.Security.SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count)
{
if (!HasOverriddenBeginEndWrite())
{
// If the Stream does not override Begin/EndWrite, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default(VoidTaskResult);
});
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read([In, Out] byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < 256);
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r==0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
[HostProtection(Synchronization=true)]
public static Stream Synchronized(Stream stream)
{
if (stream==null)
throw new ArgumentNullException("stream");
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try {
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
catch (IOException ex) {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
if (callback != null) {
callback(asyncResult);
}
return asyncResult;
}
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
Contract.Ensures(Contract.Result<int>() >= 0);
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try {
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
catch (IOException ex) {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
if (callback != null) {
callback(asyncResult);
}
return asyncResult;
}
internal static void BlockingEndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
internal void ValidateCopyToArguments(Stream destination, int bufferSize)
{
if (destination == null)
throw new ArgumentNullException("destination");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
if (!CanRead && !CanWrite)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
if (!destination.CanRead && !destination.CanWrite)
throw new ObjectDisposedException("destination", Environment.GetResourceString("ObjectDisposed_StreamClosed"));
if (!CanRead)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
if (!destination.CanWrite)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
Contract.EndContractBlock();
}
[Serializable]
private sealed class NullStream : Stream
{
internal NullStream() {}
public override bool CanRead {
[Pure]
get { return true; }
}
public override bool CanWrite {
[Pure]
get { return true; }
}
public override bool CanSeek {
[Pure]
get { return true; }
}
public override long Length {
get { return 0; }
}
public override long Position {
get { return 0; }
set {}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
ValidateCopyToArguments(destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
[HostProtection(ExternalThreading = true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanRead) __Error.ReadNotSupported();
return BlockingBeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
return BlockingEndRead(asyncResult);
}
[HostProtection(ExternalThreading = true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!CanWrite) __Error.WriteNotSupported();
return BlockingBeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
BlockingEndWrite(asyncResult);
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
return 0;
}
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var nullReadTask = s_nullReadTask;
if (nullReadTask == null)
s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition
return nullReadTask;
}
private static Task<int> s_nullReadTask;
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
internal sealed class SynchronousAsyncResult : IAsyncResult {
private readonly Object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
private bool _endXxxCalled;
private Int32 _bytesRead;
internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) {
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
internal SynchronousAsyncResult(Object asyncStateObject) {
_stateObject = asyncStateObject;
_isWrite = true;
}
internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) {
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
_isWrite = isWrite;
}
public bool IsCompleted {
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
public WaitHandle AsyncWaitHandle {
get {
return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
public Object AsyncState {
get { return _stateObject; }
}
public bool CompletedSynchronously {
get { return true; }
}
internal void ThrowIfError() {
if (_exceptionInfo != null)
_exceptionInfo.Throw();
}
internal static Int32 EndRead(IAsyncResult asyncResult) {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndReadCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
return ar._bytesRead;
}
internal static void EndWrite(IAsyncResult asyncResult) {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || !ar._isWrite)
__Error.WrongAsyncResult();
if (ar._endXxxCalled)
__Error.EndWriteCalledTwice();
ar._endXxxCalled = true;
ar.ThrowIfError();
}
} // class SynchronousAsyncResult
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
[Serializable]
internal sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
Contract.EndContractBlock();
_stream = stream;
}
public override bool CanRead {
[Pure]
get { return _stream.CanRead; }
}
public override bool CanWrite {
[Pure]
get { return _stream.CanWrite; }
}
public override bool CanSeek {
[Pure]
get { return _stream.CanSeek; }
}
[ComVisible(false)]
public override bool CanTimeout {
[Pure]
get {
return _stream.CanTimeout;
}
}
public override long Length {
get {
lock(_stream) {
return _stream.Length;
}
}
}
public override long Position {
get {
lock(_stream) {
return _stream.Position;
}
}
set {
lock(_stream) {
_stream.Position = value;
}
}
}
[ComVisible(false)]
public override int ReadTimeout {
get {
return _stream.ReadTimeout;
}
set {
_stream.ReadTimeout = value;
}
}
[ComVisible(false)]
public override int WriteTimeout {
get {
return _stream.WriteTimeout;
}
set {
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock(_stream) {
try {
_stream.Close();
}
finally {
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock(_stream) {
try {
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally {
base.Dispose(disposing);
}
}
}
public override void Flush()
{
lock(_stream)
_stream.Flush();
}
public override int Read([In, Out]byte[] bytes, int offset, int count)
{
lock(_stream)
return _stream.Read(bytes, offset, count);
}
public override int ReadByte()
{
lock(_stream)
return _stream.ReadByte();
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
lock (_stream)
{
// If the Stream does have its own BeginRead implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginRead ?
_stream.BeginRead(buffer, offset, count, callback, state) :
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
lock(_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock(_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock(_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock(_stream)
_stream.Write(bytes, offset, count);
}
public override void WriteByte(byte b)
{
lock(_stream)
_stream.WriteByte(b);
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
lock (_stream)
{
// If the Stream does have its own BeginWrite implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginWrite ?
_stream.BeginWrite(buffer, offset, count, callback, state) :
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
lock(_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
// 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.ComponentModel;
using System.IO;
using System.IO.Pipes;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// Named Pipe connection handle
/// </summary>
internal class SNINpHandle : SNIHandle
{
internal const string DefaultPipePath = @"sql\query"; // e.g. \\HOSTNAME\pipe\sql\query
private const int MAX_PIPE_INSTANCES = 255;
private readonly string _targetServer;
private readonly object _callbackObject;
private readonly TaskScheduler _writeScheduler;
private readonly TaskFactory _writeTaskFactory;
private Stream _stream;
private NamedPipeClientStream _pipeStream;
private SslOverTdsStream _sslOverTdsStream;
private SslStream _sslStream;
private SNIAsyncCallback _receiveCallback;
private SNIAsyncCallback _sendCallback;
private bool _validateCert = true;
private readonly uint _status = TdsEnums.SNI_UNINITIALIZED;
private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE;
private readonly Guid _connectionId = Guid.NewGuid();
public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject)
{
_targetServer = serverName;
_callbackObject = callbackObject;
_writeScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
_writeTaskFactory = new TaskFactory(_writeScheduler);
try
{
_pipeStream = new NamedPipeClientStream(
serverName,
pipeName,
PipeDirection.InOut,
PipeOptions.Asynchronous | PipeOptions.WriteThrough);
bool isInfiniteTimeOut = long.MaxValue == timerExpire;
if (isInfiniteTimeOut)
{
_pipeStream.Connect(Threading.Timeout.Infinite);
}
else
{
TimeSpan ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
_pipeStream.Connect((int)ts.TotalMilliseconds);
}
}
catch(TimeoutException te)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te);
_status = TdsEnums.SNI_ERROR;
return;
}
catch(IOException ioe)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe);
_status = TdsEnums.SNI_ERROR;
return;
}
if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty);
_status = TdsEnums.SNI_ERROR;
return;
}
_sslOverTdsStream = new SslOverTdsStream(_pipeStream);
_sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
_stream = _pipeStream;
_status = TdsEnums.SNI_SUCCESS;
}
public override Guid ConnectionId
{
get
{
return _connectionId;
}
}
public override uint Status
{
get
{
return _status;
}
}
public override uint CheckConnection()
{
if (!_stream.CanWrite || !_stream.CanRead)
{
return TdsEnums.SNI_ERROR;
}
else
{
return TdsEnums.SNI_SUCCESS;
}
}
public override void Dispose()
{
lock (this)
{
if (_sslOverTdsStream != null)
{
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
}
if (_sslStream != null)
{
_sslStream.Dispose();
_sslStream = null;
}
if (_pipeStream != null)
{
_pipeStream.Dispose();
_pipeStream = null;
}
//Release any references held by _stream.
_stream = null;
}
}
public override uint Receive(out SNIPacket packet, int timeout)
{
lock (this)
{
packet = null;
try
{
packet = new SNIPacket(null);
packet.Allocate(_bufferSize);
packet.ReadFromStream(_stream);
if (packet.Length == 0)
{
var e = new Win32Exception();
return ReportErrorAndReleasePacket(packet, (uint)e.NativeErrorCode, 0, e.Message);
}
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (IOException ioe)
{
return ReportErrorAndReleasePacket(packet, ioe);
}
return TdsEnums.SNI_SUCCESS;
}
}
public override uint ReceiveAsync(ref SNIPacket packet)
{
lock (this)
{
packet = new SNIPacket(null);
packet.Allocate(_bufferSize);
try
{
packet.ReadFromStreamAsync(_stream, _receiveCallback);
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (IOException ioe)
{
return ReportErrorAndReleasePacket(packet, ioe);
}
}
}
public override uint Send(SNIPacket packet)
{
lock (this)
{
try
{
packet.WriteToStream(_stream);
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
return ReportErrorAndReleasePacket(packet, ode);
}
catch (IOException ioe)
{
return ReportErrorAndReleasePacket(packet, ioe);
}
}
}
public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null)
{
SNIPacket newPacket = packet;
_writeTaskFactory.StartNew(() =>
{
try
{
lock (this)
{
packet.WriteToStream(_stream);
}
}
catch (Exception e)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, e);
if (callback != null)
{
callback(packet, TdsEnums.SNI_ERROR);
}
else
{
_sendCallback(packet, TdsEnums.SNI_ERROR);
}
return;
}
if (callback != null)
{
callback(packet, TdsEnums.SNI_SUCCESS);
}
else
{
_sendCallback(packet, TdsEnums.SNI_SUCCESS);
}
});
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
{
_receiveCallback = receiveCallback;
_sendCallback = sendCallback;
}
public override uint EnableSsl(uint options)
{
_validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
try
{
_sslStream.AuthenticateAsClientAsync(_targetServer).GetAwaiter().GetResult();
_sslOverTdsStream.FinishHandshake();
}
catch (AuthenticationException aue)
{
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, aue);
}
catch (InvalidOperationException ioe)
{
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, ioe);
}
_stream = _sslStream;
return TdsEnums.SNI_SUCCESS;
}
public override void DisableSsl()
{
_sslStream.Dispose();
_sslStream = null;
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
_stream = _pipeStream;
}
/// <summary>
/// Validate server certificate
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="cert">X.509 certificate</param>
/// <param name="chain">X.509 chain</param>
/// <param name="policyErrors">Policy errors</param>
/// <returns>true if valid</returns>
private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
if (!_validateCert)
{
return true;
}
return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors);
}
/// <summary>
/// Set buffer size
/// </summary>
/// <param name="bufferSize">Buffer size</param>
public override void SetBufferSize(int bufferSize)
{
_bufferSize = bufferSize;
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException)
{
if (packet != null)
{
packet.Release();
}
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, sniException);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage)
{
if (packet != null)
{
packet.Release();
}
return SNICommon.ReportSNIError(SNIProviders.NP_PROV, nativeError, sniError, errorMessage);
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public override void KillConnection()
{
_pipeStream.Dispose();
_pipeStream = null;
}
#endif
}
}
| |
#region License
/*
* All content copyright Marko Lahma, unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using Quartz.Spi;
using Quartz.Util;
namespace Quartz.Impl.AdoJobStore
{
/// <summary>
/// A base implementation of <see cref="ITriggerPersistenceDelegate" /> that persists
/// trigger fields in the "QRTZ_SIMPROP_TRIGGERS" table. This allows extending
/// concrete classes to simply implement a couple methods that do the work of
/// getting/setting the trigger's fields, and creating the <see cref="IScheduleBuilder" />
/// for the particular type of trigger.
/// </summary>
/// <seealso cref="CalendarIntervalTriggerPersistenceDelegate" />
/// <author>jhouse</author>
/// <author>Marko Lahma (.NET)</author>
public abstract class SimplePropertiesTriggerPersistenceDelegateSupport : ITriggerPersistenceDelegate
{
protected const string TableSimplePropertiesTriggers = "SIMPROP_TRIGGERS";
protected const string ColumnStrProp1 = "STR_PROP_1";
protected const string ColumnStrProp2 = "STR_PROP_2";
protected const string ColumnStrProp3 = "STR_PROP_3";
protected const string ColumnIntProp1 = "INT_PROP_1";
protected const string ColumnIntProp2 = "INT_PROP_2";
protected const string ColumnLongProp1 = "LONG_PROP_1";
protected const string ColumnLongProp2 = "LONG_PROP_2";
protected const string ColumnDecProp1 = "DEC_PROP_1";
protected const string ColumnDecProp2 = "DEC_PROP_2";
protected const string ColumnBoolProp1 = "BOOL_PROP_1";
protected const string ColumnBoolProp2 = "BOOL_PROP_2";
protected const string ColumnTimeZoneId = "TIME_ZONE_ID";
protected const string SelectSimplePropsTrigger = "SELECT *" + " FROM "
+ StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " WHERE "
+ AdoConstants.ColumnSchedulerName + " = @schedulerName"
+ " AND " + AdoConstants.ColumnTriggerName + " = @triggerName AND " + AdoConstants.ColumnTriggerGroup + " = @triggerGroup";
protected const string DeleteSimplePropsTrigger = "DELETE FROM "
+ StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " WHERE "
+ AdoConstants.ColumnSchedulerName + " = @schedulerName"
+ " AND " + AdoConstants.ColumnTriggerName + " = @triggerName AND " + AdoConstants.ColumnTriggerGroup + " = @triggerGroup";
protected const string InsertSimplePropsTrigger = "INSERT INTO "
+ StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " ("
+ AdoConstants.ColumnSchedulerName + ", "
+ AdoConstants.ColumnTriggerName + ", " + AdoConstants.ColumnTriggerGroup + ", "
+ ColumnStrProp1 + ", " + ColumnStrProp2 + ", " + ColumnStrProp3 + ", "
+ ColumnIntProp1 + ", " + ColumnIntProp2 + ", "
+ ColumnLongProp1 + ", " + ColumnLongProp2 + ", "
+ ColumnDecProp1 + ", " + ColumnDecProp2 + ", "
+ ColumnBoolProp1 + ", " + ColumnBoolProp2 + ", " + ColumnTimeZoneId
+ ") " + " VALUES(@schedulerName" + ", @triggerName, @triggerGroup, @string1, @string2, @string3, @int1, @int2, @long1, @long2, @decimal1, @decimal2, @boolean1, @boolean2, @timeZoneId)";
protected const string UpdateSimplePropsTrigger = "UPDATE "
+ StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " SET "
+ ColumnStrProp1 + " = @string1, " + ColumnStrProp2 + " = @string2, " + ColumnStrProp3 + " = @string3, "
+ ColumnIntProp1 + " = @int1, " + ColumnIntProp2 + " = @int2, "
+ ColumnLongProp1 + " = @long1, " + ColumnLongProp2 + " = @long2, "
+ ColumnDecProp1 + " = @decimal1, " + ColumnDecProp2 + " = @decimal2, "
+ ColumnBoolProp1 + " = @boolean1, " + ColumnBoolProp2
+ " = @boolean2, " + ColumnTimeZoneId + " = @timeZoneId WHERE " + AdoConstants.ColumnSchedulerName + " = @schedulerName"
+ " AND " + AdoConstants.ColumnTriggerName
+ " = @triggerName AND " + AdoConstants.ColumnTriggerGroup + " = @triggerGroup";
public void Initialize(string tablePrefix, string schedName, IDbAccessor dbAccessor)
{
TablePrefix = tablePrefix;
DbAccessor = dbAccessor;
SchedName = schedName;
// No longer used
SchedNameLiteral = "'" + schedName + "'";
}
/// <summary>
/// Returns whether the trigger type can be handled by delegate.
/// </summary>
public abstract bool CanHandleTriggerType(IOperableTrigger trigger);
/// <summary>
/// Returns database discriminator value for trigger type.
/// </summary>
public abstract string GetHandledTriggerTypeDiscriminator();
protected abstract SimplePropertiesTriggerProperties GetTriggerProperties(IOperableTrigger trigger);
protected abstract TriggerPropertyBundle GetTriggerPropertyBundle(SimplePropertiesTriggerProperties properties);
protected string TablePrefix { get; private set; } = null!;
[Obsolete("Scheduler name is now added to queries as a parameter")]
protected string SchedNameLiteral { get; private set; } = null!;
protected string SchedName { get; private set; } = null!;
protected IDbAccessor DbAccessor { get; private set; } = null!;
public async Task<int> DeleteExtendedTriggerProperties(
ConnectionAndTransactionHolder conn,
TriggerKey triggerKey,
CancellationToken cancellationToken = default)
{
using var cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(DeleteSimplePropsTrigger, TablePrefix));
DbAccessor.AddCommandParameter(cmd, "schedulerName", SchedName);
DbAccessor.AddCommandParameter(cmd, "triggerName", triggerKey.Name);
DbAccessor.AddCommandParameter(cmd, "triggerGroup", triggerKey.Group);
return await cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
public async Task<int> InsertExtendedTriggerProperties(
ConnectionAndTransactionHolder conn,
IOperableTrigger trigger,
string state,
IJobDetail jobDetail,
CancellationToken cancellationToken = default)
{
SimplePropertiesTriggerProperties properties = GetTriggerProperties(trigger);
using var cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(InsertSimplePropsTrigger, TablePrefix));
DbAccessor.AddCommandParameter(cmd, "schedulerName", SchedName);
DbAccessor.AddCommandParameter(cmd, "triggerName", trigger.Key.Name);
DbAccessor.AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group);
DbAccessor.AddCommandParameter(cmd, "string1", properties.String1);
DbAccessor.AddCommandParameter(cmd, "string2", properties.String2);
DbAccessor.AddCommandParameter(cmd, "string3", properties.String3);
DbAccessor.AddCommandParameter(cmd, "int1", properties.Int1);
DbAccessor.AddCommandParameter(cmd, "int2", properties.Int2);
DbAccessor.AddCommandParameter(cmd, "long1", properties.Long1);
DbAccessor.AddCommandParameter(cmd, "long2", properties.Long2);
DbAccessor.AddCommandParameter(cmd, "decimal1", properties.Decimal1);
DbAccessor.AddCommandParameter(cmd, "decimal2", properties.Decimal2);
DbAccessor.AddCommandParameter(cmd, "boolean1", DbAccessor.GetDbBooleanValue(properties.Boolean1));
DbAccessor.AddCommandParameter(cmd, "boolean2", DbAccessor.GetDbBooleanValue(properties.Boolean2));
DbAccessor.AddCommandParameter(cmd, "timeZoneId", properties.TimeZoneId);
return await cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
public async Task<TriggerPropertyBundle> LoadExtendedTriggerProperties(
ConnectionAndTransactionHolder conn,
TriggerKey triggerKey,
CancellationToken cancellationToken = default)
{
using var cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(SelectSimplePropsTrigger, TablePrefix));
DbAccessor.AddCommandParameter(cmd, "schedulerName", SchedName);
DbAccessor.AddCommandParameter(cmd, "triggerName", triggerKey.Name);
DbAccessor.AddCommandParameter(cmd, "triggerGroup", triggerKey.Group);
using var rs = await cmd.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
if (await rs.ReadAsync(cancellationToken).ConfigureAwait(false))
{
return ReadTriggerPropertyBundle(rs);
}
throw new InvalidOperationException("No record found for selection of Trigger with key: '" + triggerKey + "' and statement: " + AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlSelectSimpleTrigger, TablePrefix));
}
public TriggerPropertyBundle ReadTriggerPropertyBundle(DbDataReader rs)
{
SimplePropertiesTriggerProperties properties = new SimplePropertiesTriggerProperties();
properties.String1 = rs.GetString(ColumnStrProp1);
properties.String2 = rs.GetString(ColumnStrProp2);
properties.String3 = rs.GetString(ColumnStrProp3);
properties.Int1 = rs.GetInt32(ColumnIntProp1);
properties.Int2 = rs.GetInt32(ColumnIntProp2);
properties.Long1 = rs.GetInt64(ColumnLongProp1);
properties.Long2 = rs.GetInt64(ColumnLongProp2);
properties.Decimal1 = rs.GetDecimal(ColumnDecProp1);
properties.Decimal2 = rs.GetDecimal(ColumnDecProp2);
properties.Boolean1 = DbAccessor.GetBooleanFromDbValue(rs[ColumnBoolProp1]);
properties.Boolean2 = DbAccessor.GetBooleanFromDbValue(rs[ColumnBoolProp2]);
properties.TimeZoneId = rs.GetString(ColumnTimeZoneId);
return GetTriggerPropertyBundle(properties);
}
public async Task<int> UpdateExtendedTriggerProperties(
ConnectionAndTransactionHolder conn,
IOperableTrigger trigger,
string state,
IJobDetail jobDetail,
CancellationToken cancellationToken = default)
{
SimplePropertiesTriggerProperties properties = GetTriggerProperties(trigger);
using var cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(UpdateSimplePropsTrigger, TablePrefix));
DbAccessor.AddCommandParameter(cmd, "schedulerName", SchedName);
DbAccessor.AddCommandParameter(cmd, "string1", properties.String1);
DbAccessor.AddCommandParameter(cmd, "string2", properties.String2);
DbAccessor.AddCommandParameter(cmd, "string3", properties.String3);
DbAccessor.AddCommandParameter(cmd, "int1", properties.Int1);
DbAccessor.AddCommandParameter(cmd, "int2", properties.Int2);
DbAccessor.AddCommandParameter(cmd, "long1", properties.Long1);
DbAccessor.AddCommandParameter(cmd, "long2", properties.Long2);
DbAccessor.AddCommandParameter(cmd, "decimal1", properties.Decimal1);
DbAccessor.AddCommandParameter(cmd, "decimal2", properties.Decimal2);
DbAccessor.AddCommandParameter(cmd, "boolean1", DbAccessor.GetDbBooleanValue(properties.Boolean1));
DbAccessor.AddCommandParameter(cmd, "boolean2", DbAccessor.GetDbBooleanValue(properties.Boolean2));
DbAccessor.AddCommandParameter(cmd, "triggerName", trigger.Key.Name);
DbAccessor.AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group);
DbAccessor.AddCommandParameter(cmd, "timeZoneId", properties.TimeZoneId);
return await cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
using System.Globalization;
using OpenTK.Mathematics;
namespace Bearded.Utilities.Geometry;
/// <summary>
/// A typesafe representation of a direction in two dimensional space.
/// </summary>
public readonly struct Direction2 : IEquatable<Direction2>, IFormattable
{
private const long numSteps = (1L << 32);
private const float fromRadians = numSteps / MathConstants.TwoPi;
private const float toRadians = MathConstants.TwoPi / numSteps;
private const float fromDegrees = numSteps / 360f;
private const float toDegrees = 360f / numSteps;
private readonly uint data;
#region Constructing
private Direction2(uint data)
{
this.data = data;
}
/// <summary>
/// Initialises a direction from an absolute angle value in radians.
/// </summary>
public static Direction2 FromRadians(float radians)
{
return new Direction2((uint)(radians * fromRadians));
}
/// <summary>
/// Initialises a direction from an absolute angle value in degrees.
/// </summary>
public static Direction2 FromDegrees(float degrees)
{
return new Direction2((uint)(degrees * fromDegrees));
}
/// <summary>
/// Initialises a direction along a vector.
/// </summary>
public static Direction2 Of(Vector2 vector)
{
return FromRadians(MathF.Atan2(vector.Y, vector.X));
}
/// <summary>
/// Initialises the direction between two points.
/// </summary>
/// <param name="from">The base point.</param>
/// <param name="to">The point the directions "points" towards.</param>
public static Direction2 Between(Vector2 from, Vector2 to)
{
return Of(to - from);
}
#endregion
#region Static Fields
/// <summary>
/// Default base direction (along positive X axis).
/// </summary>
public static readonly Direction2 Zero = new Direction2(0);
#endregion
#region Properties
/// <summary>
/// Gets the absolute angle of the direction in radians between 0 and 2pi.
/// </summary>
public float Radians { get { return data * toRadians; } }
/// <summary>
/// Gets the absolute angle of the direction in degrees between 0 and 360.
/// </summary>
public float Degrees { get { return data * toDegrees; } }
/// <summary>
/// Gets the absolute angle of the direction in radians between -pi and pi.
/// </summary>
public float RadiansSigned { get { return (int)data * toRadians; } }
/// <summary>
/// Gets the absolute angle of the direction in degrees between -180 and 180.
/// </summary>
public float DegreesSigned { get { return (int)data * toDegrees; } }
/// <summary>
/// Gets the unit vector pointing in this direction.
/// </summary>
public Vector2 Vector
{
get
{
var radians = Radians;
return new Vector2(MathF.Cos(radians), MathF.Sin(radians));
}
}
#endregion
#region Methods
/// <summary>
/// Returns this direction turnen towards a goal direction with a given maximum step length in radians.
/// This will never overshoot the goal.
/// </summary>
/// <param name="goal">The goal direction.</param>
/// <param name="maxStepInRadians">The maximum step length in radians. Negative values will return the original direction.</param>
public Direction2 TurnedTowards(Direction2 goal, float maxStepInRadians)
{
if (maxStepInRadians <= 0)
return this;
var step = maxStepInRadians.Radians();
var thisToGoal = goal - this;
if (step > thisToGoal.Abs())
return goal;
step *= thisToGoal.Sign();
return this + step;
}
#region Statics
/// <summary>
/// Linearly interpolates between two directions.
/// This always interpolates along the shorter arc.
/// </summary>
/// <param name="d0">The first direction (at p == 0).</param>
/// <param name="d1">The second direction (at p == 1).</param>
/// <param name="p">The parameter.</param>
public static Direction2 Lerp(Direction2 d0, Direction2 d1, float p)
{
return d0 + p * (d1 - d0);
}
#endregion
#endregion
#region Operators
#region Arithmetic
/// <summary>
/// Adds an angle to a direction.
/// </summary>
public static Direction2 operator +(Direction2 direction, Angle angle)
{
return new Direction2((uint)(direction.data + angle.Radians * fromRadians));
}
/// <summary>
/// Substracts an angle from a direction.
/// </summary>
public static Direction2 operator -(Direction2 direction, Angle angle)
{
return new Direction2((uint)(direction.data - angle.Radians * fromRadians));
}
/// <summary>
/// Gets the signed difference between two directions.
/// Always returns the angle of the shorter arc.
/// </summary>
public static Angle operator -(Direction2 direction1, Direction2 direction2)
{
return Angle.FromRadians(((int)direction1.data - (int)direction2.data) * toRadians);
}
/// <summary>
/// Gets the inverse direction to a direction.
/// </summary>
public static Direction2 operator -(Direction2 direction)
{
return new Direction2(direction.data + (uint.MaxValue / 2 + 1));
}
#endregion
#region Boolean
/// <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(Direction2 other)
{
return data == other.data;
}
/// <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)
{
return obj is Direction2 direction2 && Equals(direction2);
}
/// <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()
{
return data.GetHashCode();
}
/// <summary>
/// Checks two directions for equality.
/// </summary>
public static bool operator ==(Direction2 x, Direction2 y)
{
return x.Equals(y);
}
/// <summary>
/// Checks two directions for inequality.
/// </summary>
public static bool operator !=(Direction2 x, Direction2 y)
{
return !(x == y);
}
#endregion
#region tostring
public override string ToString() => ToString(null, CultureInfo.CurrentCulture);
public string ToString(string? format, IFormatProvider? formatProvider)
=> $"{Radians.ToString(format, formatProvider)} rad";
public string ToString(string? format)
=> ToString(format, CultureInfo.CurrentCulture);
#endregion
#region Casts
#endregion
#endregion
}
| |
using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Timers;
using WatchThis.Models;
using WatchThis.Utilities;
using System.IO;
using Rangic.Utilities.Geo;
namespace WatchThis.Controllers
{
internal enum DriverState
{
Created,
Enumerating,
Playing,
Paused,
Stopped,
}
/// <summary>
/// Responsible for loading and playing slideshows, though delegating to a viewer for the actual
/// image display.
/// All calls to the viewer are on the main/UI thread in order to minimize threading issues in
/// the various UI implementations.
/// </summary>
public class SlideshowDriver : INotifyPropertyChanged
{
public SlideshowModel Model { get; private set; }
public ISlideshowViewer Viewer { get; private set; }
public IPlatformService PlatformService { get; private set; }
public event PropertyChangedEventHandler PropertyChanged;
public bool IsPaused { get { return State == DriverState.Paused; } }
public bool IsPlaying { get { return State == DriverState.Playing; } }
private DriverState State
{
get { return _state; }
set
{
_state = value;
PlatformService.InvokeOnUiThread(delegate
{
this.FirePropertyChanged(PropertyChanged, () => IsPaused);
this.FirePropertyChanged(PropertyChanged, () => IsPlaying);
});
}
}
private DriverState _state;
private Timer _timer;
private Random _random = new Random();
private IList<MediaItem> _recent = new List<MediaItem>();
private int? _recentIndex;
private static Logger logger = LogManager.GetCurrentClassLogger();
static public SlideshowDriver Create(string filename, ISlideshowViewer viewer, IPlatformService platformService)
{
return Create(SlideshowModel.ParseFile(filename), viewer, platformService);
}
static public SlideshowDriver Create(SlideshowModel model, ISlideshowViewer viewer, IPlatformService platformService)
{
var driver = new SlideshowDriver(model, viewer, platformService);
driver.BeginEnumerate();
return driver;
}
private SlideshowDriver(SlideshowModel model, ISlideshowViewer viewer, IPlatformService platformService)
{
PlatformService = platformService;
Model = model;
Viewer = viewer;
State = DriverState.Created;
}
public void Play()
{
logger.Info("SlideshowDriver.Play: {0}", State);
if (State == DriverState.Playing)
{
return;
}
State = DriverState.Playing;
SetupTimer();
Next();
}
public void PauseOrResume()
{
logger.Info("SlideshowDriver.Pause: {0}", State);
if (State == DriverState.Paused)
{
Play();
}
else if (State == DriverState.Playing)
{
State = DriverState.Paused;
DestroyTimer();
}
PlatformService.InvokeOnUiThread( () => Viewer.UpdateUiState());
}
public void Stop()
{
logger.Info("SlideshowDriver.Stop {0}", State);
State = DriverState.Stopped;
DestroyTimer();
}
public void Next()
{
logger.Info("SlideshowDriver.Next {0}", State);
NextSlide();
PlatformService.InvokeOnUiThread( () => Viewer.UpdateUiState());
}
private void NextSlide()
{
Task.Factory.StartNew( () =>
{
if (Model.MediaList.Count == 0)
{
BeginEnumerate();
}
else
{
if (State != DriverState.Stopped)
{
if (State == DriverState.Paused)
{
SetupTimer();
}
ResetTimer();
if (_recentIndex.HasValue)
{
++_recentIndex;
if (_recentIndex < _recent.Count)
{
ShowImage(_recent[_recentIndex.Value]);
}
else
{
_recentIndex = null;
}
}
if (!_recentIndex.HasValue)
{
ShowImage(NextRandom());
}
}
}
});
}
public void Previous()
{
logger.Info("SlideshowDriver.Previous {0}", State);
int index;
if (_recentIndex.HasValue)
{
index = _recentIndex.Value - 1;
}
else
{
// The last item (-1) is currently being displayed. -2 is the previous item
index = _recent.Count - 2;
}
if (index < 0)
{
return;
}
ResetTimer();
_recentIndex = index;
ShowImage(_recent[_recentIndex.Value]);
PlatformService.InvokeOnUiThread( () => Viewer.UpdateUiState());
}
private MediaItem NextRandom()
{
var index = _random.Next(Model.MediaList.Count);
var item = Model.MediaList[index];
Model.MediaList.RemoveAt(index);
_recent.Add(item);
while (_recent.Count > 1000)
{
_recent.RemoveAt(0);
}
return item;
}
private void ShowImage(MediaItem item)
{
Task.Factory.StartNew(() =>
{
try
{
object image = Viewer.LoadImage(item);
PlatformService.InvokeOnUiThread(() =>
{
var message = Viewer.DisplayImage(image);
logger.Info("image {0}; {1}", item.Identifier, message);
});
}
catch (Exception e)
{
logger.Error("Error loading image '{0}': {1}", item.Identifier, e);
}
})
.ContinueWith((a) =>
{
try
{
var message = string.Format(" {0} ", Path.GetFileName(item.ParentDirectoryName));
var location = item.GetLocation();
if (location != null)
{
var placeName = location.PlaceName(Location.PlaceNameFilter.Standard);
message = string.Format("{0} {1}", message, placeName);
}
PlatformService.InvokeOnUiThread(() => Viewer.DisplayInfo(message));
}
catch (Exception ex)
{
logger.Error("Error loading info for {0}: {1}", item.Identifier, ex);
}
});
}
private void LogFailedTask(Task t, string baseMessage, params object[] args)
{
if (t.IsCanceled)
{
logger.Warn("Canceled task {0}", string.Format(baseMessage, args));
}
if (t.IsFaulted)
{
logger.Error("Faulted task {0}; {1}", string.Format(baseMessage, args), t.Exception);
}
}
private double GetTimerValue()
{
var time = (Model.SlideSeconds + Model.TransitionSeconds) * 1000;
if (time < 100)
{
time = 100;
}
return time;
}
private void ResetTimer()
{
_timer.Stop();
_timer.Interval = GetTimerValue();
_timer.Start();
}
private void SetupTimer()
{
var time = GetTimerValue();
if (_timer == null)
{
_timer = new Timer(time) { AutoReset = true, Enabled = true };
_timer.Elapsed += (s, e) => NextSlide();
}
else
{
_timer.Interval = time;
}
}
private void DestroyTimer()
{
if (_timer != null)
{
_timer.Stop();
_timer.Dispose();
_timer = null;
}
}
private void BeginEnumerate()
{
State = DriverState.Enumerating;
Task.Factory.StartNew( () =>
{
Model.Enumerate( () =>
{
logger.Info("Images available: {0}", Model.MediaList.Count);
PlatformService.InvokeOnUiThread( delegate { Viewer.UpdateUiState(); } );
Play();
});
})
.ContinueWith( t =>
{
if (!t.IsFaulted && !t.IsCanceled)
{
if (State == DriverState.Playing || State == DriverState.Paused)
{
logger.Info("Images fully loaded: {0}", Model.MediaList.Count);
PlatformService.InvokeOnUiThread( delegate
{
Viewer.UpdateUiState();
} );
Play();
}
else
{
logger.Info("Not playing, ignoring completed enumeration");
}
}
else
{
logger.Error("Failed or canceled: {0}", t.Exception);
PlatformService.InvokeOnUiThread( delegate { Viewer.Error(t.Exception.Message); });
}
return t;
});
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Static methods to serialize and deserialize scene objects to and from XML
/// </summary>
public class SceneXmlLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region old xml format
public static void LoadPrimsFromXml(Scene scene, string fileName, bool newIDS, Vector3 loadOffset)
{
XmlDocument doc = new XmlDocument();
XmlNode rootNode;
if (fileName.StartsWith("http:") || File.Exists(fileName))
{
XmlTextReader reader = new XmlTextReader(fileName);
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
rootNode = doc.FirstChild;
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = SceneObjectSerializer.FromOriginalXmlFormat(aPrimNode.OuterXml);
if (newIDS)
{
obj.ResetIDs();
}
//if we want this to be a import method then we need new uuids for the object to avoid any clashes
//obj.RegenerateFullIDs();
scene.AddNewSceneObject(obj, true);
obj.InvalidateDeepEffectivePerms();
}
}
else
{
throw new Exception("Could not open file " + fileName + " for reading");
}
}
public static void SavePrimsToXml(Scene scene, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
StreamWriter stream = new StreamWriter(file);
int primCount = 0;
stream.WriteLine("<scene>\n");
EntityBase[] entityList = scene.GetEntities();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
stream.WriteLine(SceneObjectSerializer.ToOriginalXmlFormat((SceneObjectGroup)ent));
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Close();
file.Close();
}
#endregion
#region XML2 serialization
// Called by archives (save oar)
public static string SaveGroupToXml2(SceneObjectGroup grp, Dictionary<string, object> options)
{
//return SceneObjectSerializer.ToXml2Format(grp);
using (MemoryStream mem = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mem, System.Text.Encoding.UTF8))
{
SceneObjectSerializer.SOGToXml2(writer, grp, options);
writer.Flush();
using (StreamReader reader = new StreamReader(mem))
{
mem.Seek(0, SeekOrigin.Begin);
return reader.ReadToEnd();
}
}
}
}
// Called by scene serializer (save xml2)
public static void SavePrimsToXml2(Scene scene, string fileName)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, fileName);
}
// Called by scene serializer (save xml2)
public static void SaveNamedPrimsToXml2(Scene scene, string primName, string fileName)
{
m_log.InfoFormat(
"[SERIALISER]: Saving prims with name {0} in xml2 format for region {1} to {2}",
primName, scene.RegionInfo.RegionName, fileName);
EntityBase[] entityList = scene.GetEntities();
List<EntityBase> primList = new List<EntityBase>();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (ent.Name == primName)
{
primList.Add(ent);
}
}
}
SavePrimListToXml2(primList.ToArray(), fileName);
}
// Called by REST Application plugin
public static void SavePrimsToXml2(Scene scene, TextWriter stream, Vector3 min, Vector3 max)
{
EntityBase[] entityList = scene.GetEntities();
SavePrimListToXml2(entityList, stream, min, max);
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, string fileName)
{
FileStream file = new FileStream(fileName, FileMode.Create);
try
{
StreamWriter stream = new StreamWriter(file);
try
{
SavePrimListToXml2(entityList, stream, Vector3.Zero, Vector3.Zero);
}
finally
{
stream.Close();
}
}
finally
{
file.Close();
}
}
// Called here only. Should be private?
public static void SavePrimListToXml2(EntityBase[] entityList, TextWriter stream, Vector3 min, Vector3 max)
{
XmlTextWriter writer = new XmlTextWriter(stream);
int primCount = 0;
stream.WriteLine("<scene>\n");
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup g = (SceneObjectGroup)ent;
if (!min.Equals(Vector3.Zero) || !max.Equals(Vector3.Zero))
{
Vector3 pos = g.RootPart.GetWorldPosition();
if (min.X > pos.X || min.Y > pos.Y || min.Z > pos.Z)
continue;
if (max.X < pos.X || max.Y < pos.Y || max.Z < pos.Z)
continue;
}
//stream.WriteLine(SceneObjectSerializer.ToXml2Format(g));
SceneObjectSerializer.SOGToXml2(writer, (SceneObjectGroup)ent, new Dictionary<string,object>());
stream.WriteLine();
primCount++;
}
}
stream.WriteLine("</scene>\n");
stream.Flush();
}
#endregion
#region XML2 deserialization
public static SceneObjectGroup DeserializeGroupFromXml2(string xmlString)
{
return SceneObjectSerializer.FromXml2Format(xmlString);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="fileName"></param>
public static void LoadPrimsFromXml2(Scene scene, string fileName)
{
LoadPrimsFromXml2(scene, new XmlTextReader(fileName), false);
}
/// <summary>
/// Load prims from the xml2 format
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
public static void LoadPrimsFromXml2(Scene scene, TextReader reader, bool startScripts)
{
LoadPrimsFromXml2(scene, new XmlTextReader(reader), startScripts);
}
/// <summary>
/// Load prims from the xml2 format. This method will close the reader
/// </summary>
/// <param name="scene"></param>
/// <param name="reader"></param>
/// <param name="startScripts"></param>
protected static void LoadPrimsFromXml2(Scene scene, XmlTextReader reader, bool startScripts)
{
XmlDocument doc = new XmlDocument();
reader.WhitespaceHandling = WhitespaceHandling.None;
doc.Load(reader);
reader.Close();
XmlNode rootNode = doc.FirstChild;
ICollection<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
foreach (XmlNode aPrimNode in rootNode.ChildNodes)
{
SceneObjectGroup obj = DeserializeGroupFromXml2(aPrimNode.OuterXml);
scene.AddNewSceneObject(obj, true);
if (startScripts)
sceneObjects.Add(obj);
}
foreach (SceneObjectGroup sceneObject in sceneObjects)
{
sceneObject.CreateScriptInstances(0, true, scene.DefaultScriptEngine, 0);
sceneObject.ResumeScripts();
}
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MainViewModel.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CustomShaderDemo
{
using CustomShaderDemo.Materials;
using DemoCore;
using HelixToolkit.Wpf.SharpDX;
using SharpDX;
using SharpDX.Direct2D1.Effects;
using SharpDX.Direct3D11;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using System.Windows.Media;
using Color = System.Windows.Media.Color;
using Point3D = System.Windows.Media.Media3D.Point3D;
using Vector3D = System.Windows.Media.Media3D.Vector3D;
using Transform3D = System.Windows.Media.Media3D.Transform3D;
using TranslateTransform3D = System.Windows.Media.Media3D.TranslateTransform3D;
public class MainViewModel : BaseViewModel
{
public MeshGeometry3D Model { get; private set; }
public MeshGeometry3D SphereModel { get; private set; }
public LineGeometry3D AxisModel { get; private set; }
public BillboardText3D AxisLabel { private set; get; }
public ColorStripeMaterial ModelMaterial { get; private set; } = new ColorStripeMaterial();
public PhongMaterial SphereMaterial { private set; get; } = PhongMaterials.Copper;
public PointGeometry3D PointModel { private set; get; }
public CustomPointMaterial CustomPointMaterial { get; }
public Transform3D PointTransform { get; } = new TranslateTransform3D(10, 0, 0);
private Color startColor;
/// <summary>
/// Gets or sets the StartColor.
/// </summary>
/// <value>
/// StartColor
/// </value>
public Color StartColor
{
set
{
if (SetValue(ref startColor, value))
{
ColorGradient = new Color4Collection(GetGradients(startColor.ToColor4(), midColor.ToColor4(), endColor.ToColor4(), 100));
}
}
get { return startColor; }
}
private Color midColor;
/// <summary>
/// Gets or sets the StartColor.
/// </summary>
/// <value>
/// StartColor
/// </value>
public Color MidColor
{
set
{
if (SetValue(ref midColor, value))
{
ColorGradient = new Color4Collection(GetGradients(startColor.ToColor4(), midColor.ToColor4(), endColor.ToColor4(), 100));
}
}
get { return midColor; }
}
private Color endColor;
/// <summary>
/// Gets or sets the StartColor.
/// </summary>
/// <value>
/// StartColor
/// </value>
public Color EndColor
{
set
{
if (SetValue(ref endColor, value))
{
ColorGradient = new Color4Collection(GetGradients(startColor.ToColor4(), midColor.ToColor4(), endColor.ToColor4(), 100));
}
}
get { return endColor; }
}
private Color4Collection colorGradient;
public Color4Collection ColorGradient
{
private set
{
if(SetValue(ref colorGradient, value))
{
ModelMaterial.ColorStripeX = value;
}
}
get { return colorGradient; }
}
private FillMode fillMode = FillMode.Solid;
public FillMode FillMode
{
set
{
SetValue(ref fillMode, value);
}
get { return fillMode; }
}
private bool showWireframe = false;
public bool ShowWireframe
{
set
{
if(SetValue(ref showWireframe, value))
{
FillMode = value ? FillMode.Wireframe : FillMode.Solid;
}
}
get { return showWireframe; }
}
private int Width = 100;
private int Height = 100;
public ICommand GenerateNoiseCommand { private set; get; }
public MainViewModel()
{
// titles
Title = "Simple Demo";
SubTitle = "WPF & SharpDX";
// camera setup
Camera = new PerspectiveCamera {
Position = new Point3D(-6, 8, 23),
LookDirection = new Vector3D(11, -4, -23),
UpDirection = new Vector3D(0, 1, 0),
FarPlaneDistance = 5000
};
EffectsManager = new CustomEffectsManager();
var builder = new MeshBuilder(true);
Vector3[] points = new Vector3[Width*Height];
for(int i=0; i<Width; ++i)
{
for(int j=0; j<Height; ++j)
{
points[i * Width + j] = new Vector3(i / 10f, 0, j / 10f);
}
}
builder.AddRectangularMesh(points, Width);
Model = builder.ToMesh();
for(int i=0; i<Model.Normals.Count; ++i)
{
Model.Normals[i] = new Vector3(0, Math.Abs(Model.Normals[i].Y), 0);
}
StartColor = Colors.Blue;
MidColor = Colors.Green;
EndColor = Colors.Red;
var lineBuilder = new LineBuilder();
lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(10, 0, 0));
lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(0, 10, 0));
lineBuilder.AddLine(new Vector3(0, 0, 0), new Vector3(0, 0, 10));
AxisModel = lineBuilder.ToLineGeometry3D();
AxisModel.Colors = new Color4Collection(AxisModel.Positions.Count);
AxisModel.Colors.Add(Colors.Red.ToColor4());
AxisModel.Colors.Add(Colors.Red.ToColor4());
AxisModel.Colors.Add(Colors.Green.ToColor4());
AxisModel.Colors.Add(Colors.Green.ToColor4());
AxisModel.Colors.Add(Colors.Blue.ToColor4());
AxisModel.Colors.Add(Colors.Blue.ToColor4());
AxisLabel = new BillboardText3D();
AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(11, 0, 0), Text = "X", Foreground = Colors.Red.ToColor4() });
AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(0, 11, 0), Text = "Y", Foreground = Colors.Green.ToColor4() });
AxisLabel.TextInfo.Add(new TextInfo() { Origin = new Vector3(0, 0, 11), Text = "Z", Foreground = Colors.Blue.ToColor4() });
builder = new MeshBuilder(true);
builder.AddSphere(new Vector3(-15, 0, 0), 5);
SphereModel = builder.ToMesh();
GenerateNoiseCommand = new RelayCommand((o) => { CreatePerlinNoise(); });
CreatePerlinNoise();
PointModel = new PointGeometry3D()
{
Positions = SphereModel.Positions
};
CustomPointMaterial = new CustomPointMaterial() { Color = Colors.White };
}
public static IEnumerable<Color4> GetGradients(Color4 start, Color4 mid, Color4 end, int steps)
{
return GetGradients(start, mid, steps / 2).Concat(GetGradients(mid, end, steps / 2));
}
public static IEnumerable<Color4> GetGradients(Color4 start, Color4 end, int steps)
{
float stepA = ((end.Alpha - start.Alpha) / (steps - 1));
float stepR = ((end.Red - start.Red) / (steps - 1));
float stepG = ((end.Green - start.Green) / (steps - 1));
float stepB = ((end.Blue - start.Blue) / (steps - 1));
for (int i = 0; i < steps; i++)
{
yield return new Color4((start.Red + (stepR * i)),
(start.Green + (stepG * i)),
(start.Blue + (stepB * i)),
(start.Alpha + (stepA * i)));
}
}
private void CreatePerlinNoise()
{
float[] noise;
MathHelper.GenerateNoiseMap(Width, Height, 8, out noise);
Vector2Collection collection = new Vector2Collection(Width * Height);
for(int i=0; i<Width; ++i)
{
for(int j=0; j<Height; ++j)
{
collection.Add(new Vector2(Math.Abs(noise[Width * i + j]), 0));
}
}
Model.TextureCoordinates = collection;
}
}
}
| |
new SimGroup( MeshQualityGroup )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::TS::detailAdjust"] = 1.5;
key["$pref::TS::skipRenderDLs"] = 0;
};
new ArrayObject( )
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::TS::detailAdjust"] = 1.0;
key["$pref::TS::skipRenderDLs"] = 0;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::TS::detailAdjust"] = 0.75;
key["$pref::TS::skipRenderDLs"] = 0;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Lowest";
key["$pref::TS::detailAdjust"] = 0.5;
key["$pref::TS::skipRenderDLs"] = 1;
};
};
new SimGroup( TextureQualityGroup )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::Video::textureReductionLevel"] = 0;
key["$pref::Reflect::refractTexScale"] = 1.25;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::Video::textureReductionLevel"] = 0;
key["$pref::Reflect::refractTexScale"] = 1;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::Video::textureReductionLevel"] = 1;
key["$pref::Reflect::refractTexScale"] = 0.75;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Lowest";
key["$pref::Video::textureReductionLevel"] = 2;
key["$pref::Reflect::refractTexScale"] = 0.5;
};
};
new SimGroup( GroundCoverDensityGroup )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::GroundCover::densityScale"] = 1.0;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::GroundCover::densityScale"] = 0.75;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::GroundCover::densityScale"] = 0.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Lowest";
key["$pref::GroundCover::densityScale"] = 0.25;
};
};
new SimGroup( DecalLifetimeGroup )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::decalMgr::enabled"] = true;
key["$pref::Decals::lifeTimeScale"] = 1;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::decalMgr::enabled"] = true;
key["$pref::Decals::lifeTimeScale"] = 0.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::decalMgr::enabled"] = true;
key["$pref::Decals::lifeTimeScale"] = 0.25;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "None";
key["$pref::decalMgr::enabled"] = false;
};
};
new SimGroup( TerrainQualityGroup )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::Terrain::lodScale"] = 0.75;
key["$pref::Terrain::detailScale"] = 1.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::Terrain::lodScale"] = 1.0;
key["$pref::Terrain::detailScale"] = 1.0;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::Terrain::lodScale"] = 1.5;
key["$pref::Terrain::detailScale"] = 0.75;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Lowest";
key["$pref::Terrain::lodScale"] = 2.0;
key["$pref::Terrain::detailScale"] = 0.5;
};
};
//Shadows and Lighting
new SimGroup( ShadowQualityList )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::lightManager"] = "Advanced Lighting";
key["$pref::Shadows::disable"] = false;
key["$pref::Shadows::textureScalar"] = 1.0;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::lightManager"] = "Advanced Lighting";
key["$pref::Shadows::disable"] = false;
key["$pref::Shadows::textureScalar"] = 0.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::lightManager"] = "Advanced Lighting";
key["$pref::Shadows::disable"] = false;
key["$pref::Shadows::textureScalar"] = 0.25;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "None";
key["$pref::lightManager"] = "Advanced Lighting";
key["$pref::Shadows::disable"] = true;
key["$pref::Shadows::textureScalar"] = 0.5;
};
};
new SimGroup( ShadowDistanceList )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Highest";
key["$pref::Shadows::drawDistance"] = 2;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::Shadows::drawDistance"] = 1.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::Shadows::drawDistance"] = 1;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::Shadows::drawDistance"] = 0.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Lowest";
key["$pref::Shadows::drawDistance"] = 0.25;
};
};
new SimGroup( SoftShadowList )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::Shadows::filterMode"] = "SoftShadowHighQuality";
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::Shadows::filterMode"] = "SoftShadow";
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Off";
key["$pref::Shadows::filterMode"] = "None";
};
};
new SimGroup( LightDistanceList )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Highest";
key["$pref::Lights::drawDistance"] = 2;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::Lights::drawDistance"] = 1.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Medium";
key["$pref::Lights::drawDistance"] = 1;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::Lights::drawDistance"] = 0.5;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Lowest";
key["$pref::Lights::drawDistance"] = 0.25;
};
};
new SimGroup( ShaderQualityGroup )
{
class = "GraphicsOptionsMenuGroup";
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "High";
key["$pref::Video::disablePixSpecular"] = false;
key["$pref::Video::disableNormalmapping"] = false;
};
new ArrayObject()
{
class = "GraphicsQualityLevel";
caseSensitive = true;
displayName = "Low";
key["$pref::Video::disablePixSpecular"] = true;
key["$pref::Video::disableNormalmapping"] = true;
};
};
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DoVuiHaiNao.Services;
using DoVuiHaiNao.Models;
using Microsoft.AspNetCore.Authorization;
using DoVuiHaiNao.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DoVuiHaiNao.Areas.WebManager.ViewModels;
using DoVuiHaiNao.Areas.WebManager.ViewModels.MultiPuzzleViewModels;
using DoVuiHaiNao.Areas.WebManager.ViewModels.SinglePuzzleViewModels;
namespace DoVuiHaiNao.Areas.WebManager.Controllers
{
[Area("WebManager")]
[Authorize(Roles = "Admin, Manager")]
public class MultiPuzzleController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMultiPuzzleManagerRepsository _repository;
private readonly UserManager<Member> _userManager;
public MultiPuzzleController(
ApplicationDbContext context,
UserManager<Member> userManager,
IMultiPuzzleManagerRepsository multiPuzzle)
{
_context = context;
_userManager = userManager;
_repository = multiPuzzle;
}
[Route("/quan-ly-web/cau-do-dac-biet")]
public async Task<IActionResult> Index(string sortOrder,
string currentFilter,
string searchString,
int? page, int? pageSize)
{
List<NumberItem> SoLuong = new List<NumberItem>
{
new NumberItem { Value = 10},
new NumberItem { Value = 20},
new NumberItem { Value = 50},
new NumberItem { Value = 100},
};
ViewData["SoLuong"] = SoLuong;
ViewData["CurrentSort"] = sortOrder;
ViewData["TitleParm"] = String.IsNullOrEmpty(sortOrder) ? "title" : "";
ViewData["CurrentSize"] = pageSize;
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewData["CurrentFilter"] = searchString;
return View(await _repository.GetAll(sortOrder, searchString, page, pageSize));
}
[Route("/quan-ly-web/cau-do-dac-biet/tao")]
public IActionResult Create()
{
ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name");
return View();
}
[Route("/quan-ly-web/cau-do-dac-biet/tao")]
[HttpPost]
public IActionResult Create(MultiPuzzle model)
{
if (ModelState.IsValid)
{
HttpContext.Session.SetObjectAsJson("MultiPuzzle", model);
return RedirectToAction("CreateMulti");
}
ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name",model.ImageID);
return View(model);
}
[HttpPost]
public async Task<IActionResult> SaveAll()
{
var sMultiPuzzle = HttpContext.Session.GetObjectFromJson<MultiPuzzle>("MultiPuzzle");
var sListSinglePuzzleDetails = HttpContext.Session.GetObjectFromJson<List<Temp>>("listSinglePuzzleDetails");
var user = await GetCurrentUserAsync();
MultiPuzzle multipuzzle = new MultiPuzzle
{
Active = "A",
Approved = "U",
ImageID = sMultiPuzzle.ImageID,
AuthorID = user.Id,
CreateDT = DateTime.Now,
Description = sMultiPuzzle.Description,
Image = sMultiPuzzle.Image,
IsDeleted = false,
Like = 0,
UpdateDT = DateTime.Now,
Title = sMultiPuzzle.Title,
NumberQuestion = sMultiPuzzle.NumberQuestion,
Slug = sMultiPuzzle.Slug,
Note = sMultiPuzzle.Note,
Level = 1
};
List<SinglePuzzle> listSinglePuzzleDetails = new List<SinglePuzzle>(multipuzzle.NumberQuestion - 1);
await _context.MultiPuzzle.AddAsync(multipuzzle);
await _context.SaveChangesAsync();
foreach (var item in sListSinglePuzzleDetails)
{
SinglePuzzle singlePuzzleDetails = new SinglePuzzle
{
ImageID = item.Image,
IsMMultiPuzzle = true,
Reason = item.Reason,
AuthorID = (await GetCurrentUserAsync()).Id,
Active = multipuzzle.Active,
Note = multipuzzle.Note,
Title = item.Title,
Description = item.Description,
IsYesNo = item.IsYesNo,
MultiPuzzleID = multipuzzle.ID,
AnswerA = item.AnswerA,
AnswerB = item.AnswerB,
AnswerC = item.AnswerC,
AnswerD = item.AnswerD,
Correct = item.Correct,
IsDeleted = false,
CreateDT = DateTime.Now,
UpdateDT = DateTime.Now,
Approved = "A",
};
if (singlePuzzleDetails.ImageID == 0)
singlePuzzleDetails.ImageID = null;
_context.SinglePuzzle.Add(singlePuzzleDetails);
List<string> listString = StringExtensions.ConvertStringToListString(item.TempTag);
List<Tag> listTag = new List<Tag>(listString.Capacity - 1);
// Save all tag
foreach (var itemTag in listString)
{
bool IsExitsTag = await _context.Tag.AnyAsync(p => p.Slug == StringExtensions.ConvertToUnSign3(itemTag));
Tag tag;
if (IsExitsTag)
{
tag = await _context.Tag.SingleOrDefaultAsync(p => p.Slug == StringExtensions.ConvertToUnSign3(itemTag));
}
else
{
tag = new Tag
{
Title = itemTag,
Slug = StringExtensions.ConvertToUnSign3(itemTag),
CreateDT = DateTime.Now
};
_context.Tag.Add(tag);
}
_context.SingPuzzleTag.Add(new SinglePuzzleTag { TagID = tag.ID, SinglePuzzleID = singlePuzzleDetails.ID });
await _context.SaveChangesAsync();
}
}
return RedirectToAction("Index", "MultiPuzzle");
}
public IActionResult CreateMulti()
{
var multiPuzzle = HttpContext.Session.GetObjectFromJson<MultiPuzzle>("MultiPuzzle");
var listSinglePuzzleDetails = HttpContext.Session.GetObjectFromJson<List<Temp>>("listSinglePuzzleDetails");
if (listSinglePuzzleDetails == null)
{
List<Temp> list = new List<Temp>(multiPuzzle.NumberQuestion - 1);
for (int i = 0; i <= multiPuzzle.NumberQuestion - 1; i++)
{
list.Add(new Temp { ID = i });
}
ViewData["listSinglePuzzleDetails"] = list.ToList();
HttpContext.Session.SetObjectAsJson("listSinglePuzzleDetails", list);
}
else
{
ViewData["listSinglePuzzleDetails"] = listSinglePuzzleDetails.ToList();
}
ViewData["NumberQuestion"] = multiPuzzle.NumberQuestion;
ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name");
return View();
}
[HttpPost]
[Route("sendData")]
public IActionResult SaveTemp(Temp temp, string id)
{
var oldListSinglePuzzleDetails = HttpContext.Session.GetObjectFromJson<List<Temp>>("listSinglePuzzleDetails");
var multiPuzzle = HttpContext.Session.GetObjectFromJson<MultiPuzzle>("MultiPuzzle");
//luu gia tri moi vao session
List<Temp> newListSinglePuzzleDetails = new List<Temp>(multiPuzzle.NumberQuestion - 1);
foreach (var item in oldListSinglePuzzleDetails)
{
if (item.ID == Int32.Parse(id))
{
item.Title = temp.Title;
item.Description = temp.Description;
item.Image = temp.Image;
item.AnswerA = temp.AnswerA;
item.AnswerB = temp.AnswerB;
item.AnswerC = temp.AnswerC;
item.AnswerD = temp.AnswerD;
item.Correct = temp.Correct;
item.IsYesNo = temp.IsYesNo;
item.TempTag = temp.TempTag;
}
newListSinglePuzzleDetails.Add(item);
}
HttpContext.Session.SetObjectAsJson("listSinglePuzzleDetails", newListSinglePuzzleDetails);
ViewData["listSinglePuzzleDetails"] = newListSinglePuzzleDetails.ToList();
var serializedJsonModel = JsonConvert.SerializeObject(newListSinglePuzzleDetails.ToList());
return Json(serializedJsonModel);
}
private async Task<Member> GetCurrentUserAsync()
{
return await _userManager.GetUserAsync(HttpContext.User);
}
[Route("/quan-ly-web/cau-do-dac-biet/chi-tiet/{id}")]
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var multiPuzzle = await _context.MultiPuzzle
.Include(m => m.Author)
.Include(m => m.Image)
.SingleOrDefaultAsync(m => m.ID == id);
if (multiPuzzle == null)
{
return NotFound();
}
ViewData["ListSinglePuzzle"] = await _context.SinglePuzzle.Where(p => p.MultiPuzzleID == id).ToListAsync();
return View(multiPuzzle);
}
[Route("/quan-ly-web/cau-do-dac-biet/chinh-sua/{id}")]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var multiPuzzle = await _repository.GetEdit(id);
if (multiPuzzle == null)
{
return NotFound();
}
AllSelectList allSelectList = new AllSelectList();
ViewData["Approved"] = new SelectList(allSelectList.ListApproved, "ID", "Name", multiPuzzle.Approved);
ViewData["ImageID"] = new SelectList(_context.Images, "ID", "Name", multiPuzzle.ImageID);
return View(multiPuzzle);
}
// POST: WebManager/MultiPuzzlesD/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[Route("/quan-ly-web/cau-do-dac-biet/chinh-sua/{id}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, EditMultiPuzzleViewModel multiPuzzle)
{
if (id != multiPuzzle.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
await _repository.Update(multiPuzzle);
}
catch (DbUpdateConcurrencyException)
{
if (!MultiPuzzleExists(multiPuzzle.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
ViewData["ImageID"] = new SelectList(_context.Images, "ID", "ID", multiPuzzle.ImageID);
return View(multiPuzzle);
}
[Route("/quan-ly-web/cau-do-dac-biet/xoa/{id}")]
// GET: WebManager/MultiPuzzlesD/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var multiPuzzle = await _repository.Get(id);
if (multiPuzzle == null)
{
return NotFound();
}
return View(multiPuzzle);
}
[Route("/quan-ly-web/cau-do-dac-biet/xoa /{id}")]
// POST: WebManager/MultiPuzzlesD/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
await _repository.Delete(id);
return RedirectToAction("Index");
}
private bool MultiPuzzleExists(int id)
{
return _context.MultiPuzzle.Any(e => e.ID == id);
}
[Route("/quan-ly-web/cau-do-dac-biet/chinh-sua-xuat-ban/{id}")]
public async Task<IActionResult> EditPublishDT(int? id)
{
if (id == null)
{
return NotFound();
}
var singlePuzzle = await _repository.GetEditPublishDT(id);
return View(singlePuzzle);
}
[Route("/quan-ly-web/cau-do-dac-biet/chinh-sua-xuat-ban/{id}")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EditPublishDT(PublishDatetimeSinglePuzzleViewModel model)
{
if (ModelState.IsValid)
{
try
{
await _repository.UpdatePublishDT(model);
}
catch (DbUpdateConcurrencyException)
{
return NotFound();
}
return RedirectToAction("Index");
}
return View(model);
}
}
}
| |
using System;
using NUnit.Framework;
using System.Collections.Generic;
using System.Management.Automation;
using System.IO;
namespace ReferenceTests.Commands
{
[TestFixture]
public class CsvTests : ReferenceTestBase
{
private string[] _commonProperties = new [] { "name", "age", "sex" };
private Dictionary<string, object>[] _data = new []
{
new Dictionary<string, object> {{"name", "John Doe"}, {"age", "45"}, {"sex", "m"}},
new Dictionary<string, object> {{"name", "Foobar\t"}, {"age", "25"}, {"sex", "f"}, {"randomfield", "blub"}},
new Dictionary<string, object> {{"name", "Joe,"}, {"age", "23"}, {"sex", "m"}},
new Dictionary<string, object> {{"name", "'Jack"}, {"age", "15"}, {"sex", "m'"}},
new Dictionary<string, object> {{"name", "Any,bo\"\"dy"}, {"age", "8\"9"}, {"sex", ""}},
new Dictionary<string, object> {{"name", "Ma\"\"ry"}, {"age", null}, {"sex", null}},
new Dictionary<string, object> {{"name", "Jane" + Environment.NewLine + ",12"}, {"age", "3"}, {"sex", "f" + Environment.NewLine}}
};
private string[] ExecuteGenerateCsvCommand(bool exportToFile, string input, string args)
{
var fname = "__tmpCsvExport.csv";
var cmd = input + " | ";
cmd += exportToFile ? "Export-Csv -Path " + fname + " " + args : "ConvertTo-Csv " + args;
var results = ReferenceHost.Execute(cmd).Split(new []{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
if (exportToFile)
{
results = ReadLinesFromFile(fname);
File.Delete(fname);
}
return results;
}
[Test]
public void ImportCsvWorksRobustly()
{
var csvFile = CreateFile(NewlineJoin(
"name, age,\t\tsex", // tabs shouldn't matter, last commas neither
"John Doe,45,m", // a normal data set
"Foobar\t,\t\t25,f,randomdata,", // tabs are stripped only at beginning, extra data is ignored and shouldn't cause an error
"\"Joe,\",23,m", //delimiter is in quotes
"'Jack,15,m'", // single quotes don't introduce a string as double quotes
"\"Any,\"bo\"\"dy, 8\"9,", // escape only if beginning with quote. missing value => empty string
"\"Ma\"\"\"\"ry\"", // missing fields, early NL => other fields are null. "" in quotes => escaped quote
"\"Jane", // starting the quotes, include newline; no finishing quote (file end)
",12\",3,\"f"), // rest of "Jane"
"csv");
var results = ReferenceHost.RawExecute(String.Format("Import-Csv {0}", csvFile));
Assert.AreEqual(_data.Length, results.Count);
for (int i = 0; i < _data.Length; i++)
{
foreach (var prop in _commonProperties)
{
var resProp = results[i].Properties[prop];
Assert.NotNull(resProp);
Assert.AreEqual(_data[i][prop], resProp.Value, prop + " doesn't match");
}
}
}
[Test]
public void ImportCsvWithDifferentDelimiter()
{
var csvFile = CreateFile(NewlineJoin(
"foo|bar",
"\"1|2\"|3"
), "csv");
var results = ReferenceHost.RawExecute(String.Format("Import-Csv {0} -Delimiter '|'", csvFile));
Assert.AreEqual(1, results.Count);
Assert.AreEqual("1|2", results[0].Properties["foo"].Value);
Assert.AreEqual("3", results[0].Properties["bar"].Value);
}
[Test]
public void ImportCsvWithDifferentHeader()
{
var csvFile = CreateFile(NewlineJoin(
"name, age",
"John,40"
), "csv");
var results = ReferenceHost.RawExecute(String.Format("Import-Csv {0} -Header 'his name','his age','his sex'", csvFile));
Assert.AreEqual(2, results.Count); // first line is interpreted as data
Assert.AreEqual("name", results[0].Properties["his name"].Value);
Assert.AreEqual("age", results[0].Properties["his age"].Value);
Assert.NotNull(results[0].Properties["his sex"]); // property should exist, but value has to be null
Assert.AreEqual(null, results[0].Properties["his sex"].Value);
Assert.AreEqual("John", results[1].Properties["his name"].Value);
Assert.AreEqual("40", results[1].Properties["his age"].Value);
Assert.NotNull(results[1].Properties["his sex"]); // property should exist, but value has to be null
Assert.AreEqual(null, results[1].Properties["his sex"].Value);
}
[TestCase(""), Explicit("Starting with PowerShell v3 this case results in the respective column being dropped if it occurs at the end of the line. Otherwise a generated name will be used for the header.")] // empty field name
[TestCase("name")] // twice the same name
public void ImportCsvNeedsValidHeader(string invalidHeader)
{
var csvFile = CreateFile(NewlineJoin(
"name, age," + invalidHeader,
"John,40,Doe"
), "csv");
// TODO: need to fix the exception type somewhere in the pipeline processing
Assert.Throws(Is.InstanceOf(typeof(Exception)), delegate() {
ReferenceHost.RawExecute(String.Format("Import-Csv {0}", csvFile));
});
}
[Test]
public void ImportCsvDoesntThrowOnImportingAnEmptyFile()
{
var csvFile = CreateFile("", "csv");
var result = ReferenceHost.RawExecute(String.Format("Import-Csv {0}", csvFile));
Assert.AreEqual(0, result.Count);
}
[Test]
public void ImportCsvImportsTypeName()
{
var csvFile = CreateFile(NewlineJoin(
"#TYPE My.Custom.Person",
"name,age",
"John,40"
), "csv");
var result = ReferenceHost.RawExecute(String.Format("Import-Csv {0}", csvFile));
Assert.AreEqual(1, result.Count);
Assert.Contains("CSV:My.Custom.Person", result[0].TypeNames);
}
[TestCase(true)]
[TestCase(false)]
public void GenerateCsvExportsDataCorrectly(bool exportToFile)
{
var expected = new string[] {
"#TYPE System.Management.Automation.PSCustomObject",
"\"name\",\"age\",\"sex\"",
"\"John Doe\",\"45\",\"m\"",
"\"Foobar\t\",\"25\",\"f\"",
"\"Joe,\",\"23\",\"m\"",
"\"'Jack\",\"15\",\"m'\"",
"\"Any,bo\"\"\"\"dy\",\"8\"\"9\",\"\"",
"\"Ma\"\"\"\"ry\",,",
"\"Jane",
",12\",\"3\",\"f",
"\""
};
var objectCmd = CreateObjectsCommand(_data);
var result = ExecuteGenerateCsvCommand(true, objectCmd, "");
Assert.AreEqual(expected, result);
}
[TestCase(true)]
[TestCase(false)]
public void GenerateCsvWithOtherDelimiter(bool exportToFile)
{
var expected = new string[] {
"#TYPE System.Management.Automation.PSCustomObject",
"\"name\"|\"age\"|\"sex\"",
"\"John Doe\"|\"45\"|\"m\""
};
var objectCmd = CreateObjectsCommand(new[] { _data[0] });
var result = ExecuteGenerateCsvCommand(true, objectCmd, "-Delimiter '|'");
Assert.AreEqual(expected, result);
}
[TestCase(true)]
[TestCase(false)]
public void GenerateCsvWithoutTypedata(bool exportToFile)
{
var expected = new string[] {
"\"name\",\"age\",\"sex\"",
"\"John Doe\",\"45\",\"m\""
};
var objectCmd = CreateObjectsCommand(new[] { _data[0] });
var result = ExecuteGenerateCsvCommand(true, objectCmd, "-NoTypeInformation");
Assert.AreEqual(expected, result);
}
[Test]
public void GenerateCsvFirstDataSetDeterminesHeader()
{
var expectedHeaders = new [] {
"\"randomfield\"","\"name\"","\"age\"","\"sex\""
};
var objectCmd = CreateObjectsCommand(new[] { _data[1], _data[0] });
var result = ExecuteGenerateCsvCommand(true, objectCmd, "");
var resultHeaders = result[1].Split(new [] { ',' }, StringSplitOptions.None);
Assert.AreEqual(expectedHeaders.Length, resultHeaders.Length);
foreach (var h in expectedHeaders)
{
Assert.Contains(h, resultHeaders);
}
}
[Test]
public void ExportCsvOverwritesByDefault()
{
var expected = new string[] {
"#TYPE System.Management.Automation.PSCustomObject",
"\"name\",\"age\",\"sex\"",
"\"Joe,\",\"23\",\"m\""
};
var exportFileName = "__tmpExportedCsvData.csv";
var objectCmd = CreateObjectsCommand(new[] { _data[0] });
ReferenceHost.Execute(String.Format("{0} | Export-Csv {1}", objectCmd, exportFileName));
objectCmd = CreateObjectsCommand(new[] { _data[2] });
ReferenceHost.Execute(String.Format("{0} | Export-Csv {1}", objectCmd, exportFileName));
var lines = ReadLinesFromFile(exportFileName);
File.Delete(exportFileName);
Assert.AreEqual(expected, lines);
}
[Test]
public void ExportCsvDoesNotOverwriteWithClobberArg()
{
var exportFileName = "__tmpExportedCsvData.csv";
var objectCmd = CreateObjectsCommand(new[] { _data[0] });
ReferenceHost.Execute(String.Format("{0} | Export-Csv {1}", objectCmd, exportFileName));
objectCmd = CreateObjectsCommand(new[] { _data[1] });
// TODO: need to fix the exception type somewhere in the pipeline processing
Assert.Throws(Is.InstanceOf(typeof(Exception)), delegate () {
ReferenceHost.Execute(String.Format("{0} | Export-Csv {1} -NoClobber", objectCmd, exportFileName));
});
}
}
}
| |
//#define IMITATE_BATCH_MODE //uncomment if you want to imitate batch mode behaviour in non-batch mode mode run
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityTest.IntegrationTestRunner;
namespace UnityTest
{
[Serializable]
public class TestRunner : MonoBehaviour
{
static private TestResultRenderer resultRenderer = new TestResultRenderer ();
public TestComponent currentTest;
private List<TestResult> resultList = new List<TestResult> ();
private List<TestComponent> testComponents;
public bool isInitializedByRunner
{
get
{
#if !IMITATE_BATCH_MODE
if (Application.isEditor && !isBatchMode ())
return true;
#endif
return false;
}
}
private double startTime;
private bool readyToRun;
private AssertionComponent[] assertionsToCheck = null;
private string testMessages;
private string stacktrace;
private TestState testState = TestState.Running;
private TestRunnerConfigurator configurator;
public TestRunnerCallbackList TestRunnerCallback = new TestRunnerCallbackList();
private IntegrationTestsProvider testsProvider;
private const string prefix = "IntegrationTest";
private const string startedMessage = prefix + " Started";
private const string finishedMessage = prefix + " Finished";
private const string timeoutMessage = prefix + " Timeout";
private const string failedMessage = prefix + " Failed";
private const string failedExceptionMessage = prefix + " Failed with exception";
private const string ignoredMessage = prefix + " Ignored";
private const string interruptedMessage = prefix + " Run interrupted";
public void Awake ()
{
configurator = new TestRunnerConfigurator ();
if (isInitializedByRunner) return;
TestComponent.DisableAllTests ();
}
public void Start ()
{
if (isInitializedByRunner) return;
if (configurator.sendResultsOverNetwork)
{
var nrs = configurator.ResolveNetworkConnection ();
if(nrs!=null)
TestRunnerCallback.Add (nrs);
}
TestComponent.DestroyAllDynamicTests ();
var dynamicTestTypes = TestComponent.GetTypesWithHelpAttribute (Application.loadedLevelName);
foreach (var dynamicTestType in dynamicTestTypes)
TestComponent.CreateDynamicTest (dynamicTestType);
var tests = TestComponent.FindAllTestsOnScene ();
InitRunner (tests, dynamicTestTypes.Select (type => type.AssemblyQualifiedName).ToList ());
}
public void InitRunner(List<TestComponent> tests, List<string> dynamicTestsToRun)
{
currentlyRegisteredLogCallback = GetLogCallbackField ();
logCallback = LogHandler;
Application.RegisterLogCallback (logCallback);
//Init dynamic tests
foreach (var typeName in dynamicTestsToRun)
{
var t = Type.GetType (typeName);
if (t == null) continue;
var scriptComponents = Resources.FindObjectsOfTypeAll (t) as MonoBehaviour[];
if (scriptComponents.Length == 0)
{
Debug.LogWarning (t + " not found. Skipping.");
continue;
}
if (scriptComponents.Length > 1) Debug.LogWarning ("Multiple GameObjects refer to " + typeName);
tests.Add (scriptComponents.First().GetComponent<TestComponent> ());
}
//create test structure
testComponents = ParseListForGroups (tests).ToList ();
//create results for tests
resultList = testComponents.Select (component => new TestResult (component)).ToList ();
//init test provider
testsProvider = new IntegrationTestsProvider (resultList.Select (result => result.TestComponent as ITestComponent));
readyToRun = true;
}
private static IEnumerable<TestComponent> ParseListForGroups ( IEnumerable<TestComponent> tests )
{
var results = new HashSet<TestComponent> ();
foreach (var testResult in tests)
{
if (testResult.IsTestGroup ())
{
var childrenTestResult = testResult.gameObject.GetComponentsInChildren (typeof (TestComponent), true)
.Where (t=>t!=testResult)
.Cast<TestComponent> ()
.ToArray ();
foreach (var result in childrenTestResult)
{
if(!result.IsTestGroup())
results.Add (result);
}
continue;
}
results.Add (testResult);
}
return results;
}
public void Update ()
{
if (readyToRun && Time.frameCount > 1)
{
readyToRun = false;
StartCoroutine ("StateMachine");
}
LogCallbackStillRegistered ();
}
public void OnDestroy()
{
if (currentTest != null)
{
var testResult = resultList.Single (result => result.TestComponent == currentTest);
testResult.messages += "Test run interrupted (crash?)";
LogMessage(interruptedMessage);
FinishTest(TestResult.ResultType.Failed);
}
if (currentTest != null || (testsProvider != null && testsProvider.AnyTestsLeft ()))
{
var remainingTests = testsProvider.GetRemainingTests ();
TestRunnerCallback.TestRunInterrupted( remainingTests.ToList () );
}
Application.RegisterLogCallback(null);
}
private void LogHandler (string condition, string stacktrace, LogType type)
{
if (!condition.StartsWith (startedMessage) && !condition.StartsWith (finishedMessage))
{
var msg = condition;
if (msg.StartsWith(prefix)) msg = msg.Substring(prefix.Length+1);
if (currentTest != null && msg.EndsWith ("(" + currentTest.name + ')')) msg = msg.Substring (0, msg.LastIndexOf ('('));
testMessages += msg + "\n";
}
if (type == LogType.Exception)
{
var exceptionType = condition.Substring (0, condition.IndexOf(':'));
if (currentTest.IsExceptionExpected (exceptionType))
{
testMessages += exceptionType + " was expected\n";
if (currentTest.ShouldSucceedOnException())
{
testState = TestState.Success;
}
}
else
{
testState = TestState.Exception;
this.stacktrace = stacktrace;
}
}
else if (type == LogType.Error || type == LogType.Assert)
{
testState = TestState.Failure;
this.stacktrace = stacktrace;
}
else if (type == LogType.Log)
{
if (testState == TestState.Running && condition.StartsWith (IntegrationTest.passMessage))
{
testState = TestState.Success;
}
if (condition.StartsWith(IntegrationTest.failMessage))
{
testState = TestState.Failure;
}
}
}
public IEnumerator StateMachine ()
{
TestRunnerCallback.RunStarted (Application.platform.ToString (), testComponents);
while (true)
{
if (!testsProvider.AnyTestsLeft() && currentTest == null)
{
FinishTestRun ();
yield break;
}
if (currentTest == null)
{
StartNewTest ();
}
if (currentTest != null)
{
if (testState == TestState.Running)
{
if (assertionsToCheck != null && assertionsToCheck.All (a => a.checksPerformed > 0))
{
IntegrationTest.Pass (currentTest.gameObject);
testState = TestState.Success;
}
if (currentTest != null && Time.time > startTime + currentTest.GetTimeout())
{
testState = TestState.Timeout;
}
}
switch (testState)
{
case TestState.Success:
LogMessage (finishedMessage);
FinishTest (TestResult.ResultType.Success);
break;
case TestState.Failure:
LogMessage (failedMessage);
FinishTest (TestResult.ResultType.Failed);
break;
case TestState.Exception:
LogMessage (failedExceptionMessage);
FinishTest (TestResult.ResultType.FailedException);
break;
case TestState.Timeout:
LogMessage(timeoutMessage);
FinishTest(TestResult.ResultType.Timeout);
break;
case TestState.Ignored:
LogMessage (ignoredMessage);
FinishTest(TestResult.ResultType.Ignored);
break;
}
}
yield return null;
}
}
private void LogMessage(string message)
{
if (currentTest != null)
Debug.Log (message + " (" + currentTest.Name + ")", currentTest.gameObject);
else
Debug.Log (message);
}
private void FinishTestRun ()
{
PrintResultToLog ();
TestRunnerCallback.RunFinished (resultList);
LoadNextLevelOrQuit ();
}
private void PrintResultToLog ()
{
var resultString = "";
resultString += "Passed: " + resultList.Count (t => t.IsSuccess);
if (resultList.Any (result => result.IsFailure))
{
resultString += " Failed: " + resultList.Count (t => t.IsFailure);
Debug.Log ("Failed tests: " + string.Join (", ", resultList.Where (t => t.IsFailure).Select (result => result.Name).ToArray ()));
}
if (resultList.Any (result => result.IsIgnored))
{
resultString += " Ignored: " + resultList.Count (t => t.IsIgnored);
Debug.Log ("Ignored tests: " + string.Join (", ",
resultList.Where (t => t.IsIgnored).Select (result => result.Name).ToArray ()));
}
Debug.Log (resultString);
}
private void LoadNextLevelOrQuit ()
{
if (isInitializedByRunner) return;
if (Application.loadedLevel < Application.levelCount - 1)
Application.LoadLevel (Application.loadedLevel + 1);
else
{
resultRenderer.ShowResults();
if (configurator.isBatchRun && configurator.sendResultsOverNetwork)
Application.Quit ();
}
}
public void OnGUI ()
{
resultRenderer.Draw ();
}
private void StartNewTest ()
{
this.testMessages = "";
this.stacktrace = "";
testState = TestState.Running;
assertionsToCheck = null;
startTime = Time.time;
currentTest = testsProvider.GetNextTest () as TestComponent;
var testResult = resultList.Single (result => result.TestComponent == currentTest);
if (currentTest.ShouldSucceedOnAssertions ())
{
var assertionList = currentTest.gameObject.GetComponentsInChildren<AssertionComponent> ().Where (a => a.enabled);
if(assertionList.Any())
assertionsToCheck = assertionList.ToArray();
}
if (currentTest.IsExludedOnThisPlatform ())
{
testState = TestState.Ignored;
Debug.Log(currentTest.gameObject.name + " is excluded on this platform");
}
//don't ignore test if user initiated it from the runner and it's the only test that is being run
if (currentTest.IsIgnored () && !(isInitializedByRunner && resultList.Count == 1)) testState = TestState.Ignored;
LogMessage(startedMessage);
TestRunnerCallback.TestStarted (testResult);
}
private void FinishTest(TestResult.ResultType result)
{
testsProvider.FinishTest (currentTest);
var testResult = resultList.Single (t => t.GameObject == currentTest.gameObject);
testResult.resultType = result;
testResult.duration = Time.time - startTime;
testResult.messages = testMessages;
testResult.stacktrace = stacktrace;
TestRunnerCallback.TestFinished (testResult);
currentTest = null;
if (!testResult.IsSuccess
&& testResult.Executed
&& !testResult.IsIgnored) resultRenderer.AddResults (Application.loadedLevelName, testResult);
}
#region Test Runner Helpers
public static TestRunner GetTestRunner ()
{
TestRunner testRunnerComponent = null;
var testRunnerComponents = Resources.FindObjectsOfTypeAll(typeof(TestRunner));
if (testRunnerComponents.Count () > 1)
foreach (var t in testRunnerComponents) DestroyImmediate((t as TestRunner).gameObject);
else if (!testRunnerComponents.Any())
testRunnerComponent = Create().GetComponent<TestRunner>();
else
testRunnerComponent = testRunnerComponents.Single() as TestRunner;
return testRunnerComponent;
}
private static GameObject Create()
{
var runner = new GameObject ("TestRunner");
var component = runner.AddComponent<TestRunner> ();
component.hideFlags = HideFlags.NotEditable;
Debug.Log ("Created Test Runner");
return runner;
}
private static bool isBatchMode ()
{
#if !UNITY_METRO
var InternalEditorUtilityClassName = "UnityEditorInternal.InternalEditorUtility, UnityEditor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
var t = Type.GetType(InternalEditorUtilityClassName, false);
if (t == null) return false;
var inBatchModeProperty = "inBatchMode";
var prop = t.GetProperty (inBatchModeProperty);
return (bool) prop.GetValue (null, null);
#else
return false;
#endif
}
#endregion
#region LogCallback check
private Application.LogCallback logCallback;
private FieldInfo currentlyRegisteredLogCallback;
public void LogCallbackStillRegistered()
{
if (Application.platform == RuntimePlatform.OSXWebPlayer
|| Application.platform == RuntimePlatform.WindowsWebPlayer)
return;
if (currentlyRegisteredLogCallback == null) return;
var v = (Application.LogCallback)currentlyRegisteredLogCallback.GetValue(null);
if (v == logCallback) return;
Debug.LogError("Log callback got changed. This may be caused by other tools using RegisterLogCallback.");
Application.RegisterLogCallback(logCallback);
}
private FieldInfo GetLogCallbackField()
{
#if !UNITY_METRO
var type = typeof(Application);
var f = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic).Where(p => p.Name == "s_LogCallback");
if (f.Count() != 1) return null;
return f.Single();
#else
return null;
#endif
}
#endregion
enum TestState
{
Running,
Success,
Failure,
Exception,
Timeout,
Ignored
}
}
}
| |
/*
* Created by: Leslie Sanford (08/27/2003)
* Contact: jabberdabber@hotmail.com
*
* http://www.codeproject.com/KB/recipes/skiplist1.aspx
*/
using System;
using System.Collections;
using System.Resources;
using System.Reflection;
namespace LSCollections
{
/// <summary>
/// Represents a collection of key-and-value pairs.
/// </summary>
/// <remarks>
/// The SkipList class is an implementation of the IDictionary interface. It
/// is based on the data structure created by William Pugh.
/// </remarks>
public class SkipList : IDictionary
{
#region SkipList Members
#region Constants
// Maximum level any node in a skip list can have
private const int MaxLevel = 32;
// Probability factor used to determine the node level
private const double Probability = 0.5;
#endregion
#region Fields
// The skip list header. It also serves as the NIL node.
private Node header = new Node(MaxLevel);
// Comparer for comparing keys.
private IComparer comparer;
// Random number generator for generating random node levels.
private Random random = new Random();
// Current maximum list level.
private int listLevel;
// Current number of elements in the skip list.
private int count;
// Version of the skip list. Used for validation checks with
// enumerators.
private long version = 0;
// Resource manager for retrieving exception messages.
private ResourceManager resManager;
#endregion
/// <summary>
/// Initializes a new instance of the SkipList class that is empty and
/// is sorted according to the IComparable interface implemented by
/// each key added to the SkipList.
/// </summary>
/// <remarks>
/// Each key must implement the IComparable interface to be capable of
/// comparisons with every other key in the SortedList. The elements
/// are sorted according to the IComparable implementation of each key
/// added to the SkipList.
/// </remarks>
public SkipList()
{
// Initialize the skip list.
Initialize();
// Load resources.
resManager =
new ResourceManager("LSCollections.Resource",
this.GetType().Assembly);
}
/// <summary>
/// Initializes a new instance of the SkipList class that is empty and
/// is sorted according to the specified IComparer interface.
/// </summary>
/// <param name="comparer">
/// The IComparer implementation to use when comparing keys.
/// </param>
/// <remarks>
/// The elements are sorted according to the specified IComparer
/// implementation. If comparer is a null reference, the IComparable
/// implementation of each key is used; therefore, each key must
/// implement the IComparable interface to be capable of comparisons
/// with every other key in the SkipList.
/// </remarks>
public SkipList(IComparer comparer)
{
// Initialize comparer with the client provided comparer.
this.comparer = comparer;
// Initialize the skip list.
Initialize();
// Load resources.
resManager =
new ResourceManager("LSCollections.Resource",
this.GetType().Assembly);
}
~SkipList()
{
Clear();
}
#region Private Helper Methods
/// <summary>
/// Initializes the SkipList.
/// </summary>
private void Initialize()
{
listLevel = 1;
count = 0;
// When the list is empty, make sure all forward references in the
// header point back to the header. This is important because the
// header is used as the sentinel to mark the end of the skip list.
for(int i = 0; i < MaxLevel; i++)
{
header.forward[i] = header;
}
}
/// <summary>
/// Returns a level value for a new SkipList node.
/// </summary>
/// <returns>
/// The level value for a new SkipList node.
/// </returns>
private int GetNewLevel()
{
int level = 1;
// Determines the next node level.
while(random.NextDouble() < Probability && level < MaxLevel &&
level <= listLevel)
{
level++;
}
return level;
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool Search(object key)
{
Node curr;
Node[] dummy = new Node[MaxLevel];
return Search(key, out curr, dummy);
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
/// <remarks>
private bool Search(object key, out Node curr)
{
Node[] dummy = new Node[MaxLevel];
return Search(key, out curr, dummy);
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool Search(object key, Node[] update)
{
Node curr;
return Search(key, out curr, update);
}
/// <summary>
/// Searches for the specified key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool Search(object key, out Node curr, Node[] update)
{
// Make sure key isn't null.
if(key == null)
{
string msg = resManager.GetString("NullKey");
throw new ArgumentNullException(msg);
}
bool result;
// Check to see if we will search with a comparer.
if(comparer != null)
{
result = SearchWithComparer(key, out curr, update);
}
// Else we're using the IComparable interface.
else
{
result = SearchWithComparable(key, out curr, update);
}
return result;
}
/// <summary>
/// Search for the specified key using a comparer.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
private bool SearchWithComparer(object key, out Node curr,
Node[] update)
{
bool found = false;
// Start from the beginning of the skip list.
curr = header;
// Work our way down from the top of the skip list to the bottom.
for(int i = listLevel - 1; i >= 0; i--)
{
// While we haven't reached the end of the skip list and the
// current key is less than the new key.
while(curr.forward[i] != header &&
comparer.Compare(curr.forward[i].entry.Key, key) < 0)
{
// Move forward in the skip list.
curr = curr.forward[i];
}
// Keep track of each node where we move down a level. This
// will be used later to rearrange node references when
// inserting a new element.
update[i] = curr;
}
// Move ahead in the skip list. If the new key doesn't already
// exist in the skip list, this should put us at either the end of
// the skip list or at a node with a key greater than the sarch key.
// If the new key already exists in the skip list, this should put
// us at a node with a key equal to the search key.
curr = curr.forward[0];
// If we haven't reached the end of the skip list and the
// current key is equal to the search key.
if(curr != header && comparer.Compare(key, curr.entry.Key) == 0)
{
// Indicate that we've found the search key.
found = true;
}
return found;
}
/// <summary>
/// Search for the specified key using the IComparable interface
/// implemented by each key.
/// </summary>
/// <param name="key">
/// The key to search for.
/// </param>
/// <param name="curr">
/// A SkipList node to hold the results of the search.
/// </param>
/// <param name="update">
/// An array of nodes holding references to the places in the SkipList
/// search in which the search dropped down one level.
/// </param>
/// <returns>
/// Returns true if the specified key is in the SkipList.
/// </returns>
/// <remarks>
/// Assumes each key inserted into the SkipList implements the
/// IComparable interface.
///
/// If the specified key is in the SkipList, the curr parameter will
/// reference the node with the key. If the specified key is not in the
/// SkipList, the curr paramater will either hold the node with the
/// first key value greater than the specified key or null indicating
/// that the search reached the end of the SkipList.
/// </remarks>
private bool SearchWithComparable(object key, out Node curr,
Node[] update)
{
// Make sure key is comparable.
if(!(key is IComparable))
{
string msg = resManager.GetString("ComparableError");
throw new ArgumentException(msg);
}
bool found = false;
IComparable comp;
// Begin at the start of the skip list.
curr = header;
// Work our way down from the top of the skip list to the bottom.
for(int i = listLevel - 1; i >= 0; i--)
{
// Get the comparable interface for the current key.
comp = (IComparable)curr.forward[i].entry.Key;
// While we haven't reached the end of the skip list and the
// current key is less than the search key.
while(curr.forward[i] != header && comp.CompareTo(key) < 0)
{
// Move forward in the skip list.
curr = curr.forward[i];
// Get the comparable interface for the current key.
comp = (IComparable)curr.forward[i].entry.Key;
}
// Keep track of each node where we move down a level. This
// will be used later to rearrange node references when
// inserting a new element.
update[i] = curr;
}
// Move ahead in the skip list. If the new key doesn't already
// exist in the skip list, this should put us at either the end of
// the skip list or at a node with a key greater than the search key.
// If the new key already exists in the skip list, this should put
// us at a node with a key equal to the search key.
curr = curr.forward[0];
// Get the comparable interface for the current key.
comp = (IComparable)curr.entry.Key;
// If we haven't reached the end of the skip list and the
// current key is equal to the search key.
if(curr != header && comp.CompareTo(key) == 0)
{
// Indicate that we've found the search key.
found = true;
}
return found;
}
/// <summary>
/// Inserts a key/value pair into the SkipList.
/// </summary>
/// <param name="key">
/// The key to insert into the SkipList.
/// </param>
/// <param name="val">
/// The value to insert into the SkipList.
/// </param>
/// <param name="update">
/// An array of nodes holding references to places in the SkipList in
/// which the search for the place to insert the new key/value pair
/// dropped down one level.
/// </param>
private void Insert(object key, object val, Node[] update)
{
// Get the level for the new node.
int newLevel = GetNewLevel();
// If the level for the new node is greater than the skip list
// level.
if(newLevel > listLevel)
{
// Make sure our update references above the current skip list
// level point to the header.
for(int i = listLevel; i < newLevel; i++)
{
update[i] = header;
}
// The current skip list level is now the new node level.
listLevel = newLevel;
}
// Create the new node.
Node newNode = new Node(newLevel, key, val);
// Insert the new node into the skip list.
for(int i = 0; i < newLevel; i++)
{
// The new node forward references are initialized to point to
// our update forward references which point to nodes further
// along in the skip list.
newNode.forward[i] = update[i].forward[i];
// Take our update forward references and point them towards
// the new node.
update[i].forward[i] = newNode;
}
// Keep track of the number of nodes in the skip list.
count++;
// Indicate that the skip list has changed.
version++;
}
#endregion
#endregion
#region Node Class
/// <summary>
/// Represents a node in the SkipList.
/// </summary>
private class Node : IDisposable
{
#region Fields
// References to nodes further along in the skip list.
public Node[] forward;
// The key/value pair.
public DictionaryEntry entry;
#endregion
/// <summary>
/// Initializes an instant of a Node with its node level.
/// </summary>
/// <param name="level">
/// The node level.
/// </param>
public Node(int level)
{
forward = new Node[level];
}
/// <summary>
/// Initializes an instant of a Node with its node level and
/// key/value pair.
/// </summary>
/// <param name="level">
/// The node level.
/// </param>
/// <param name="key">
/// The key for the node.
/// </param>
/// <param name="val">
/// The value for the node.
/// </param>
public Node(int level, object key, object val)
{
forward = new Node[level];
entry.Key = key;
entry.Value = val;
}
#region IDisposable Members
/// <summary>
/// Disposes the Node.
/// </summary>
public void Dispose()
{
for(int i = 0; i < forward.Length; i++)
{
forward[i] = null;
}
}
#endregion
}
#endregion
#region SkipListEnumerator Class
/// <summary>
/// Enumerates the elements of a skip list.
/// </summary>
private class SkipListEnumerator : IDictionaryEnumerator
{
#region SkipListEnumerator Members
#region Fields
// The skip list to enumerate.
private SkipList list;
// The current node.
private Node current;
// The version of the skip list we are enumerating.
private long version;
// Keeps track of previous move result so that we can know
// whether or not we are at the end of the skip list.
private bool moveResult = true;
#endregion
/// <summary>
/// Initializes an instance of a SkipListEnumerator.
/// </summary>
/// <param name="list"></param>
public SkipListEnumerator(SkipList list)
{
this.list = list;
version = list.version;
current = list.header;
}
#endregion
#region IDictionaryEnumerator Members
/// <summary>
/// Gets both the key and the value of the current dictionary
/// entry.
/// </summary>
public DictionaryEntry Entry
{
get
{
DictionaryEntry entry;
// Make sure the skip list hasn't been modified since the
// enumerator was created.
if(version != list.version)
{
string msg = list.resManager.GetString("InvalidEnum");
throw new InvalidOperationException(msg);
}
// Make sure we are not before the beginning or beyond the
// end of the skip list.
else if(current == list.header)
{
string msg = list.resManager.GetString("BadEnumAccess");
throw new InvalidOperationException();
}
// Finally, all checks have passed. Get the current entry.
else
{
entry = current.entry;
}
return entry;
}
}
/// <summary>
/// Gets the key of the current dictionary entry.
/// </summary>
public object Key
{
get
{
object key = Entry.Key;
return key;
}
}
/// <summary>
/// Gets the value of the current dictionary entry.
/// </summary>
public object Value
{
get
{
object val = Entry.Value;
return val;
}
}
#endregion
#region IEnumerator Members
/// <summary>
/// Advances the enumerator to the next element of the skip list.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next
/// element; false if the enumerator has passed the end of the
/// skip list.
/// </returns>
public bool MoveNext()
{
// Make sure the skip list hasn't been modified since the
// enumerator was created.
if(version == list.version)
{
// If the result of the previous move operation was true
// we can still move forward in the skip list.
if(moveResult)
{
// Move forward in the skip list.
current = current.forward[0];
// If we are at the end of the skip list.
if(current == list.header)
{
// Indicate that we've reached the end of the skip
// list.
moveResult = false;
}
}
}
// Else this version of the enumerator doesn't match that of
// the skip list. The skip list has been modified since the
// creation of the enumerator.
else
{
string msg = list.resManager.GetString("InvalidEnum");
throw new InvalidOperationException(msg);
}
return moveResult;
}
/// <summary>
/// Sets the enumerator to its initial position, which is before
/// the first element in the skip list.
/// </summary>
public void Reset()
{
// Make sure the skip list hasn't been modified since the
// enumerator was created.
if(version == list.version)
{
current = list.header;
moveResult = true;
}
// Else this version of the enumerator doesn't match that of
// the skip list. The skip list has been modified since the
// creation of the enumerator.
else
{
string msg = list.resManager.GetString("InvalidEnum");
throw new InvalidOperationException(msg);
}
}
/// <summary>
/// Gets the current element in the skip list.
/// </summary>
public object Current
{
get
{
return Value;
}
}
#endregion
}
#endregion
#region IDictionary Members
/// <summary>
/// Adds an element with the provided key and value to the SkipList.
/// </summary>
/// <param name="key">
/// The Object to use as the key of the element to add.
/// </param>
/// <param name="value">
/// The Object to use as the value of the element to add.
/// </param>
public void Add(object key, object value)
{
Node[] update = new Node[MaxLevel];
// If key does not already exist in the skip list.
if(!Search(key, update))
{
// Inseart key/value pair into the skip list.
Insert(key, value, update);
}
// Else throw an exception. The IDictionary Add method throws an
// exception if an attempt is made to add a key that already
// exists in the skip list.
else
{
string msg = resManager.GetString("KeyExistsAdd");
throw new ArgumentException(msg);
}
}
/// <summary>
/// Removes all elements from the SkipList.
/// </summary>
public void Clear()
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
Node prev;
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Keep track of the previous node.
prev = curr;
// Move forward in the skip list.
curr = curr.forward[0];
// Dispose of the previous node.
prev.Dispose();
}
// Initialize skip list and indicate that it has been changed.
Initialize();
version++;
}
/// <summary>
/// Determines whether the SkipList contains an element with the
/// specified key.
/// </summary>
/// <param name="key">
/// The key to locate in the SkipList.
/// </param>
/// <returns>
/// true if the SkipList contains an element with the key; otherwise,
/// false.
/// </returns>
public bool Contains(object key)
{
return Search(key);
}
/// <summary>
/// Returns an IDictionaryEnumerator for the SkipList.
/// </summary>
/// <returns>
/// An IDictionaryEnumerator for the SkipList.
/// </returns>
public IDictionaryEnumerator GetEnumerator()
{
return new SkipListEnumerator(this);
}
/// <summary>
/// Removes the element with the specified key from the SkipList.
/// </summary>
/// <param name="key">
/// The key of the element to remove.
/// </param>
public void Remove(object key)
{
Node[] update = new Node[MaxLevel];
Node curr;
if(Search(key, out curr, update))
{
// Take the forward references that point to the node to be
// removed and reassign them to the nodes that come after it.
for(int i = 0; i < listLevel &&
update[i].forward[i] == curr; i++)
{
update[i].forward[i] = curr.forward[i];
}
curr.Dispose();
// After removing the node, we may need to lower the current
// skip list level if the node had the highest level of all of
// the nodes.
while(listLevel > 1 && header.forward[listLevel - 1] == header)
{
listLevel--;
}
// Keep track of the number of nodes.
count--;
// Indicate that the skip list has changed.
version++;
}
}
/// <summary>
/// Gets a value indicating whether the SkipList has a fixed size.
/// </summary>
public bool IsFixedSize
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the IDictionary is read-only.
/// </summary>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Gets or sets the element with the specified key. This is the
/// indexer for the SkipList.
/// </summary>
public object this[object key]
{
get
{
object val = null;
Node curr;
if(Search(key, out curr))
{
val = curr.entry.Value;
}
return val;
}
set
{
Node[] update = new Node[MaxLevel];
Node curr;
// If the search key already exists in the skip list.
if(Search(key, out curr, update))
{
// Replace the current value with the new value.
curr.entry.Value = value;
// Indicate that the skip list has changed.
version++;
}
// Else the key doesn't exist in the skip list.
else
{
// Insert the key and value into the skip list.
Insert(key, value, update);
}
}
}
/// <summary>
/// Gets an ICollection containing the keys of the SkipList.
/// </summary>
public ICollection Keys
{
get
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
// Create a collection to hold the keys.
ArrayList collection = new ArrayList();
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Add the key to the collection.
collection.Add(curr.entry.Key);
// Move forward in the skip list.
curr = curr.forward[0];
}
return collection;
}
}
/// <summary>
/// Gets an ICollection containing the values of the SkipList.
/// </summary>
public ICollection Values
{
get
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
// Create a collection to hold the values.
ArrayList collection = new ArrayList();
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Add the value to the collection.
collection.Add(curr.entry.Value);
// Move forward in the skip list.
curr = curr.forward[0];
}
return collection;
}
}
#endregion
#region ICollection Members
/// <summary>
/// Copies the elements of the SkipList to an Array, starting at a
/// particular Array index.
/// </summary>
/// <param name="array">
/// The one-dimensional Array that is the destination of the elements
/// copied from SkipList.
/// </param>
/// <param name="index">
/// The zero-based index in array at which copying begins.
/// </param>
public void CopyTo(Array array, int index)
{
// Make sure array isn't null.
if(array == null)
{
string msg = resManager.GetString("NullArrayCopyTo");
throw new ArgumentNullException(msg);
}
// Make sure index is not negative.
else if(index < 0)
{
string msg = resManager.GetString("BadIndexCopyTo");
throw new ArgumentOutOfRangeException(msg);
}
// Array bounds checking.
else if(index >= array.Length)
{
string msg = resManager.GetString("BadIndexCopyTo");
throw new ArgumentException(msg);
}
// Make sure that the number of elements in the skip list is not
// greater than the available space from index to the end of the
// array.
else if((array.Length - index) < Count)
{
string msg = resManager.GetString("BadIndexCopyTo");
throw new ArgumentException(msg);
}
// Else copy elements from skip list into array.
else
{
// Start at the beginning of the skip list.
Node curr = header.forward[0];
// While we haven't reached the end of the skip list.
while(curr != header)
{
// Copy current value into array.
array.SetValue(curr.entry.Value, index);
// Move forward in the skip list and array.
curr = curr.forward[0];
index++;
}
}
}
/// <summary>
/// Gets the number of elements contained in the SkipList.
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// Gets a value indicating whether access to the SkipList is
/// synchronized (thread-safe).
/// </summary>
public bool IsSynchronized
{
get
{
return false;
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to the
/// SkipList.
/// </summary>
public object SyncRoot
{
get
{
return this;
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that can iterate through the SkipList.
/// </summary>
/// <returns>
/// An IEnumerator that can be used to iterate through the collection.
/// </returns>
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new SkipListEnumerator(this);
}
#endregion
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime
{
using System;
using System.Collections.Generic;
using System.Security;
using System.Threading;
[Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.MonitorWait, SupportsAsync = true, ReleaseMethod = "Set")]
class AsyncWaitHandle
{
static Action<object> timerCompleteCallback;
List<AsyncWaiter> asyncWaiters;
bool isSignaled;
EventResetMode resetMode;
[Fx.Tag.SynchronizationObject(Kind = Fx.Tag.SynchronizationKind.MonitorWait)]
object syncObject;
int syncWaiterCount;
public AsyncWaitHandle()
: this(EventResetMode.AutoReset)
{
}
public AsyncWaitHandle(EventResetMode resetMode)
{
this.resetMode = resetMode;
this.syncObject = new object();
}
public bool WaitAsync(Action<object, TimeoutException> callback, object state, TimeSpan timeout)
{
if (!this.isSignaled || (this.isSignaled && this.resetMode == EventResetMode.AutoReset))
{
lock (syncObject)
{
if (this.isSignaled && this.resetMode == EventResetMode.AutoReset)
{
this.isSignaled = false;
}
else if (!this.isSignaled)
{
AsyncWaiter waiter = new AsyncWaiter(this, callback, state);
if (this.asyncWaiters == null)
{
this.asyncWaiters = new List<AsyncWaiter>();
}
this.asyncWaiters.Add(waiter);
if (timeout != TimeSpan.MaxValue)
{
if (timerCompleteCallback == null)
{
timerCompleteCallback = new Action<object>(OnTimerComplete);
}
waiter.SetTimer(timerCompleteCallback, waiter, timeout);
}
return false;
}
}
}
return true;
}
static void OnTimerComplete(object state)
{
AsyncWaiter waiter = (AsyncWaiter)state;
AsyncWaitHandle thisPtr = waiter.Parent;
bool callWaiter = false;
lock (thisPtr.syncObject)
{
// If still in the waiting list (that means it hasn't been signaled)
if (thisPtr.asyncWaiters != null && thisPtr.asyncWaiters.Remove(waiter))
{
waiter.TimedOut = true;
callWaiter = true;
}
}
waiter.CancelTimer();
if (callWaiter)
{
waiter.Call();
}
}
[Fx.Tag.Blocking]
public bool Wait(TimeSpan timeout)
{
if (!this.isSignaled || (this.isSignaled && this.resetMode == EventResetMode.AutoReset))
{
lock (syncObject)
{
if (this.isSignaled && this.resetMode == EventResetMode.AutoReset)
{
this.isSignaled = false;
}
else if (!this.isSignaled)
{
bool decrementRequired = false;
try
{
try
{
}
finally
{
this.syncWaiterCount++;
decrementRequired = true;
}
if (timeout == TimeSpan.MaxValue)
{
if (!Monitor.Wait(syncObject, Timeout.Infinite))
{
return false;
}
}
else
{
if (!Monitor.Wait(syncObject, timeout))
{
return false;
}
}
}
finally
{
if (decrementRequired)
{
this.syncWaiterCount--;
}
}
}
}
}
return true;
}
public void Set()
{
List<AsyncWaiter> toCallList = null;
AsyncWaiter toCall = null;
if (!this.isSignaled)
{
lock (syncObject)
{
if (!this.isSignaled)
{
if (this.resetMode == EventResetMode.ManualReset)
{
this.isSignaled = true;
Monitor.PulseAll(syncObject);
toCallList = this.asyncWaiters;
this.asyncWaiters = null;
}
else
{
if (this.syncWaiterCount > 0)
{
Monitor.Pulse(syncObject);
}
else if (this.asyncWaiters != null && this.asyncWaiters.Count > 0)
{
toCall = this.asyncWaiters[0];
this.asyncWaiters.RemoveAt(0);
}
else
{
this.isSignaled = true;
}
}
}
}
}
if (toCallList != null)
{
foreach (AsyncWaiter waiter in toCallList)
{
waiter.CancelTimer();
waiter.Call();
}
}
if (toCall != null)
{
toCall.CancelTimer();
toCall.Call();
}
}
public void Reset()
{
// Doesn't matter if this changes during processing of another method
this.isSignaled = false;
}
class AsyncWaiter : ActionItem
{
[Fx.Tag.SecurityNote(Critical = "Store the delegate to be invoked")]
[SecurityCritical]
Action<object, TimeoutException> callback;
[Fx.Tag.SecurityNote(Critical = "Stores the state object to be passed to the callback")]
[SecurityCritical]
object state;
IOThreadTimer timer;
TimeSpan originalTimeout;
[Fx.Tag.SecurityNote(Critical = "Access critical members", Safe = "Doesn't leak information")]
[SecuritySafeCritical]
public AsyncWaiter(AsyncWaitHandle parent, Action<object, TimeoutException> callback, object state)
{
this.Parent = parent;
this.callback = callback;
this.state = state;
}
public AsyncWaitHandle Parent
{
get;
private set;
}
public bool TimedOut
{
get;
set;
}
[Fx.Tag.SecurityNote(Critical = "Calls into critical method Schedule", Safe = "Invokes the given delegate under the current context")]
[SecuritySafeCritical]
public void Call()
{
Schedule();
}
[Fx.Tag.SecurityNote(Critical = "Overriding an inherited critical method, access critical members")]
[SecurityCritical]
protected override void Invoke()
{
this.callback(this.state,
this.TimedOut ? new TimeoutException(InternalSR.TimeoutOnOperation(this.originalTimeout)) : null);
}
public void SetTimer(Action<object> callback, object state, TimeSpan timeout)
{
if (this.timer != null)
{
throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.MustCancelOldTimer));
}
this.originalTimeout = timeout;
this.timer = new IOThreadTimer(callback, state, false);
this.timer.Set(timeout);
}
public void CancelTimer()
{
if (this.timer != null)
{
this.timer.Cancel();
this.timer = null;
}
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Pool-wide patches
/// First published in XenServer 4.1.
/// </summary>
public partial class Pool_patch : XenObject<Pool_patch>
{
#region Constructors
public Pool_patch()
{
}
public Pool_patch(string uuid,
string name_label,
string name_description,
string version,
long size,
bool pool_applied,
List<XenRef<Host_patch>> host_patches,
List<after_apply_guidance> after_apply_guidance,
XenRef<Pool_update> pool_update,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.size = size;
this.pool_applied = pool_applied;
this.host_patches = host_patches;
this.after_apply_guidance = after_apply_guidance;
this.pool_update = pool_update;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Pool_patch from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Pool_patch(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Pool_patch from a Proxy_Pool_patch.
/// </summary>
/// <param name="proxy"></param>
public Pool_patch(Proxy_Pool_patch proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Pool_patch.
/// </summary>
public override void UpdateFrom(Pool_patch record)
{
uuid = record.uuid;
name_label = record.name_label;
name_description = record.name_description;
version = record.version;
size = record.size;
pool_applied = record.pool_applied;
host_patches = record.host_patches;
after_apply_guidance = record.after_apply_guidance;
pool_update = record.pool_update;
other_config = record.other_config;
}
internal void UpdateFrom(Proxy_Pool_patch proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
version = proxy.version == null ? null : proxy.version;
size = proxy.size == null ? 0 : long.Parse(proxy.size);
pool_applied = (bool)proxy.pool_applied;
host_patches = proxy.host_patches == null ? null : XenRef<Host_patch>.Create(proxy.host_patches);
after_apply_guidance = proxy.after_apply_guidance == null ? null : Helper.StringArrayToEnumList<after_apply_guidance>(proxy.after_apply_guidance);
pool_update = proxy.pool_update == null ? null : XenRef<Pool_update>.Create(proxy.pool_update);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Pool_patch
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("pool_applied"))
pool_applied = Marshalling.ParseBool(table, "pool_applied");
if (table.ContainsKey("host_patches"))
host_patches = Marshalling.ParseSetRef<Host_patch>(table, "host_patches");
if (table.ContainsKey("after_apply_guidance"))
after_apply_guidance = Helper.StringArrayToEnumList<after_apply_guidance>(Marshalling.ParseStringArray(table, "after_apply_guidance"));
if (table.ContainsKey("pool_update"))
pool_update = Marshalling.ParseRef<Pool_update>(table, "pool_update");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public Proxy_Pool_patch ToProxy()
{
Proxy_Pool_patch result_ = new Proxy_Pool_patch();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.version = version ?? "";
result_.size = size.ToString();
result_.pool_applied = pool_applied;
result_.host_patches = host_patches == null ? new string[] {} : Helper.RefListToStringArray(host_patches);
result_.after_apply_guidance = after_apply_guidance == null ? new string[] {} : Helper.ObjectListToStringArray(after_apply_guidance);
result_.pool_update = pool_update ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
public bool DeepEquals(Pool_patch other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pool_applied, other._pool_applied) &&
Helper.AreEqual2(this._host_patches, other._host_patches) &&
Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) &&
Helper.AreEqual2(this._pool_update, other._pool_update) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Pool_patch server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Pool_patch.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given pool_patch.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static Pool_patch get_record(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_record(session.opaque_ref, _pool_patch);
else
return new Pool_patch(session.XmlRpcProxy.pool_patch_get_record(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get a reference to the pool_patch instance with the specified UUID.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Pool_patch> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Pool_patch>.Create(session.XmlRpcProxy.pool_patch_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the pool_patch instances with the given label.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Pool_patch>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Pool_patch>.Create(session.XmlRpcProxy.pool_patch_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_uuid(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_uuid(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_uuid(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_name_label(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_name_label(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_name_label(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_name_description(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_name_description(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_name_description(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the version field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_version(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_version(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_version(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the size field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static long get_size(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_size(session.opaque_ref, _pool_patch);
else
return long.Parse(session.XmlRpcProxy.pool_patch_get_size(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the pool_applied field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static bool get_pool_applied(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_pool_applied(session.opaque_ref, _pool_patch);
else
return (bool)session.XmlRpcProxy.pool_patch_get_pool_applied(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the host_patches field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static List<XenRef<Host_patch>> get_host_patches(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_host_patches(session.opaque_ref, _pool_patch);
else
return XenRef<Host_patch>.Create(session.XmlRpcProxy.pool_patch_get_host_patches(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the after_apply_guidance field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static List<after_apply_guidance> get_after_apply_guidance(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_after_apply_guidance(session.opaque_ref, _pool_patch);
else
return Helper.StringArrayToEnumList<after_apply_guidance>(session.XmlRpcProxy.pool_patch_get_after_apply_guidance(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the pool_update field of the given pool_patch.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static XenRef<Pool_update> get_pool_update(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_pool_update(session.opaque_ref, _pool_patch);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.pool_patch_get_pool_update(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static Dictionary<string, string> get_other_config(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_other_config(session.opaque_ref, _pool_patch);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.pool_patch_get_other_config(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pool_patch, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_set_other_config(session.opaque_ref, _pool_patch, _other_config);
else
session.XmlRpcProxy.pool_patch_set_other_config(session.opaque_ref, _pool_patch ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pool_patch, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_add_to_other_config(session.opaque_ref, _pool_patch, _key, _value);
else
session.XmlRpcProxy.pool_patch_add_to_other_config(session.opaque_ref, _pool_patch ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given pool_patch. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pool_patch, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_remove_from_other_config(session.opaque_ref, _pool_patch, _key);
else
session.XmlRpcProxy.pool_patch_remove_from_other_config(session.opaque_ref, _pool_patch ?? "", _key ?? "").parse();
}
/// <summary>
/// Apply the selected patch to a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to apply the patch too</param>
[Deprecated("XenServer 7.1")]
public static string apply(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_apply(session.opaque_ref, _pool_patch, _host);
else
return session.XmlRpcProxy.pool_patch_apply(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse();
}
/// <summary>
/// Apply the selected patch to a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to apply the patch too</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_apply(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_apply(session.opaque_ref, _pool_patch, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_apply(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected patch to all hosts in the pool and return a map of host_ref -> patch output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void pool_apply(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_pool_apply(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_pool_apply(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Apply the selected patch to all hosts in the pool and return a map of host_ref -> patch output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_pool_apply(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_pool_apply(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_pool_apply(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected patch on a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to run the prechecks on</param>
[Deprecated("XenServer 7.1")]
public static string precheck(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_precheck(session.opaque_ref, _pool_patch, _host);
else
return session.XmlRpcProxy.pool_patch_precheck(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse();
}
/// <summary>
/// Execute the precheck stage of the selected patch on a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to run the prechecks on</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_precheck(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_precheck(session.opaque_ref, _pool_patch, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_precheck(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse());
}
/// <summary>
/// Removes the patch's files from the server
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_clean(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_clean(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Removes the patch's files from the server
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_clean(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_clean(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, but does not remove the database entries
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void pool_clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_pool_clean(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_pool_clean(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, but does not remove the database entries
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_pool_clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_pool_clean(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_pool_clean(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, and removes the database entries. Only works on unapplied patches.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void destroy(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_destroy(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_destroy(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, and removes the database entries. Only works on unapplied patches.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_destroy(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_destroy(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_destroy(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Removes the patch's files from the specified host
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host on which to clean the patch</param>
[Deprecated("XenServer 7.1")]
public static void clean_on_host(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_clean_on_host(session.opaque_ref, _pool_patch, _host);
else
session.XmlRpcProxy.pool_patch_clean_on_host(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse();
}
/// <summary>
/// Removes the patch's files from the specified host
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host on which to clean the patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_clean_on_host(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_clean_on_host(session.opaque_ref, _pool_patch, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_clean_on_host(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse());
}
/// <summary>
/// Return a list of all the pool_patchs known to the system.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Pool_patch>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_all(session.opaque_ref);
else
return XenRef<Pool_patch>.Create(session.XmlRpcProxy.pool_patch_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the pool_patch Records at once, in a single XML RPC call
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Pool_patch>, Pool_patch> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_all_records(session.opaque_ref);
else
return XenRef<Pool_patch>.Create<Proxy_Pool_patch>(session.XmlRpcProxy.pool_patch_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Patch version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Size of the patch
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
NotifyPropertyChanged("size");
}
}
}
private long _size = 0;
/// <summary>
/// This patch should be applied across the entire pool
/// </summary>
public virtual bool pool_applied
{
get { return _pool_applied; }
set
{
if (!Helper.AreEqual(value, _pool_applied))
{
_pool_applied = value;
NotifyPropertyChanged("pool_applied");
}
}
}
private bool _pool_applied = false;
/// <summary>
/// This hosts this patch is applied to.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host_patch>))]
public virtual List<XenRef<Host_patch>> host_patches
{
get { return _host_patches; }
set
{
if (!Helper.AreEqual(value, _host_patches))
{
_host_patches = value;
NotifyPropertyChanged("host_patches");
}
}
}
private List<XenRef<Host_patch>> _host_patches = new List<XenRef<Host_patch>>() {};
/// <summary>
/// What the client should do after this patch has been applied.
/// </summary>
public virtual List<after_apply_guidance> after_apply_guidance
{
get { return _after_apply_guidance; }
set
{
if (!Helper.AreEqual(value, _after_apply_guidance))
{
_after_apply_guidance = value;
NotifyPropertyChanged("after_apply_guidance");
}
}
}
private List<after_apply_guidance> _after_apply_guidance = new List<after_apply_guidance>() {};
/// <summary>
/// A reference to the associated pool_update object
/// First published in XenServer 7.1.
/// </summary>
[JsonConverter(typeof(XenRefConverter<Pool_update>))]
public virtual XenRef<Pool_update> pool_update
{
get { return _pool_update; }
set
{
if (!Helper.AreEqual(value, _pool_update))
{
_pool_update = value;
NotifyPropertyChanged("pool_update");
}
}
}
private XenRef<Pool_update> _pool_update = new XenRef<Pool_update>("OpaqueRef:NULL");
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BitCoinSharp.Store;
using log4net;
using NUnit.Framework;
namespace BitCoinSharp.Test
{
[TestFixture]
public class WalletTest
{
private static readonly NetworkParameters Params = NetworkParameters.UnitTests();
private Address _myAddress;
private Wallet _wallet;
private IBlockStore _blockStore;
[SetUp]
public void SetUp()
{
var myKey = new EcKey();
_myAddress = myKey.ToAddress(Params);
_wallet = new Wallet(Params);
_wallet.AddKey(myKey);
_blockStore = new MemoryBlockStore(Params);
}
[TearDown]
public void TearDown()
{
_blockStore.Dispose();
}
[Test]
public void BasicSpending()
{
// We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
var v1 = Utils.ToNanoCoins(1, 0);
var t1 = TestUtils.CreateFakeTx(Params, v1, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(v1, _wallet.GetBalance());
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
var k2 = new EcKey();
var v2 = Utils.ToNanoCoins(0, 50);
var t2 = _wallet.CreateSend(k2.ToAddress(Params), v2);
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
// Do some basic sanity checks.
Assert.AreEqual(1, t2.Inputs.Count);
Assert.AreEqual(_myAddress, t2.Inputs[0].ScriptSig.FromAddress);
// We have NOT proven that the signature is correct!
_wallet.ConfirmSend(t2);
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Pending));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Spent));
Assert.AreEqual(2, _wallet.GetPoolSize(Wallet.Pool.All));
}
[Test]
public void SideChain()
{
// The wallet receives a coin on the main chain, then on a side chain. Only main chain counts towards balance.
var v1 = Utils.ToNanoCoins(1, 0);
var t1 = TestUtils.CreateFakeTx(Params, v1, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(v1, _wallet.GetBalance());
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
var v2 = Utils.ToNanoCoins(0, 50);
var t2 = TestUtils.CreateFakeTx(Params, v2, _myAddress);
_wallet.Receive(t2, null, BlockChain.NewBlockType.SideChain);
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Inactive));
Assert.AreEqual(2, _wallet.GetPoolSize(Wallet.Pool.All));
Assert.AreEqual(v1, _wallet.GetBalance());
}
[Test]
public void Listener()
{
var fakeTx = TestUtils.CreateFakeTx(Params, Utils.ToNanoCoins(1, 0), _myAddress);
var didRun = false;
_wallet.CoinsReceived +=
(sender, e) =>
{
Assert.IsTrue(e.PrevBalance.Equals(0));
Assert.IsTrue(e.NewBalance.Equals(Utils.ToNanoCoins(1, 0)));
Assert.AreEqual(e.Tx, fakeTx);
Assert.AreEqual(sender, _wallet);
didRun = true;
};
_wallet.Receive(fakeTx, null, BlockChain.NewBlockType.BestChain);
Assert.IsTrue(didRun);
}
[Test]
public void Balance()
{
// Receive 5 coins then half a coin.
var v1 = Utils.ToNanoCoins(5, 0);
var v2 = Utils.ToNanoCoins(0, 50);
var t1 = TestUtils.CreateFakeTx(Params, v1, _myAddress);
var t2 = TestUtils.CreateFakeTx(Params, v2, _myAddress);
var b1 = TestUtils.CreateFakeBlock(Params, _blockStore, t1).StoredBlock;
var b2 = TestUtils.CreateFakeBlock(Params, _blockStore, t2).StoredBlock;
var expected = Utils.ToNanoCoins(5, 50);
_wallet.Receive(t1, b1, BlockChain.NewBlockType.BestChain);
_wallet.Receive(t2, b2, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(expected, _wallet.GetBalance());
// Now spend one coin.
var v3 = Utils.ToNanoCoins(1, 0);
var spend = _wallet.CreateSend(new EcKey().ToAddress(Params), v3);
_wallet.ConfirmSend(spend);
// Available and estimated balances should not be the same. We don't check the exact available balance here
// because it depends on the coin selection algorithm.
Assert.AreEqual(Utils.ToNanoCoins(4, 50), _wallet.GetBalance(Wallet.BalanceType.Estimated));
Assert.IsFalse(_wallet.GetBalance(Wallet.BalanceType.Available).Equals(
_wallet.GetBalance(Wallet.BalanceType.Estimated)));
// Now confirm the transaction by including it into a block.
var b3 = TestUtils.CreateFakeBlock(Params, _blockStore, spend).StoredBlock;
_wallet.Receive(spend, b3, BlockChain.NewBlockType.BestChain);
// Change is confirmed. We started with 5.50 so we should have 4.50 left.
var v4 = Utils.ToNanoCoins(4, 50);
Assert.AreEqual(v4, _wallet.GetBalance(Wallet.BalanceType.Available));
}
// Intuitively you'd expect to be able to create a transaction with identical inputs and outputs and get an
// identical result to the official client. However the signatures are not deterministic - signing the same data
// with the same key twice gives two different outputs. So we cannot prove bit-for-bit compatibility in this test
// suite.
[Test]
public void BlockChainCatchup()
{
var tx1 = TestUtils.CreateFakeTx(Params, Utils.ToNanoCoins(1, 0), _myAddress);
var b1 = TestUtils.CreateFakeBlock(Params, _blockStore, tx1).StoredBlock;
_wallet.Receive(tx1, b1, BlockChain.NewBlockType.BestChain);
// Send 0.10 to somebody else.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(Params), Utils.ToNanoCoins(0, 10), _myAddress);
// Pretend it makes it into the block chain, our wallet state is cleared but we still have the keys, and we
// want to get back to our previous state. We can do this by just not confirming the transaction as
// createSend is stateless.
var b2 = TestUtils.CreateFakeBlock(Params, _blockStore, send1).StoredBlock;
_wallet.Receive(send1, b2, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(Utils.BitcoinValueToFriendlyString(_wallet.GetBalance()), "0.90");
// And we do it again after the catch-up.
var send2 = _wallet.CreateSend(new EcKey().ToAddress(Params), Utils.ToNanoCoins(0, 10), _myAddress);
// What we'd really like to do is prove the official client would accept it .... no such luck unfortunately.
_wallet.ConfirmSend(send2);
var b3 = TestUtils.CreateFakeBlock(Params, _blockStore, send2).StoredBlock;
_wallet.Receive(send2, b3, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(Utils.BitcoinValueToFriendlyString(_wallet.GetBalance()), "0.80");
}
[Test]
public void Balances()
{
var nanos = Utils.ToNanoCoins(1, 0);
var tx1 = TestUtils.CreateFakeTx(Params, nanos, _myAddress);
_wallet.Receive(tx1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(nanos, tx1.GetValueSentToMe(_wallet, true));
// Send 0.10 to somebody else.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(Params), Utils.ToNanoCoins(0, 10), _myAddress);
// Re-serialize.
var send2 = new Transaction(Params, send1.BitcoinSerialize());
Assert.AreEqual(nanos, send2.GetValueSentFromMe(_wallet));
}
[Test]
public void Transactions()
{
// This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly.
var tx = TestUtils.CreateFakeTx(Params, Utils.ToNanoCoins(1, 0), _myAddress);
// Now add another output (ie, change) that goes to some other address.
var someOtherGuy = new EcKey().ToAddress(Params);
var output = new TransactionOutput(Params, tx, Utils.ToNanoCoins(0, 5), someOtherGuy);
tx.AddOutput(output);
// Note that tx is no longer valid: it spends more than it imports. However checking transactions balance
// correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all
// transactions you can't check they add up.
_wallet.Receive(tx, null, BlockChain.NewBlockType.BestChain);
// Now the other guy creates a transaction which spends that change.
var tx2 = new Transaction(Params);
tx2.AddInput(output);
tx2.AddOutput(new TransactionOutput(Params, tx2, Utils.ToNanoCoins(0, 5), _myAddress));
// tx2 doesn't send any coins from us, even though the output is in the wallet.
Assert.AreEqual(Utils.ToNanoCoins(0, 0), tx2.GetValueSentFromMe(_wallet));
}
[Test]
public void Bounce()
{
// This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent
// back to us, this isn't considered as a double spend.
var coin1 = Utils.ToNanoCoins(1, 0);
var coinHalf = Utils.ToNanoCoins(0, 50);
// Start by giving us 1 coin.
var inbound1 = TestUtils.CreateFakeTx(Params, coin1, _myAddress);
_wallet.Receive(inbound1, null, BlockChain.NewBlockType.BestChain);
// Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is
// in the unspent pool, not pending or spent.
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
var someOtherGuy = new EcKey().ToAddress(Params);
var outbound1 = _wallet.CreateSend(someOtherGuy, coinHalf);
_wallet.ConfirmSend(outbound1);
_wallet.Receive(outbound1, null, BlockChain.NewBlockType.BestChain);
// That other guy gives us the coins right back.
var inbound2 = new Transaction(Params);
inbound2.AddOutput(new TransactionOutput(Params, inbound2, coinHalf, _myAddress));
inbound2.AddInput(outbound1.Outputs[0]);
_wallet.Receive(inbound2, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(coin1, _wallet.GetBalance());
}
[Test]
public void FinneyAttack()
{
// A Finney attack is where a miner includes a transaction spending coins to themselves but does not
// broadcast it. When they find a solved block, they hold it back temporarily whilst they buy something with
// those same coins. After purchasing, they broadcast the block thus reversing the transaction. It can be
// done by any miner for products that can be bought at a chosen time and very quickly (as every second you
// withhold your block means somebody else might find it first, invalidating your work).
//
// Test that we handle ourselves performing the attack correctly: a double spend on the chain moves
// transactions from pending to dead.
//
// Note that the other way around, where a pending transaction sending us coins becomes dead,
// isn't tested because today BitCoinJ only learns about such transactions when they appear in the chain.
Transaction eventDead = null;
Transaction eventReplacement = null;
_wallet.DeadTransaction +=
(sender, e) =>
{
eventDead = e.DeadTx;
eventReplacement = e.ReplacementTx;
};
// Receive 1 BTC.
var nanos = Utils.ToNanoCoins(1, 0);
var t1 = TestUtils.CreateFakeTx(Params, nanos, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
// Create a send to a merchant.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(Params), Utils.ToNanoCoins(0, 50));
// Create a double spend.
var send2 = _wallet.CreateSend(new EcKey().ToAddress(Params), Utils.ToNanoCoins(0, 50));
// Broadcast send1.
_wallet.ConfirmSend(send1);
// Receive a block that overrides it.
_wallet.Receive(send2, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(send1, eventDead);
Assert.AreEqual(send2, eventReplacement);
}
}
}
| |
// This is a collection of .NET concurrency utilities, inspired by the classes
// available in java. This utilities are written by Iulian Margarintescu as described here
// https://github.com/etishor/ConcurrencyUtilities
//
//
// Striped64 & LongAdder classes were ported from Java and had this copyright:
//
// Written by Doug Lea with assistance from members of JCP JSR-166
// Expert Group and released to the public domain, as explained at
// http://creativecommons.org/publicdomain/zero/1.0/
//
// Source: http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.8
//
// By default all added classes are internal to your assembly.
// To make them public define you have to define the conditional compilation symbol CONCURRENCY_UTILS_PUBLIC in your project properties.
//
#pragma warning disable 1591
// ReSharper disable All
/*
* Striped64 & LongAdder classes were ported from Java and had this copyright:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*
* Source: http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?revision=1.8
*
* This class has been ported to .NET by Iulian Margarintescu and will retain the same license as the Java Version
*
*/
// ReSharper disable TooWideLocalVariableScope
// ReSharper disable InvertIf
// ReSharper disable ForCanBeConvertedToForeach
// ReSharper disable LoopCanBeConvertedToQuery
namespace Metrics.ConcurrencyUtilities
{
/// <summary>
/// One or more variables that together maintain an initially zero sum.
/// When updates are contended cross threads, the set of variables may grow dynamically to reduce contention.
/// Method GetValue() returns the current total combined across the variables maintaining the sum.
///
/// This class is usually preferable to AtomicLong when multiple threads update a common sum that is used for purposes such
/// as collecting statistics, not for fine-grained synchronization control.
///
/// Under low update contention, the two classes have similar characteristics.
/// But under high contention, expected throughput of this class is significantly higher, at the expense of higher space consumption.
///
/// </summary>
#if CONCURRENCY_UTILS_PUBLIC
public
#else
internal
#endif
sealed class StripedLongAdder : Striped64
{
/// <summary>
/// Creates a new instance of the adder with initial value of zero.
/// </summary>
public StripedLongAdder() { }
/// <summary>
/// Creates a new instance of the adder with initial <paramref name="value"/>.
/// </summary>
public StripedLongAdder(long value)
{
Add(value);
}
/// <summary>
/// Returns the current value of this adder. This method sums all the buckets and returns the result.
/// </summary>
/// <returns>The current value recored by this adder.</returns>
public long GetValue()
{
var @as = this.Cells; Cell a;
var sum = Base.GetValue();
if (@as != null)
{
for (var i = 0; i < @as.Length; ++i)
{
if ((a = @as[i]) != null)
sum += a.Value.GetValue();
}
}
return sum;
}
/// <summary>
/// Returns the current value of the instance without using Volatile.Read fence and ordering.
/// </summary>
/// <returns>The current value of the instance in a non-volatile way (might not observe changes on other threads).</returns>
public long NonVolatileGetValue()
{
var @as = this.Cells; Cell a;
var sum = Base.NonVolatileGetValue();
if (@as != null)
{
for (var i = 0; i < @as.Length; ++i)
{
if ((a = @as[i]) != null)
sum += a.Value.NonVolatileGetValue();
}
}
return sum;
}
/// <summary>
/// Returns the current value of this adder and resets the value to zero.
/// This method sums all the buckets, resets their value and returns the result.
/// </summary>
/// <remarks>
/// This method is thread-safe. If updates happen during this method, they are either included in the final sum, or reflected in the value after the reset.
/// </remarks>
/// <returns>The current value recored by this adder.</returns>
public long GetAndReset()
{
var @as = this.Cells; Cell a;
var sum = Base.GetAndReset();
if (@as != null)
{
for (var i = 0; i < @as.Length; ++i)
{
if ((a = @as[i]) != null)
{
sum += a.Value.GetAndReset();
}
}
}
return sum;
}
/// <summary>
/// Resets the current value to zero.
/// </summary>
public void Reset()
{
var @as = this.Cells; Cell a;
Base.SetValue(0L);
if (@as != null)
{
for (var i = 0; i < @as.Length; ++i)
{
if ((a = @as[i]) != null)
{
a.Value.SetValue(0L);
}
}
}
}
/// <summary>
/// Increment the value of this instance.
/// </summary>
public void Increment()
{
Add(1L);
}
/// <summary>
/// Increment the value of this instance with <paramref name="value"/>.
/// </summary>
public void Increment(long value)
{
Add(value);
}
/// <summary>
/// Decrement the value of this instance.
/// </summary>
public void Decrement()
{
Add(-1L);
}
/// <summary>
/// Decrement the value of this instance with <paramref name="value"/>.
/// </summary>
public void Decrement(long value)
{
Add(-value);
}
/// <summary>
/// Add <paramref name="value"/> to this instance.
/// </summary>
/// <param name="value">Value to add.</param>
public void Add(long value)
{
Cell[] @as;
long b, v;
int m;
Cell a;
if ((@as = this.Cells) != null || !Base.CompareAndSwap(b = Base.GetValue(), b + value))
{
var uncontended = true;
if (@as == null || (m = @as.Length - 1) < 0 || (a = @as[GetProbe() & m]) == null || !(uncontended = a.Value.CompareAndSwap(v = a.Value.GetValue(), v + value)))
{
LongAccumulate(value, uncontended);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Reflection.Emit.Tests
{
public interface DefineMethodOverrideInterface
{
int M();
}
public class DefineMethodOverrideClass : DefineMethodOverrideInterface
{
public virtual int M() => 1;
}
public class MethodBuilderDefineMethodOverride
{
[Fact]
public void DefineMethodOverride_InterfaceMethod()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldc_I4, 2);
ilGenerator.Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface));
MethodInfo decleration = typeof(DefineMethodOverrideInterface).GetMethod("M");
type.DefineMethodOverride(method, decleration);
Type createdType = type.CreateTypeInfo().AsType();
MethodInfo createdMethod = typeof(DefineMethodOverrideInterface).GetMethod("M");
Assert.Equal(2, createdMethod.Invoke(Activator.CreateInstance(createdType), null));
}
[Fact]
public void DefineMethodOverride_InterfaceMethodWithConflictingName()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
type.SetParent(typeof(DefineMethodOverrideClass));
MethodBuilder method = type.DefineMethod("M2", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldc_I4, 2);
ilGenerator.Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface));
MethodInfo decleration = typeof(DefineMethodOverrideInterface).GetMethod("M");
type.DefineMethodOverride(method, decleration);
Type createdType = type.CreateTypeInfo().AsType();
MethodInfo createdMethod = typeof(DefineMethodOverrideInterface).GetMethod("M");
ConstructorInfo createdTypeCtor = createdType.GetConstructor(new Type[0]);
object instance = createdTypeCtor.Invoke(new object[0]);
Assert.Equal(2, createdMethod.Invoke(instance, null));
Assert.Equal(1, createdMethod.Invoke(Activator.CreateInstance(typeof(DefineMethodOverrideClass)), null));
}
[Fact]
public void DefineMethodOverride_GenericInterface_Succeeds()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
type.AddInterfaceImplementation(typeof(GenericInterface<string>));
MethodBuilder method = type.DefineMethod(nameof(GenericInterface<string>.Method), MethodAttributes.Public | MethodAttributes.Virtual, typeof(string), new Type[0]);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldstr, "Hello World");
ilGenerator.Emit(OpCodes.Ret);
MethodInfo interfaceMethod = typeof(GenericInterface<string>).GetMethod(nameof(GenericInterface<string>.Method));
type.DefineMethodOverride(method, interfaceMethod);
Type createdType = type.CreateTypeInfo().AsType();
Assert.Equal("Hello World", interfaceMethod.Invoke(Activator.CreateInstance(createdType), null));
}
[Fact]
public void DefineMethodOverride_CalledTwiceWithSameBodies_Works()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldc_I4, 2);
ilGenerator.Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface));
MethodInfo decleration = typeof(DefineMethodOverrideInterface).GetMethod("M");
type.DefineMethodOverride(method, decleration);
type.DefineMethodOverride(method, decleration);
Type createdType = type.CreateTypeInfo().AsType();
MethodInfo createdMethod = typeof(DefineMethodOverrideInterface).GetMethod("M");
Assert.Equal(2, createdMethod.Invoke(Activator.CreateInstance(createdType), null));
}
[Fact]
public void DefineMethodOverride_NullMethodInfoBody_ThrowsArgumentNullException()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodInfo method = typeof(DefineMethodOverrideClass).GetMethod("M");
Assert.Throws<ArgumentNullException>("methodInfoBody", () => type.DefineMethodOverride(null, method));
}
[Fact]
public void DefineMethodOverride_NullMethodInfoDeclaration_ThrowsArgumentNullException()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodInfo method = typeof(DefineMethodOverrideInterface).GetMethod("M");
Assert.Throws<ArgumentNullException>("methodInfoDeclaration", () => type.DefineMethodOverride(method, null));
}
[Fact]
public void DefineMethodOverride_MethodNotInClass_ThrowsArgumentException()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodInfo body = typeof(DefineMethodOverrideInterface).GetMethod("M");
MethodInfo decleration = typeof(DefineMethodOverrideClass).GetMethod("M");
Assert.Throws<ArgumentException>(null, () => type.DefineMethodOverride(body, decleration));
}
[Fact]
public void DefineMethodOverride_GlobalMethod_ThrowsArgumentException()
{
ModuleBuilder module = Helpers.DynamicModule();
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[0]);
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
TypeBuilder type = module.DefineType("Name");
Assert.Throws<ArgumentException>(null, () => type.DefineMethodOverride(globalMethod, typeof(DefineMethodOverrideInterface).GetMethod(nameof(DefineMethodOverrideInterface.M))));
}
[Fact]
public void DefineMethodOverride_TypeCreated_ThrowsInvalidOperationException()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
method.GetILGenerator().Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface));
Type createdType = type.CreateTypeInfo().AsType();
MethodInfo body = createdType.GetMethod(method.Name);
MethodInfo declaration = typeof(DefineMethodOverrideInterface).GetMethod(method.Name);
Assert.Throws<InvalidOperationException>(() => type.DefineMethodOverride(body, declaration));
}
[Fact]
public void DefineMethodOverride_MethodNotVirtual_ThrowsTypeLoadExceptionOnCreation()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public, typeof(int), null);
ILGenerator ilGenerator = method.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldc_I4, 2);
ilGenerator.Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface));
MethodInfo decleration = typeof(DefineMethodOverrideInterface).GetMethod(method.Name);
type.DefineMethodOverride(method, decleration);
Assert.Throws<TypeLoadException>(() => type.CreateTypeInfo());
}
[Fact]
public void DefineMethodOverride_NothingToOverride_ThrowsTypeLoadExceptionOnCreation()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
method.GetILGenerator().Emit(OpCodes.Ret);
type.DefineMethodOverride(method, typeof(DefineMethodOverrideInterface).GetMethod(nameof(DefineMethodOverrideInterface.M)));
Assert.Throws<TypeLoadException>(() => type.CreateTypeInfo());
}
[Theory]
[InlineData(typeof(GenericInterface<>), nameof(GenericInterface<string>.Method))]
[InlineData(typeof(DefineMethodOverrideInterface), nameof(DefineMethodOverrideInterface.M))]
public void DefineMethodOverride_ClassDoesNotImplementOrInheritMethod_ThrowsTypeLoadExceptionOnCreation(Type methodType, string methodName)
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
type.AddInterfaceImplementation(typeof(GenericInterface<string>));
MethodBuilder method = type.DefineMethod("Name", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new Type[0]);
method.GetILGenerator().Emit(OpCodes.Ret);
type.DefineMethodOverride(method, methodType.GetMethod(methodName));
Assert.Throws<TypeLoadException>(() => type.CreateTypeInfo());
}
[Fact]
public void DefineMethodOverride_BodyAndDeclarationTheSame_ThrowsTypeLoadExceptionOnCreation()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
method.GetILGenerator().Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface));
MethodInfo declaration = typeof(DefineMethodOverrideInterface).GetMethod(method.Name);
type.DefineMethodOverride(method, method);
Assert.Throws<TypeLoadException>(() => type.CreateTypeInfo());
}
[Fact]
public void DefineMethodOverride_CalledTwiceWithDifferentBodies_ThrowsTypeLoadExceptionOnCreation()
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Public);
MethodBuilder method1 = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
ILGenerator ilGenerator1 = method1.GetILGenerator();
ilGenerator1.Emit(OpCodes.Ldc_I4, 2);
ilGenerator1.Emit(OpCodes.Ret);
MethodBuilder method2 = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, typeof(int), null);
ILGenerator ilGenerator2 = method2.GetILGenerator();
ilGenerator2.Emit(OpCodes.Ldc_I4, 2);
ilGenerator2.Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(DefineMethodOverrideInterface));
MethodInfo decleration = typeof(DefineMethodOverrideInterface).GetMethod("M");
type.DefineMethodOverride(method1, decleration);
type.DefineMethodOverride(method2, decleration);
Assert.Throws<TypeLoadException>(() => type.CreateTypeInfo());
}
[Theory]
[InlineData(typeof(int), new Type[0])]
[InlineData(typeof(int), new Type[] { typeof(int), typeof(int) })]
[InlineData(typeof(int), new Type[] { typeof(string), typeof(string) })]
[InlineData(typeof(int), new Type[] { typeof(int), typeof(string), typeof(bool) })]
[InlineData(typeof(string), new Type[] { typeof(string), typeof(int) })]
public void DefineMethodOverride_BodyAndDeclarationHaveDifferentSignatures_ThrowsTypeLoadExceptionOnCreation(Type returnType, Type[] parameterTypes)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder type = module.DefineType("GenericType", TypeAttributes.Public);
MethodBuilder method = type.DefineMethod("M", MethodAttributes.Public | MethodAttributes.Virtual, returnType, parameterTypes);
method.GetILGenerator().Emit(OpCodes.Ret);
type.AddInterfaceImplementation(typeof(InterfaceWithMethod));
MethodInfo declaration = typeof(InterfaceWithMethod).GetMethod(nameof(InterfaceWithMethod.Method));
type.DefineMethodOverride(method, declaration);
Assert.Throws<TypeLoadException>(() => type.CreateTypeInfo());
}
public interface GenericInterface<T>
{
T Method();
}
public interface InterfaceWithMethod
{
int Method(string s, int i);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Internal
{
/// <summary>
/// Defines enumerations for the keywords
/// </summary>
internal enum PSKeyword : ulong
{
Runspace = 0x1,
Pipeline = 0x2,
Protocol = 0x4,
Transport = 0x8,
Host = 0x10,
Cmdlets = 0x20,
Serializer = 0x40,
Session = 0x80,
ManagedPlugin = 0x100,
UseAlwaysOperational = 0x8000000000000000,
UseAlwaysAnalytic = 0x4000000000000000,
}
/// <summary>
/// Define enumerations for levels
/// </summary>
internal enum PSLevel : byte
{
LogAlways = 0x0,
Critical = 0x1,
Error = 0x2,
Warning = 0x3,
Informational = 0x4,
Verbose = 0x5,
Debug = 0x14
}
/// <summary>
/// Defines enumerations for op codes
/// </summary>
internal enum PSOpcode : byte
{
WinStart = 0x1,
WinStop = 0x2,
Open = 0xA,
Close = 0xB,
Connect = 0xC,
Disconnect = 0xD,
Negotiate = 0xE,
Create = 0xF,
Constructor = 0x10,
Dispose = 0x11,
EventHandler = 0x12,
Exception = 0x13,
Method = 0x14,
Send = 0x15,
Receive = 0x16,
Rehydration = 0x17,
SerializationSettings = 0x18,
ShuttingDown = 0x19,
}
/// <summary>
/// Defines enumerations for event ids
/// </summary>
/// <remarks>add an entry for a new event that you
/// add to the manifest. Set it to the same value
/// that was set in the manifest</remarks>
internal enum PSEventId : int
{
HostNameResolve = 0x1001,
SchemeResolve = 0x1002,
ShellResolve = 0x1003,
RunspaceConstructor = 0x2001,
RunspacePoolConstructor = 0x2002,
RunspacePoolOpen = 0x2003,
OperationalTransferEventRunspacePool = 0x2004,
RunspaceStateChange = 0x2005,
RetrySessionCreation = 0x2006,
Port = 0x2F01,
AppName = 0x2F02,
ComputerName = 0x2F03,
Scheme = 0x2F04,
TestAnalytic = 0x2F05,
WSManConnectionInfoDump = 0x2F06,
AnalyticTransferEventRunspacePool = 0x2F07,
// Start: Transport related events
TransportReceivedObject = 0x8001,
TransportSendingData = 0x8002,
TransportReceivedData = 0x8003,
AppDomainUnhandledException_Analytic = 0x8007,
TransportError_Analytic = 0x8008,
AppDomainUnhandledException = 0x8009,
TransportError = 0x8010,
WSManCreateShell = 0x8011,
WSManCreateShellCallbackReceived = 0x8012,
WSManCloseShell = 0x8013,
WSManCloseShellCallbackReceived = 0x8014,
WSManSendShellInputEx = 0x8015,
WSManSendShellInputExCallbackReceived = 0x8016,
WSManReceiveShellOutputEx = 0x8017,
WSManReceiveShellOutputExCallbackReceived = 0x8018,
WSManCreateCommand = 0x8019,
WSManCreateCommandCallbackReceived = 0x8020,
WSManCloseCommand = 0x8021,
WSManCloseCommandCallbackReceived = 0x8022,
WSManSignal = 0x8023,
WSManSignalCallbackReceived = 0x8024,
URIRedirection = 0x8025,
ServerSendData = 0x8051,
ServerCreateRemoteSession = 0x8052,
ReportContext = 0x8053,
ReportOperationComplete = 0x8054,
ServerCreateCommandSession = 0x8055,
ServerStopCommand = 0x8056,
ServerReceivedData = 0x8057,
ServerClientReceiveRequest = 0x8058,
ServerCloseOperation = 0x8059,
LoadingPSCustomShellAssembly = 0x8061,
LoadingPSCustomShellType = 0x8062,
ReceivedRemotingFragment = 0x8063,
SentRemotingFragment = 0x8064,
WSManPluginShutdown = 0x8065,
// End: Transport related events
// Start: Serialization related events
Serializer_RehydrationSuccess = 0x7001,
Serializer_RehydrationFailure = 0x7002,
Serializer_DepthOverride = 0x7003,
Serializer_ModeOverride = 0x7004,
Serializer_ScriptPropertyWithoutRunspace = 0x7005,
Serializer_PropertyGetterFailed = 0x7006,
Serializer_EnumerationFailed = 0x7007,
Serializer_ToStringFailed = 0x7008,
Serializer_MaxDepthWhenSerializing = 0x700A,
Serializer_XmlExceptionWhenDeserializing = 0x700B,
Serializer_SpecificPropertyMissing = 0x700C,
// End: Serialization related events
// Start: Perftrack related events
Perftrack_ConsoleStartupStart = 0xA001,
Perftrack_ConsoleStartupStop = 0xA002,
// End: Preftrack related events
Command_Health = 0x1004,
Engine_Health = 0x1005,
Provider_Health = 0x1006,
Pipeline_Detail = 0x1007,
ScriptBlock_Compile_Detail = 0x1008,
ScriptBlock_Invoke_Start_Detail = 0x1009,
ScriptBlock_Invoke_Complete_Detail = 0x100A,
Command_Lifecycle = 0x1F01,
Engine_Lifecycle = 0x1F02,
Provider_Lifecycle = 0x1F03,
Settings = 0x1F04,
Engine_Trace = 0x1F06,
// Scheduled Jobs
ScheduledJob_Start = 0xD001,
ScheduledJob_Complete = 0xD002,
ScheduledJob_Error = 0xD003,
// PowerShell IPC Named Pipe Connection
NamedPipeIPC_ServerListenerStarted = 0xD100,
NamedPipeIPC_ServerListenerEnded = 0xD101,
NamedPipeIPC_ServerListenerError = 0xD102,
NamedPipeIPC_ServerConnect = 0xD103,
NamedPipeIPC_ServerDisconnect = 0xD104,
// Start: ISE related events
ISEExecuteScript = 0x6001,
ISEExecuteSelection = 0x6002,
ISEStopCommand = 0x6003,
ISEResumeDebugger = 0x6004,
ISEStopDebugger = 0x6005,
ISEDebuggerStepInto = 0x6006,
ISEDebuggerStepOver = 0x6007,
ISEDebuggerStepOut = 0x6008,
ISEEnableAllBreakpoints = 0x6010,
ISEDisableAllBreakpoints = 0x6011,
ISERemoveAllBreakpoints = 0x6012,
ISESetBreakpoint = 0x6013,
ISERemoveBreakpoint = 0x6014,
ISEEnableBreakpoint = 0x6015,
ISEDisableBreakpoint = 0x6016,
ISEHitBreakpoint = 0x6017,
// End: ISE related events
}
/// <summary>
/// Defines enumerations for channels
/// </summary>
internal enum PSChannel : byte
{
Operational = 0x10,
Analytic = 0x11
}
/// <summary>
/// Defines enumerations for tasks
/// </summary>
internal enum PSTask : int
{
None = 0x0,
CreateRunspace = 0x1,
ExecuteCommand = 0x2,
Serialization = 0x3,
PowershellConsoleStartup = 0x4,
EngineStart = 0x64,
EngineStop = 0x65,
CommandStart = 0x66,
CommandStop = 0x67,
ProviderStart = 0x68,
ProviderStop = 0x69,
ExecutePipeline = 0x6A,
ScheduledJob = 0x6E,
NamedPipe = 0x6F,
ISEOperation = 0x78
}
/// <summary>
/// Defines enumerations for version
/// </summary>
/// <remarks>all messages in V2 timeframe
/// should be of version 1</remarks>
internal enum PSEventVersion : byte
{
One = 0x1,
}
/// <summary>
/// Describes a binary blob to be used as a data item for ETW.
/// </summary>
internal sealed class PSETWBinaryBlob
{
public PSETWBinaryBlob(byte[] blob, int offset, int length)
{
this.blob = blob;
this.offset = offset;
this.length = length;
}
public readonly byte[] blob;
public readonly int offset;
public readonly int length;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Bluehands.Hypermedia.Client.Hypermedia;
using Bluehands.Hypermedia.Client.Hypermedia.Attributes;
using Bluehands.Hypermedia.Client.Hypermedia.Commands;
using Bluehands.Hypermedia.Client.Resolver;
using Bluehands.Hypermedia.Client.Util;
namespace Bluehands.Hypermedia.Client.Reader
{
internal enum HypermediaPropertyType
{
Unknown,
Property,
Entity,
EntityCollection,
Link,
Command
}
public class SirenHypermediaReader : IHypermediaReader
{
private readonly IHypermediaObjectRegister hypermediaObjectRegister;
private readonly IHypermediaCommandFactory hypermediaCommandFactory;
private IHypermediaResolver resolver;
private readonly IStringParser stringParser;
private readonly DistinctOrderedStringCollectionComparer distinctOrderedStringCollectionComparer = new DistinctOrderedStringCollectionComparer();
public SirenHypermediaReader(
IHypermediaObjectRegister hypermediaObjectRegister,
IStringParser stringParser)
{
this.hypermediaObjectRegister = hypermediaObjectRegister;
this.hypermediaCommandFactory = RegisterHypermediaCommandFactory.Create();
this.stringParser = stringParser;
}
public void InitializeHypermediaResolver(IHypermediaResolver resolver)
{
this.resolver = resolver;
}
public HypermediaClientObject Read(string contentString)
{
// TODO inject deserializer
// todo catch exception: invalid format
var rootObject = this.stringParser.Parse(contentString);
var result = this.ReadHypermediaObject(rootObject);
return result;
}
public async Task<HypermediaClientObject> ReadAsync(Stream contentStream)
{
var rootObject = await this.stringParser.ParseAsync(contentStream);
var result = this.ReadHypermediaObject(rootObject);
return result;
}
private HypermediaClientObject ReadHypermediaObject(IToken rootObject)
{
var classes = ReadClasses(rootObject);
var hypermediaObjectInstance = this.hypermediaObjectRegister.CreateFromClasses(classes);
this.ReadTitle(hypermediaObjectInstance, rootObject);
this.ReadRelations(hypermediaObjectInstance, rootObject);
this.FillHypermediaProperties(hypermediaObjectInstance, rootObject);
return hypermediaObjectInstance;
}
private void FillHypermediaProperties(HypermediaClientObject hypermediaObjectInstance, IToken rootObject)
{
var typeInfo = hypermediaObjectInstance.GetType().GetTypeInfo();
var properties = typeInfo.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var propertyInfo in properties)
{
var ignore = propertyInfo.GetCustomAttribute<ClientIgnoreHypermediaPropertyAttribute>() != null;
if (ignore)
{
continue;
}
var hypermediaPropertyType = GetHypermediaPropertyType(propertyInfo);
switch (hypermediaPropertyType)
{
case HypermediaPropertyType.Property:
FillProperty(hypermediaObjectInstance, propertyInfo, rootObject);
break;
case HypermediaPropertyType.Link:
this.FillLink(hypermediaObjectInstance, propertyInfo, rootObject);
break;
case HypermediaPropertyType.Entity:
this.FillEntity(hypermediaObjectInstance, propertyInfo, rootObject);
break;
case HypermediaPropertyType.EntityCollection:
this.FillEntities(hypermediaObjectInstance, propertyInfo, rootObject);
break;
case HypermediaPropertyType.Command:
this.FillCommand(hypermediaObjectInstance, propertyInfo, rootObject);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
//todo linked entities
//todo no derived types considered
private void FillEntities(HypermediaClientObject hypermediaObjectInstance, PropertyInfo propertyInfo, IToken rootObject)
{
var relationsAttribute = propertyInfo.GetCustomAttribute<HypermediaRelationsAttribute>();
var classes = this.GetClassesFromEntitiesListProperty(propertyInfo);
var entityCollection = Activator.CreateInstance(propertyInfo.PropertyType);
propertyInfo.SetValue(hypermediaObjectInstance, entityCollection);
var entities = rootObject["entities"];
if (entities == null)
{
return;
}
var matchingEntities = entities.Where(e =>
this.EntityRelationsMatch(e, relationsAttribute.Relations) && this.EntityClassMatch(e, classes, propertyInfo.Name));
var genericAddFunction = entityCollection.GetType().GetTypeInfo().GetMethod("Add");
foreach (var match in matchingEntities)
{
var entity = this.ReadHypermediaObject(match);
genericAddFunction.Invoke(entityCollection, new object[] { entity });
}
}
private void FillCommand(HypermediaClientObject hypermediaObjectInstance, PropertyInfo propertyInfo, IToken rootObject)
{
var commandAttribute = propertyInfo.GetCustomAttribute<HypermediaCommandAttribute>();
if (commandAttribute == null)
{
throw new Exception($"Hypermedia command '{propertyInfo.Name}' requires a {nameof(HypermediaCommandAttribute)} ");
}
// create instance in any case so CanExecute can be called
var commandInstance = this.CreateHypermediaClientCommand(propertyInfo.PropertyType);
commandInstance.Resolver = this.resolver;
propertyInfo.SetValue(hypermediaObjectInstance, commandInstance);
var actions = rootObject["actions"];
var desiredAction = actions.FirstOrDefault(e => this.IsDesiredAction(e, commandAttribute.Name));
if (actions == null || desiredAction == null)
{
if (IsMandatoryHypermediaProperty(propertyInfo))
{
throw new Exception($"Mandatory hypermedia command '{propertyInfo.Name}' not found.");
}
return;
}
this.FillCommandParameters(commandInstance, desiredAction, commandAttribute.Name);
}
private void FillCommandParameters(IHypermediaClientCommand commandInstance, IToken action, string commandName)
{
commandInstance.Name = commandName;
commandInstance.CanExecute = true;
var title = action["title"]?.ValueAsString();
if (title == null)
{
title = string.Empty;
}
commandInstance.Title = title;
var uri = action["href"]?.ValueAsString();
if (uri == null)
{
throw new Exception($"Siren action without href: '{commandName}'");
}
commandInstance.Uri = new Uri(uri);
var method = action["method"]?.ValueAsString();
if (method == null)
{
method = "GET";
}
commandInstance.Method = method;
var fields = action["fields"];
if (!commandInstance.HasParameters && fields != null)
{
throw new Exception($"hypermedia Command '{commandName}' has no parameter but hypermedia document indicates parameters.");
}
if (fields == null)
{
if (commandInstance.HasParameters)
{
throw new Exception($"hypermedia Command '{commandName}' has parameter but hypermedia document has not.");
}
return;
}
foreach (var field in fields)
{
var parameterDescription = new ParameterDescription
{
Name = field["name"].ValueAsString(),
Type = field["type"].ValueAsString(),
Classes = field["class"]?.ChildrenAsStrings().ToList(),
};
// todo optional but not save, or check annotation on class
commandInstance.ParameterDescriptions.Add(parameterDescription);
}
}
private IHypermediaClientCommand CreateHypermediaClientCommand(Type commandType)
{
var commandInstance = this.hypermediaCommandFactory.Create(commandType);
return commandInstance;
}
private bool IsDesiredAction(IToken action, string commandName)
{
var name = action["name"]?.ValueAsString();
if (name == null)
{
return false;
}
return name.Equals(commandName);
}
private void FillEntity(HypermediaClientObject hypermediaObjectInstance, PropertyInfo propertyInfo, IToken rootObject)
{
var relationsAttribute = propertyInfo.GetCustomAttribute<HypermediaRelationsAttribute>();
var classes = GetClassesFromEntityProperty(propertyInfo.PropertyType.GetTypeInfo());
var entities = rootObject["entities"];
if (entities == null)
{
if (IsMandatoryHypermediaProperty(propertyInfo))
{
throw new Exception($"Mandatory hypermedia property can not be filled {propertyInfo.Name}: server object contains no entities.");
}
return;
}
var jEntity = entities.FirstOrDefault( e =>
this.EntityRelationsMatch(e, relationsAttribute.Relations) && this.EntityClassMatch(e, classes, propertyInfo.Name));
if (jEntity == null)
{
if (IsMandatoryHypermediaProperty(propertyInfo)) {
throw new Exception($"Mandatory hypermedia property can not be filled {propertyInfo.Name}: server object contains no entity of matching type (relation and class).");
}
return;
}
var entity = this.ReadHypermediaObject(jEntity);
propertyInfo.SetValue(hypermediaObjectInstance, entity);
}
private IDistinctOrderedCollection<string> GetClassesFromEntitiesListProperty(PropertyInfo propertyInfo)
{
var genericListType = GetGenericFromICollection(propertyInfo.PropertyType);
return GetClassesFromEntityProperty(genericListType.GetTypeInfo());
}
private static IDistinctOrderedCollection<string> GetClassesFromEntityProperty(TypeInfo targetTypeInfo)
{
var classAttribute = targetTypeInfo.GetCustomAttribute<HypermediaClientObjectAttribute>();
IDistinctOrderedCollection<string> classes;
if (classAttribute == null || classAttribute.Classes == null)
{
classes = new DistinctOrderedStringCollection(targetTypeInfo.Name);
}
else
{
classes = classAttribute.Classes;
}
return classes;
}
private bool EntityClassMatch(IToken entity, IDistinctOrderedCollection<string> expectedClasses, string propertyName)
{
if (expectedClasses == null || expectedClasses.Count == 0)
{
throw new Exception($"No class provided for entity property '{propertyName}'.");
}
var actualClasses = entity["class"];
if (actualClasses == null)
{
return false;
}
return this.distinctOrderedStringCollectionComparer.Equals(new DistinctOrderedStringCollection(actualClasses.ChildrenAsStrings()), expectedClasses);
}
private bool EntityRelationsMatch(IToken entity, IDistinctOrderedCollection<string> expectedRelations)
{
if (expectedRelations == null || expectedRelations.Count == 0)
{
return true;
}
var actualRelations = entity["rel"];
if (actualRelations == null)
{
return false;
}
return this.distinctOrderedStringCollectionComparer.Equals(new DistinctOrderedStringCollection(actualRelations.ChildrenAsStrings()), expectedRelations);
}
private void FillLink(HypermediaClientObject hypermediaObjectInstance, PropertyInfo propertyInfo, IToken rootObject)
{
var linkAttribute = propertyInfo.GetCustomAttribute<HypermediaRelationsAttribute>();
if (linkAttribute == null)
{
throw new Exception($"{nameof(IHypermediaLink)} requires a {nameof(HypermediaRelationsAttribute)} Attribute.");
}
var hypermediaLink = (IHypermediaLink)Activator.CreateInstance(propertyInfo.PropertyType);
hypermediaLink.Resolver = this.resolver;
propertyInfo.SetValue(hypermediaObjectInstance, hypermediaLink);
var links = rootObject["links"];
if (links == null)
{
if (IsMandatoryHypermediaLink(propertyInfo))
{
throw new Exception($"Mandatory link not found {propertyInfo.Name}");
}
return;
}
var link = links.FirstOrDefault(l => this.distinctOrderedStringCollectionComparer.Equals(new DistinctOrderedStringCollection(l["rel"].ChildrenAsStrings()), linkAttribute.Relations));
if (link == null)
{
if (IsMandatoryHypermediaLink(propertyInfo))
{
throw new Exception($"Mandatory link not found {propertyInfo.Name}");
}
return;
}
hypermediaLink.Uri = new Uri(link["href"].ValueAsString());
hypermediaLink.Relations = link["rel"].ChildrenAsStrings().ToList();
}
// todo attribute with different property name
private static void FillProperty(HypermediaClientObject hypermediaObjectInstance, PropertyInfo propertyInfo, IToken rootObject)
{
var properties = rootObject["properties"];
if (properties == null)
{
if (IsMandatoryHypermediaProperty(propertyInfo)) {
throw new Exception($"Mandatory property not found {propertyInfo.Name}");
}
return;
}
var propertyValue = properties[propertyInfo.Name];
if (propertyValue == null)
{
if (IsMandatoryHypermediaProperty(propertyInfo))
{
throw new Exception($"Mandatory property not found {propertyInfo.Name}");
}
return;
}
propertyInfo.SetValue(hypermediaObjectInstance, propertyValue.ToObject(propertyInfo.PropertyType));
}
private static bool IsMandatoryHypermediaProperty(PropertyInfo propertyInfo)
{
return propertyInfo.GetCustomAttribute<MandatoryAttribute>() != null;
}
private static bool IsMandatoryHypermediaLink(PropertyInfo propertyInfo)
{
return propertyInfo.PropertyType.GetTypeInfo().IsAssignableFrom(typeof(MandatoryHypermediaLink<>))
|| propertyInfo.GetCustomAttribute<MandatoryAttribute>() != null;
}
private static HypermediaPropertyType GetHypermediaPropertyType(PropertyInfo propertyInfo)
{
var propertyType = propertyInfo.PropertyType;
if (typeof(IHypermediaLink).GetTypeInfo().IsAssignableFrom(propertyType))
{
return HypermediaPropertyType.Link;
}
if (typeof(HypermediaClientObject).GetTypeInfo().IsAssignableFrom(propertyType))
{
return HypermediaPropertyType.Entity;
}
if (typeof(IHypermediaClientCommand).GetTypeInfo().IsAssignableFrom(propertyType))
{
return HypermediaPropertyType.Command;
}
var isCollection = IsGenericCollection(propertyType);
if (isCollection)
{
var collectionType = GetGenericFromICollection(propertyType);
if (typeof(HypermediaClientObject).GetTypeInfo().IsAssignableFrom(collectionType))
{
return HypermediaPropertyType.EntityCollection;
}
}
return HypermediaPropertyType.Property;
}
private static bool IsGenericCollection(Type propertyType)
{
return propertyType.GetTypeInfo().IsGenericType && propertyType.GetTypeInfo().GetInterface("ICollection") != null;
}
private static Type GetGenericFromICollection(Type type)
{
return type.GetTypeInfo().GetGenericArguments()[0];
}
private void ReadRelations(HypermediaClientObject hypermediaObjectInstance, IToken rootObject)
{
var relations = rootObject["rel"]?.ChildrenAsStrings();
if (relations == null)
{
return;
}
hypermediaObjectInstance.Relations = relations.ToList();
}
private void ReadTitle(HypermediaClientObject hypermediaObjectInstance, IToken rootObject)
{
var title = rootObject["title"];
if (title == null)
{
return;
}
hypermediaObjectInstance.Title = title.ValueAsString();
}
private static IDistinctOrderedCollection<string> ReadClasses(IToken rootObject)
{
// todo catch exception
// rel migth be missing so provide better error message
return new DistinctOrderedStringCollection(rootObject["class"].ChildrenAsStrings());
}
}
}
| |
/* ====================================================================
Licensed To the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file To You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed To in writing, software
distributed under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using System.Text;
using System.Collections;
using NPOI.Util;
using NPOI.HPSF.Wellknown;
/// <summary>
/// Represents a section in a {@link PropertySet}.
/// @author Rainer Klute
/// <a href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
/// @author Drew Varner (Drew.Varner allUpIn sc.edu)
/// @since 2002-02-09
/// </summary>
public class Section
{
/**
* Maps property IDs To section-private PID strings. These
* strings can be found in the property with ID 0.
*/
protected IDictionary dictionary;
/**
* The section's format ID, {@link #GetFormatID}.
*/
protected ClassID formatID;
/// <summary>
/// Returns the format ID. The format ID is the "type" of the
/// section. For example, if the format ID of the first {@link
/// Section} Contains the bytes specified by
/// <c>org.apache.poi.hpsf.wellknown.SectionIDMap.SUMMARY_INFORMATION_ID</c>
/// the section (and thus the property Set) is a SummaryInformation.
/// </summary>
/// <value>The format ID.</value>
public ClassID FormatID
{
get { return formatID; }
}
protected long offset;
/// <summary>
/// Gets the offset of the section in the stream.
/// </summary>
/// <value>The offset of the section in the stream</value>
public long OffSet
{
get { return offset; }
}
protected int size;
/// <summary>
/// Returns the section's size in bytes.
/// </summary>
/// <value>The section's size in bytes.</value>
public virtual int Size
{
get { return size; }
}
/// <summary>
/// Returns the number of properties in this section.
/// </summary>
/// <value>The number of properties in this section.</value>
public virtual int PropertyCount
{
get { return properties.Length; }
}
protected Property[] properties;
/// <summary>
/// Returns this section's properties.
/// </summary>
/// <value>This section's properties.</value>
public virtual Property[] Properties
{
get { return properties; }
}
/// <summary>
/// Creates an empty and uninitialized {@link Section}.
/// </summary>
protected Section()
{ }
/// <summary>
/// Creates a {@link Section} instance from a byte array.
/// </summary>
/// <param name="src">Contains the complete property Set stream.</param>
/// <param name="offset">The position in the stream that points To the
/// section's format ID.</param>
public Section(byte[] src, int offset)
{
int o1 = offset;
/*
* Read the format ID.
*/
formatID = new ClassID(src, o1);
o1 += ClassID.LENGTH;
/*
* Read the offset from the stream's start and positions To
* the section header.
*/
this.offset = LittleEndian.GetUInt(src, o1);
o1 = (int)this.offset;
/*
* Read the section Length.
*/
size = (int)LittleEndian.GetUInt(src, o1);
o1 += LittleEndianConsts.INT_SIZE;
/*
* Read the number of properties.
*/
int propertyCount = (int)LittleEndian.GetUInt(src, o1);
o1 += LittleEndianConsts.INT_SIZE;
/*
* Read the properties. The offset is positioned at the first
* entry of the property list. There are two problems:
*
* 1. For each property we have To Find out its Length. In the
* property list we Find each property's ID and its offset relative
* To the section's beginning. Unfortunately the properties in the
* property list need not To be in ascending order, so it is not
* possible To calculate the Length as
* (offset of property(i+1) - offset of property(i)). Before we can
* that we first have To sort the property list by ascending offsets.
*
* 2. We have To Read the property with ID 1 before we Read other
* properties, at least before other properties containing strings.
* The reason is that property 1 specifies the codepage. If it Is
* 1200, all strings are in Unicode. In other words: Before we can
* Read any strings we have To know whether they are in Unicode or
* not. Unfortunately property 1 is not guaranteed To be the first in
* a section.
*
* The algorithm below Reads the properties in two passes: The first
* one looks for property ID 1 and extracts the codepage number. The
* seconds pass Reads the other properties.
*/
properties = new Property[propertyCount];
/* Pass 1: Read the property list. */
int pass1OffSet = o1;
ArrayList propertyList = new ArrayList(propertyCount);
PropertyListEntry ple;
for (int i = 0; i < properties.Length; i++)
{
ple = new PropertyListEntry();
/* Read the property ID. */
ple.id = (int)LittleEndian.GetUInt(src, pass1OffSet);
pass1OffSet += LittleEndianConsts.INT_SIZE;
/* OffSet from the section's start. */
ple.offset = (int)LittleEndian.GetUInt(src, pass1OffSet);
pass1OffSet += LittleEndianConsts.INT_SIZE;
/* Add the entry To the property list. */
propertyList.Add(ple);
}
/* Sort the property list by ascending offsets: */
propertyList.Sort();
/* Calculate the properties' Lengths. */
for (int i = 0; i < propertyCount - 1; i++)
{
PropertyListEntry ple1 =
(PropertyListEntry)propertyList[i];
PropertyListEntry ple2 =
(PropertyListEntry)propertyList[i + 1];
ple1.Length = ple2.offset - ple1.offset;
}
if (propertyCount > 0)
{
ple = (PropertyListEntry)propertyList[propertyCount - 1];
ple.Length = size - ple.offset;
//if (ple.Length <= 0)
//{
// StringBuilder b = new StringBuilder();
// b.Append("The property Set claims To have a size of ");
// b.Append(size);
// b.Append(" bytes. However, it exceeds ");
// b.Append(ple.offset);
// b.Append(" bytes.");
// throw new IllegalPropertySetDataException(b.ToString());
//}
}
/* Look for the codepage. */
int codepage = -1;
for (IEnumerator i = propertyList.GetEnumerator();
codepage == -1 && i.MoveNext(); )
{
ple = (PropertyListEntry)i.Current;
/* Read the codepage if the property ID is 1. */
if (ple.id == PropertyIDMap.PID_CODEPAGE)
{
/* Read the property's value type. It must be
* VT_I2. */
int o = (int)(this.offset + ple.offset);
long type = LittleEndian.GetUInt(src, o);
o += LittleEndianConsts.INT_SIZE;
if (type != Variant.VT_I2)
throw new HPSFRuntimeException
("Value type of property ID 1 is not VT_I2 but " +
type + ".");
/* Read the codepage number. */
codepage = LittleEndian.GetUShort(src, o);
}
}
/* Pass 2: Read all properties - including the codepage property,
* if available. */
int i1 = 0;
for (IEnumerator i = propertyList.GetEnumerator(); i.MoveNext(); )
{
ple = (PropertyListEntry)i.Current;
Property p = new Property(ple.id, src,
this.offset + ple.offset,
ple.Length, codepage);
if (p.ID == PropertyIDMap.PID_CODEPAGE)
p = new Property(p.ID, p.Type, codepage);
properties[i1++] = p;
}
/*
* Extract the dictionary (if available).
* Tony changed the logic
*/
this.dictionary = (IDictionary)GetProperty(0);
}
/**
* Represents an entry in the property list and holds a property's ID and
* its offset from the section's beginning.
*/
class PropertyListEntry : IComparable
{
public int id;
public int offset;
public int Length;
/**
* Compares this {@link PropertyListEntry} with another one by their
* offsets. A {@link PropertyListEntry} is "smaller" than another one if
* its offset from the section's begin is smaller.
*
* @see Comparable#CompareTo(java.lang.Object)
*/
public int CompareTo(Object o)
{
if (!(o is PropertyListEntry))
throw new InvalidCastException(o.ToString());
int otherOffSet = ((PropertyListEntry)o).offset;
if (offset < otherOffSet)
return -1;
else if (offset == otherOffSet)
return 0;
else
return 1;
}
public override String ToString()
{
StringBuilder b = new StringBuilder();
b.Append(GetType().Name);
b.Append("[id=");
b.Append(id);
b.Append(", offset=");
b.Append(offset);
b.Append(", Length=");
b.Append(Length);
b.Append(']');
return b.ToString();
}
}
/**
* Returns the value of the property with the specified ID. If
* the property is not available, <c>null</c> is returned
* and a subsequent call To {@link #wasNull} will return
* <c>true</c>.
*
* @param id The property's ID
*
* @return The property's value
*/
public virtual Object GetProperty(long id)
{
wasNull = false;
for (int i = 0; i < properties.Length; i++)
if (id == properties[i].ID)
return properties[i].Value;
wasNull = true;
return null;
}
/**
* Returns the value of the numeric property with the specified
* ID. If the property is not available, 0 is returned. A
* subsequent call To {@link #wasNull} will return
* <c>true</c> To let the caller distinguish that case from
* a real property value of 0.
*
* @param id The property's ID
*
* @return The property's value
*/
public virtual int GetPropertyIntValue(long id)
{
Object o = GetProperty(id);
if (o == null)
return 0;
if (!(o is long || o is int))
throw new HPSFRuntimeException
("This property is not an integer type, but " +
o.GetType().Name + ".");
return (int)o;
}
/**
* Returns the value of the bool property with the specified
* ID. If the property is not available, <c>false</c> Is
* returned. A subsequent call To {@link #wasNull} will return
* <c>true</c> To let the caller distinguish that case from
* a real property value of <c>false</c>.
*
* @param id The property's ID
*
* @return The property's value
*/
public virtual bool GetPropertyBooleanValue(int id)
{
object tmp = GetProperty(id);
if (tmp != null)
{
return (bool)GetProperty(id);
}
else
{
return false;
}
}
/**
* This member is <c>true</c> if the last call To {@link
* #GetPropertyIntValue} or {@link #GetProperty} tried To access a
* property that was not available, else <c>false</c>.
*/
private bool wasNull;
/// <summary>
/// Checks whether the property which the last call To {@link
/// #GetPropertyIntValue} or {@link #GetProperty} tried To access
/// was available or not. This information might be important for
/// callers of {@link #GetPropertyIntValue} since the latter
/// returns 0 if the property does not exist. Using {@link
/// #wasNull} the caller can distiguish this case from a property's
/// real value of 0.
/// </summary>
/// <value><c>true</c> if the last call To {@link
/// #GetPropertyIntValue} or {@link #GetProperty} tried To access a
/// property that was not available; otherwise, <c>false</c>.</value>
public virtual bool WasNull
{
get { return wasNull; }
}
/// <summary>
/// Returns the PID string associated with a property ID. The ID
/// is first looked up in the {@link Section}'s private
/// dictionary. If it is not found there, the method calls {@link
/// SectionIDMap#GetPIDString}.
/// </summary>
/// <param name="pid">The property ID.</param>
/// <returns>The property ID's string value</returns>
public String GetPIDString(long pid)
{
String s = null;
if (dictionary != null)
s = (String)dictionary[pid];
if (s == null)
s = SectionIDMap.GetPIDString(FormatID.Bytes, pid);
if (s == null)
s = SectionIDMap.UNDEFINED;
return s;
}
/**
* Checks whether this section is equal To another object. The result Is
* <c>false</c> if one of the the following conditions holds:
*
* <ul>
*
* <li>The other object is not a {@link Section}.</li>
*
* <li>The format IDs of the two sections are not equal.</li>
*
* <li>The sections have a different number of properties. However,
* properties with ID 1 (codepage) are not counted.</li>
*
* <li>The other object is not a {@link Section}.</li>
*
* <li>The properties have different values. The order of the properties
* is irrelevant.</li>
*
* </ul>
*
* @param o The object To Compare this section with
* @return <c>true</c> if the objects are equal, <c>false</c> if
* not
*/
public override bool Equals(Object o)
{
if (o == null || !(o is Section))
return false;
Section s = (Section)o;
if (!s.FormatID.Equals(FormatID))
return false;
/* Compare all properties except 0 and 1 as they must be handled
* specially. */
Property[] pa1 = new Property[Properties.Length];
Property[] pa2 = new Property[s.Properties.Length];
System.Array.Copy(Properties, 0, pa1, 0, pa1.Length);
System.Array.Copy(s.Properties, 0, pa2, 0, pa2.Length);
/* Extract properties 0 and 1 and Remove them from the copy of the
* arrays. */
Property p10 = null;
Property p20 = null;
for (int i = 0; i < pa1.Length; i++)
{
long id = pa1[i].ID;
if (id == 0)
{
p10 = pa1[i];
pa1 = Remove(pa1, i);
i--;
}
if (id == 1)
{
// p11 = pa1[i];
pa1 = Remove(pa1, i);
i--;
}
}
for (int i = 0; i < pa2.Length; i++)
{
long id = pa2[i].ID;
if (id == 0)
{
p20 = pa2[i];
pa2 = Remove(pa2, i);
i--;
}
if (id == 1)
{
// p21 = pa2[i];
pa2 = Remove(pa2, i);
i--;
}
}
/* If the number of properties (not counting property 1) is unequal the
* sections are unequal. */
if (pa1.Length != pa2.Length)
return false;
/* If the dictionaries are unequal the sections are unequal. */
bool dictionaryEqual = true;
if (p10 != null && p20 != null)
{
//tony qu fixed this issue
Hashtable a=(Hashtable)p10.Value;
Hashtable b = (Hashtable)p20.Value;
dictionaryEqual = a.Count==b.Count;
}
else if (p10 != null || p20 != null)
{
dictionaryEqual = false;
}
if (!dictionaryEqual)
return false;
else
return Util.AreEqual(pa1, pa2);
}
/// <summary>
/// Removes a field from a property array. The resulting array Is
/// compactified and returned.
/// </summary>
/// <param name="pa">The property array.</param>
/// <param name="i">The index of the field To be Removed.</param>
/// <returns>the compactified array.</returns>
private Property[] Remove(Property[] pa, int i)
{
Property[] h = new Property[pa.Length - 1];
if (i > 0)
System.Array.Copy(pa, 0, h, 0, i);
System.Array.Copy(pa, i + 1, h, i, h.Length - i);
return h;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
long GetHashCode = 0;
GetHashCode += FormatID.GetHashCode();
Property[] pa = Properties;
for (int i = 0; i < pa.Length; i++)
GetHashCode += pa[i].GetHashCode();
int returnHashCode = (int)(GetHashCode & 0x0ffffffffL);
return returnHashCode;
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
StringBuilder b = new StringBuilder();
Property[] pa = Properties;
b.Append(GetType().Name);
b.Append('[');
b.Append("formatID: ");
b.Append(FormatID);
b.Append(", offset: ");
b.Append(OffSet);
b.Append(", propertyCount: ");
b.Append(PropertyCount);
b.Append(", size: ");
b.Append(Size);
b.Append(", properties: [\n");
for (int i = 0; i < pa.Length; i++)
{
b.Append(pa[i].ToString());
b.Append(",\n");
}
b.Append(']');
b.Append(']');
return b.ToString();
}
/// <summary>
/// Gets the section's dictionary. A dictionary allows an application To
/// use human-Readable property names instead of numeric property IDs. It
/// Contains mappings from property IDs To their associated string
/// values. The dictionary is stored as the property with ID 0. The codepage
/// for the strings in the dictionary is defined by property with ID 1.
/// </summary>
/// <value>the dictionary or null
/// if the section does not have
/// a dictionary.</value>
public virtual IDictionary Dictionary
{
get {
if (dictionary == null)
dictionary = new Hashtable();
return dictionary;
}
set {
dictionary = value;
}
}
/// <summary>
/// Gets the section's codepage, if any.
/// </summary>
/// <value>The section's codepage if one is defined, else -1.</value>
public int Codepage
{
get
{
if (GetProperty(PropertyIDMap.PID_CODEPAGE) == null)
return -1;
int codepage =
(int)GetProperty(PropertyIDMap.PID_CODEPAGE);
return codepage;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009-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.Generic;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework
{
/// <summary>
/// TestFixtureAttribute is used to mark a class that represents a TestFixture.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)]
public class TestFixtureAttribute : NUnitAttribute, IFixtureBuilder, ITestFixtureData
{
private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder();
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public TestFixtureAttribute() : this( new object[0] ) { }
/// <summary>
/// Construct with a object[] representing a set of arguments.
/// In .NET 2.0, the arguments may later be separated into
/// type arguments and constructor arguments.
/// </summary>
/// <param name="arguments"></param>
public TestFixtureAttribute(params object[] arguments)
{
RunState = RunState.Runnable;
Arguments = arguments;
TypeArgs = new Type[0];
Properties = new PropertyBag();
}
#endregion
#region ITestData Members
/// <summary>
/// Gets or sets the name of the test.
/// </summary>
/// <value>The name of the test.</value>
public string TestName { get; set; }
/// <summary>
/// Gets or sets the RunState of this test fixture.
/// </summary>
public RunState RunState { get; private set; }
/// <summary>
/// The arguments originally provided to the attribute
/// </summary>
public object[] Arguments { get; private set; }
/// <summary>
/// Properties pertaining to this fixture
/// </summary>
public IPropertyBag Properties { get; private set; }
#endregion
#region ITestFixtureData Members
/// <summary>
/// Get or set the type arguments. If not set
/// explicitly, any leading arguments that are
/// Types are taken as type arguments.
/// </summary>
public Type[] TypeArgs { get; set; }
#endregion
#region Other Properties
/// <summary>
/// Descriptive text for this fixture
/// </summary>
public string Description
{
get { return Properties.Get(PropertyNames.Description) as string; }
set { Properties.Set(PropertyNames.Description, value); }
}
/// <summary>
/// The author of this fixture
/// </summary>
public string Author
{
get { return Properties.Get(PropertyNames.Author) as string; }
set { Properties.Set(PropertyNames.Author, value); }
}
/// <summary>
/// The type that this fixture is testing
/// </summary>
public Type TestOf
{
get { return _testOf; }
set
{
_testOf = value;
Properties.Set(PropertyNames.TestOf, value.FullName);
}
}
private Type _testOf;
/// <summary>
/// Gets or sets the ignore reason. May set RunState as a side effect.
/// </summary>
/// <value>The ignore reason.</value>
public string Ignore
{
get { return IgnoreReason; }
set { IgnoreReason = value; }
}
/// <summary>
/// Gets or sets the reason for not running the fixture.
/// </summary>
/// <value>The reason.</value>
public string Reason
{
get { return this.Properties.Get(PropertyNames.SkipReason) as string; }
set { this.Properties.Set(PropertyNames.SkipReason, value); }
}
/// <summary>
/// Gets or sets the ignore reason. When set to a non-null
/// non-empty value, the test is marked as ignored.
/// </summary>
/// <value>The ignore reason.</value>
public string IgnoreReason
{
get { return Reason; }
set
{
RunState = RunState.Ignored;
Reason = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestFixtureAttribute"/> is explicit.
/// </summary>
/// <value>
/// <c>true</c> if explicit; otherwise, <c>false</c>.
/// </value>
public bool Explicit
{
get { return RunState == RunState.Explicit; }
set { RunState = value ? RunState.Explicit : RunState.Runnable; }
}
/// <summary>
/// Gets and sets the category for this fixture.
/// May be a comma-separated list of categories.
/// </summary>
public string Category
{
get
{
//return Properties.Get(PropertyNames.Category) as string;
var catList = Properties[PropertyNames.Category];
if (catList == null)
return null;
switch (catList.Count)
{
case 0:
return null;
case 1:
return catList[0] as string;
default:
var cats = new string[catList.Count];
int index = 0;
foreach (string cat in catList)
cats[index++] = cat;
return string.Join(",", cats);
}
}
set
{
foreach (string cat in value.Split(new char[] { ',' }))
Properties.Add(PropertyNames.Category, cat);
}
}
#endregion
#region IFixtureBuilder Members
/// <summary>
/// Build a fixture from type provided. Normally called for a Type
/// on which the attribute has been placed.
/// </summary>
/// <param name="type">The type of the fixture to be used.</param>
/// <returns>A an IEnumerable holding one TestFixture object.</returns>
public IEnumerable<TestSuite> BuildFrom(Type type)
{
yield return _builder.BuildFrom(type, this);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="PublishSubscribeChannel.cs" company="The Phantom Coder">
// Copyright The Phantom Coder. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Phantom.PubSub
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Transactions;
using Phantom.PubSub;
/// <summary>
/// PublishSubscribeChannel will accepts new messages puts them on a queue and fire calls to all subscribers
/// </summary>
/// <typeparam name="T">The Type that you wish tp publish each type requires its own implementation</typeparam>
public class PublishSubscribeChannel<T> : IPublishSubscribeChannel<T>
{
private Dictionary<string, Tuple<string, Type, TimeSpan>> subscriberInfos = new Dictionary<string, Tuple<string, Type, TimeSpan>>();
/// <summary>
/// Initializes a new instance of the <see cref="PublishSubscribeChannel{T}" /> class.
/// </summary>
public PublishSubscribeChannel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="PublishSubscribeChannel{T}" /> class.
/// </summary>
/// <param name="queueProvider">The queue provider.</param>
public PublishSubscribeChannel(IStoreProvider<T> queueProvider)
{
this.StorageProvider = queueProvider;
}
public IStoreProvider<T> StorageProvider { get; set; }
public int Count
{
get
{
return this.StorageProvider.GetMessageCount();
}
}
/// <summary>
/// Publishes a message first by placing on a durable Queue, then passing the message to a new thread for processing.
/// Returns as soon as the message is succesfully on the Queue.
/// This component does not read the message from the Queue to start processing. It takes the same message that is added to the Queue and starts processing
/// as soon as it is guaranteed to be on the queue.
/// It will only throw exceptions from the AutoConfiguration
/// </summary>
/// <param name="message">The message of the type specified to process</param>
public void PublishMessage(T message)
{
if (!BatchProcessor<T>.IsConfigured)
{
BatchProcessor<T>.ConfigureWithPubSubChannel(this);
}
if (this.subscriberInfos.Count == 0)
{
foreach (var item in AutoConfig<T>.SubscriberInfos)
{
this.subscriberInfos.Add(item.Item1, new Tuple<string, Type, TimeSpan>(item.Item1, item.Item2, item.Item3));
}
}
List<ISubscriberMetadata> metadatalist = new List<ISubscriberMetadata>();
foreach (var item in this.subscriberInfos)
{
var subscribermetadata = new SubscriberMetadata()
{
Name = item.Key,
TimeToExpire = item.Value.Item3,
StartTime = DateTime.Now
};
metadatalist.Add(subscribermetadata);
}
var messageForQueue = new MessagePacket<T>(message, metadatalist);
string result = this.StorageProvider.PutMessage(messageForQueue);
Task.Factory.StartNew(() => this.HandleMessageForFirstTime(messageForQueue, result));
}
/// <summary>
/// Batch processing alternative, this is used as part of the clean up process for Messages that expire prior to being handled.
/// </summary>
public void ProcessBatch()
{
this.StorageProvider.ProcessStoreAsBatch(this.HandleMessageForBatchProcessing);
}
/// <summary>
/// This method receives a single message and processes all of the subscribers for each individual message. The subscribers are processed in parallel
/// to ensure that one long running process will not impact the others.
/// When all subscribers have indicate they have completed a flag is set to indicate that this message has completed publishing, and it is removed
/// from the Queue
/// This method uses the Parallel.ForEach method, so Visual Studio parallel debugging can be used.
/// It will not return a exception
/// </summary>
/// <param name="messagePacket">THe message being sent inside of the messagepacket wrapper</param>
/// <param name="messageId">ID of message generated by the queue in mechanism</param>
/// <returns>True on success</returns>
public bool HandleMessageForFirstTime(MessagePacket<T> messagePacket, string messageId)
{
if (messagePacket == null)
{
throw new ArgumentNullException("messagePacket");
}
if (string.IsNullOrEmpty(messageId))
{
throw new ArgumentNullException("messagePacket");
}
var subscribersForThisMessage = this.GetSubscriptions();
this.RunSubscriptions(messagePacket, messageId, subscribersForThisMessage);
return true;
}
/// <summary>
/// Handles the message for batch processing.
/// This code is called from the batch processor, which means that it has queried the store for all messages, and sent them to this method
/// they may or may not have finished processing, if they have then the metadata will have been updated (or updated for those subscribers that have completed or failed)
/// If they have not finished processing then the metadat will still reflect what was the state of the subscription at the time that the
/// message was first saved to the store.
/// </summary>
/// <param name="messagePacket">The message packet.</param>
/// <param name="messageId">The message id.</param>
/// <returns>Always returns true - need to change to void</returns>
/// <exception cref="System.ArgumentNullException">Argument Null Exception</exception>
public bool HandleMessageForBatchProcessing(MessagePacket<T> messagePacket, string messageId)
{
if (messagePacket == null)
{
throw new ArgumentNullException("messagePacket");
}
if (string.IsNullOrEmpty(messageId))
{
throw new ArgumentNullException("messageId");
}
var runnableSubscribersCollection = new SubscribersCollection<T>();
foreach (var item in messagePacket.SubscriberMetadataList)
{
if (item.CanProcess())
{
string subscriptionId = GetSubscriptionId(messageId, item.Name);
var subscriberInfo = this.subscriberInfos.FirstOrDefault(si => si.Key == item.Name);
var newSubscription = (ISubscriber<T>)Activator.CreateInstance(subscriberInfo.Value.Item2);
newSubscription.Name = subscriberInfo.Value.Item1;
newSubscription.TimeToExpire = subscriberInfo.Value.Item3;
newSubscription.Id = subscriptionId;
newSubscription.AbortCount = item.RetryCount;
newSubscription.Aborted = false;
newSubscription.MessageId = messageId;
newSubscription.StartTime = DateTime.Now;
runnableSubscribersCollection.Add(newSubscription);
}
}
this.RunSubscriptions(messagePacket, messageId, runnableSubscribersCollection);
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Its Appropriate")]
public SubscribersCollection<T> GetSubscriptions()
{
if (this.subscriberInfos == null || this.subscriberInfos.Count == 0)
{
throw new InvalidOperationException("There are no subscribers set up for this channel");
}
var subscribers = new SubscribersCollection<T>();
foreach (var item in this.subscriberInfos)
{
ISubscriber<T> subscriber = (ISubscriber<T>)Activator.CreateInstance(item.Value.Item2);
subscriber.Name = item.Value.Item1;
subscriber.TimeToExpire = item.Value.Item3;
subscribers.Add(subscriber);
}
return subscribers;
}
public ISubscriberInfo<T> AddSubscriberType(Type type)
{
return new SubscriberInfo<T>(type, this);
}
public IPublishSubscribeChannel<T> AddSubscriberInfo(Tuple<string, Type, TimeSpan> tuple)
{
if (tuple == null)
{
throw new ArgumentNullException("tuple");
}
this.subscriberInfos.Add(tuple.Item1, tuple);
return this;
}
////private static bool HasExpired(ISubscriberMetadata subscriberMetaData)
////{
//// var nextstart = subscriberMetaData.StartTime + subscriberMetaData.TimeToExpire;
//// if (DateTime.Compare(DateTime.Now, nextstart) > 0)
//// {
//// return true;
//// }
//// return false;
////}
private static string GetSubscriptionId(string messageId, string subscriberName)
{
StringBuilder sb = new StringBuilder();
return sb.Append(":SubScriber::").Append(subscriberName).Append("::MessageID::").Append(messageId).Append(":").ToString();
}
private static MessagePacket<T> CreateSingleSubscriberMessagePacket(ISubscriber<T> subscriber, MessagePacket<T> messagePacket, bool failedOrTimedOut)
{
if (messagePacket == null)
{
throw new ArgumentNullException("messagePacket");
}
if (subscriber == null)
{
throw new ArgumentNullException("subscriber");
}
List<ISubscriberMetadata> metadatalist = new List<ISubscriberMetadata>();
ISubscriberMetadata subscribermetadata = new SubscriberMetadata()
{
////need to add abort count and think thru appropriate start time
Name = subscriber.GetType().Name,
TimeToExpire = subscriber.TimeToExpire,
StartTime = subscriber.StartTime,
RetryCount = subscriber.AbortCount,
FailedOrTimedOutTime = subscriber.AbortedTime,
FailedOrTimedOut = failedOrTimedOut
};
metadatalist.Add(subscribermetadata);
var newMessagePacket = new MessagePacket<T>((T)messagePacket.Body, metadatalist);
if ((messagePacket.MessageId != null) && (messagePacket.MessageId != 0))
{
newMessagePacket.MessageId = messagePacket.MessageId;
}
else
{
newMessagePacket.MessageId = Convert.ToInt32(subscriber.MessageId);
}
if (newMessagePacket.MessageId == null)
{
throw new ArgumentException("MessageId is null, and it can't be");
}
return newMessagePacket;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Error message needs to be swallowed, next processing run will try again")]
private bool HandleSingleSubscriberforMessage(MessagePacket<T> messagePacket, string messageId)
{
var metaData = messagePacket.SubscriberMetadataList[0];
string subscriptionId = GetSubscriptionId(messageId, metaData.Name);
Trace.WriteLine("About to check if I can process: " + subscriptionId);
ISubscriber<T> newSubscription = null;
if (metaData.CanProcess())
{
var subscriberInfo = this.subscriberInfos.FirstOrDefault(si => si.Key == metaData.Name);
newSubscription = (ISubscriber<T>)Activator.CreateInstance(subscriberInfo.Value.Item2);
newSubscription.Name = subscriberInfo.Value.Item1;
newSubscription.TimeToExpire = subscriberInfo.Value.Item3;
newSubscription.Id = subscriptionId;
newSubscription.AbortCount = metaData.RetryCount;
if (metaData.FailedOrTimedOut == true)
{
Debug.Assert(newSubscription.AbortCount > 0, "Abort count did not exceed 0 this is an invalid condition");
}
var cancellationTokenSource = new CancellationTokenSource(newSubscription.TimeToExpire);
Task.Run(async () =>
{
await newSubscription.RunAsync((T)messagePacket.Body, cancellationTokenSource.Token);
return true;
})
.ContinueWith(anticedant =>
{
switch (anticedant.Status)
{
case TaskStatus.RanToCompletion:
#if DEBUG
Counter.Increment(16);
#endif
this.StorageProvider.UpdateMessageStore(CreateSingleSubscriberMessagePacket(newSubscription, messagePacket, false));
this.StorageProvider.SubscriberGroupCompletedForMessage(messageId);
break;
case TaskStatus.Faulted:
try
{
newSubscription.Abort();
this.StorageProvider.UpdateMessageStore(CreateSingleSubscriberMessagePacket(newSubscription, messagePacket, true));
#if DEBUG
Counter.Increment(20);
#endif
}
catch
{
break;
}
this.StorageProvider.SubscriberGroupCompletedForMessage(messageId);
break;
case TaskStatus.Canceled:
try
{
newSubscription.Abort();
this.StorageProvider.UpdateMessageStore(CreateSingleSubscriberMessagePacket(newSubscription, messagePacket, true));
#if DEBUG
Counter.Increment(18);
#endif
}
catch
{
break;
}
this.StorageProvider.SubscriberGroupCompletedForMessage(messageId);
break;
}
cancellationTokenSource.Dispose();
});
}
return true;
}
////private bool IsReady()
////{
//// if (this.storeageProvider == null)
//// {
//// return false;
//// }
//// if (this.subscriberInfos.Count == 0)
//// {
//// return false; // will not work with no subscribers
//// }
//// return true;
////}
private void RunSubscriptions(MessagePacket<T> messagePacket, string messageId, SubscribersCollection<T> subscribersForThisMessage)
{
Task.Run(async () =>
{
foreach (var subscriber in subscribersForThisMessage)
{
string newSubscriptionId = GetSubscriptionId(messageId, subscriber.Name);
subscriber.Id = newSubscriptionId;
subscriber.MessageId = messageId;
var cancellationToken = new CancellationTokenSource(subscriber.TimeToExpire).Token;
try
{
bool result = await subscriber.RunAsync((T)messagePacket.Body, cancellationToken);
this.StorageProvider.UpdateMessageStore(CreateSingleSubscriberMessagePacket(subscriber, messagePacket, false));
#if DEBUG
Counter.Increment(14);
#endif
}
catch (OperationCanceledException)
{
subscriber.Abort();
this.StorageProvider.UpdateMessageStore(CreateSingleSubscriberMessagePacket(subscriber, messagePacket, true));
Counter.Increment(12);
////Trace.WriteLine("This task timed out : " + subscriber.Name + " The timeout timespan was: " + subscriber.TimeToExpire.TotalMilliseconds + " ms");
}
catch (Exception)
{
subscriber.Abort();
this.StorageProvider.UpdateMessageStore(CreateSingleSubscriberMessagePacket(subscriber, messagePacket, true));
#if DEBUG
Counter.Increment(13);
#endif
////Trace.WriteLine("Request failed: " + newSubscriptionId + " newMessagId" + newMessagId + " " + anticedant.Exception.InnerException.ToString());
}
}
}).ContinueWith((Anticedant) =>
{
this.StorageProvider.SubscriberGroupCompletedForMessage(messageId);
});
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class SnapshotProperties : IEquatable<SnapshotProperties>
{
/// <summary>
/// Initializes a new instance of the <see cref="SnapshotProperties" /> class.
/// </summary>
public SnapshotProperties()
{
this.CpuHotPlug = false;
this.CpuHotUnplug = false;
this.RamHotPlug = false;
this.RamHotUnplug = false;
this.NicHotPlug = false;
this.NicHotUnplug = false;
this.DiscVirtioHotPlug = false;
this.DiscVirtioHotUnplug = false;
this.DiscScsiHotPlug = false;
this.DiscScsiHotUnplug = false;
}
/// <summary>
/// A name of that resource
/// </summary>
/// <value>A name of that resource</value>
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// Human readable description
/// </summary>
/// <value>Human readable description</value>
[DataMember(Name = "description", EmitDefaultValue = false)]
public string Description { get; set; }
/// <summary>
/// Location of that image/snapshot.
/// </summary>
/// <value>Location of that image/snapshot.</value>
[DataMember(Name = "location", EmitDefaultValue = false)]
public string Location { get; set; }
/// <summary>
/// The size of the image in GB
/// </summary>
/// <value>The size of the image in GB</value>
[DataMember(Name = "size", EmitDefaultValue = false)]
public double? Size { get; set; }
/// <summary>
/// Is capable of CPU hot plug (no reboot required)
/// </summary>
/// <value>Is capable of CPU hot plug (no reboot required)</value>
[DataMember(Name = "cpuHotPlug", EmitDefaultValue = false)]
public bool? CpuHotPlug { get; set; }
/// <summary>
/// Is capable of CPU hot unplug (no reboot required)
/// </summary>
/// <value>Is capable of CPU hot unplug (no reboot required)</value>
[DataMember(Name = "cpuHotUnplug", EmitDefaultValue = false)]
public bool? CpuHotUnplug { get; set; }
/// <summary>
/// Is capable of memory hot plug (no reboot required)
/// </summary>
/// <value>Is capable of memory hot plug (no reboot required)</value>
[DataMember(Name = "ramHotPlug", EmitDefaultValue = false)]
public bool? RamHotPlug { get; set; }
/// <summary>
/// Is capable of memory hot unplug (no reboot required)
/// </summary>
/// <value>Is capable of memory hot unplug (no reboot required)</value>
[DataMember(Name = "ramHotUnplug", EmitDefaultValue = false)]
public bool? RamHotUnplug { get; set; }
/// <summary>
/// Is capable of nic hot plug (no reboot required)
/// </summary>
/// <value>Is capable of nic hot plug (no reboot required)</value>
[DataMember(Name = "nicHotPlug", EmitDefaultValue = false)]
public bool? NicHotPlug { get; set; }
/// <summary>
/// Is capable of nic hot unplug (no reboot required)
/// </summary>
/// <value>Is capable of nic hot unplug (no reboot required)</value>
[DataMember(Name = "nicHotUnplug", EmitDefaultValue = false)]
public bool? NicHotUnplug { get; set; }
/// <summary>
/// Is capable of Virt-IO drive hot plug (no reboot required)
/// </summary>
/// <value>Is capable of Virt-IO drive hot plug (no reboot required)</value>
[DataMember(Name = "discVirtioHotPlug", EmitDefaultValue = false)]
public bool? DiscVirtioHotPlug { get; set; }
/// <summary>
/// Is capable of Virt-IO drive hot unplug (no reboot required)
/// </summary>
/// <value>Is capable of Virt-IO drive hot unplug (no reboot required)</value>
[DataMember(Name = "discVirtioHotUnplug", EmitDefaultValue = false)]
public bool? DiscVirtioHotUnplug { get; set; }
/// <summary>
/// Is capable of SCSI drive hot plug (no reboot required)
/// </summary>
/// <value>Is capable of SCSI drive hot plug (no reboot required)</value>
[DataMember(Name = "discScsiHotPlug", EmitDefaultValue = false)]
public bool? DiscScsiHotPlug { get; set; }
/// <summary>
/// Is capable of SCSI drive hot unplug (no reboot required)
/// </summary>
/// <value>Is capable of SCSI drive hot unplug (no reboot required)</value>
[DataMember(Name = "discScsiHotUnplug", EmitDefaultValue = false)]
public bool? DiscScsiHotUnplug { get; set; }
/// <summary>
/// OS type of this Snapshot
/// </summary>
/// <value>OS type of this Snapshot</value>
[DataMember(Name = "licenceType", EmitDefaultValue = false)]
public string LicenceType { 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 SnapshotProperties {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" Location: ").Append(Location).Append("\n");
sb.Append(" Size: ").Append(Size).Append("\n");
sb.Append(" CpuHotPlug: ").Append(CpuHotPlug).Append("\n");
sb.Append(" CpuHotUnplug: ").Append(CpuHotUnplug).Append("\n");
sb.Append(" RamHotPlug: ").Append(RamHotPlug).Append("\n");
sb.Append(" RamHotUnplug: ").Append(RamHotUnplug).Append("\n");
sb.Append(" NicHotPlug: ").Append(NicHotPlug).Append("\n");
sb.Append(" NicHotUnplug: ").Append(NicHotUnplug).Append("\n");
sb.Append(" DiscVirtioHotPlug: ").Append(DiscVirtioHotPlug).Append("\n");
sb.Append(" DiscVirtioHotUnplug: ").Append(DiscVirtioHotUnplug).Append("\n");
sb.Append(" DiscScsiHotPlug: ").Append(DiscScsiHotPlug).Append("\n");
sb.Append(" DiscScsiHotUnplug: ").Append(DiscScsiHotUnplug).Append("\n");
sb.Append(" LicenceType: ").Append(LicenceType).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 SnapshotProperties);
}
/// <summary>
/// Returns true if SnapshotProperties instances are equal
/// </summary>
/// <param name="other">Instance of SnapshotProperties to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SnapshotProperties other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.Location == other.Location ||
this.Location != null &&
this.Location.Equals(other.Location)
) &&
(
this.Size == other.Size ||
this.Size != null &&
this.Size.Equals(other.Size)
) &&
(
this.CpuHotPlug == other.CpuHotPlug ||
this.CpuHotPlug != null &&
this.CpuHotPlug.Equals(other.CpuHotPlug)
) &&
(
this.CpuHotUnplug == other.CpuHotUnplug ||
this.CpuHotUnplug != null &&
this.CpuHotUnplug.Equals(other.CpuHotUnplug)
) &&
(
this.RamHotPlug == other.RamHotPlug ||
this.RamHotPlug != null &&
this.RamHotPlug.Equals(other.RamHotPlug)
) &&
(
this.RamHotUnplug == other.RamHotUnplug ||
this.RamHotUnplug != null &&
this.RamHotUnplug.Equals(other.RamHotUnplug)
) &&
(
this.NicHotPlug == other.NicHotPlug ||
this.NicHotPlug != null &&
this.NicHotPlug.Equals(other.NicHotPlug)
) &&
(
this.NicHotUnplug == other.NicHotUnplug ||
this.NicHotUnplug != null &&
this.NicHotUnplug.Equals(other.NicHotUnplug)
) &&
(
this.DiscVirtioHotPlug == other.DiscVirtioHotPlug ||
this.DiscVirtioHotPlug != null &&
this.DiscVirtioHotPlug.Equals(other.DiscVirtioHotPlug)
) &&
(
this.DiscVirtioHotUnplug == other.DiscVirtioHotUnplug ||
this.DiscVirtioHotUnplug != null &&
this.DiscVirtioHotUnplug.Equals(other.DiscVirtioHotUnplug)
) &&
(
this.DiscScsiHotPlug == other.DiscScsiHotPlug ||
this.DiscScsiHotPlug != null &&
this.DiscScsiHotPlug.Equals(other.DiscScsiHotPlug)
) &&
(
this.DiscScsiHotUnplug == other.DiscScsiHotUnplug ||
this.DiscScsiHotUnplug != null &&
this.DiscScsiHotUnplug.Equals(other.DiscScsiHotUnplug)
) &&
(
this.LicenceType == other.LicenceType ||
this.LicenceType != null &&
this.LicenceType.Equals(other.LicenceType)
);
}
/// <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.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.Location != null)
hash = hash * 59 + this.Location.GetHashCode();
if (this.Size != null)
hash = hash * 59 + this.Size.GetHashCode();
if (this.CpuHotPlug != null)
hash = hash * 59 + this.CpuHotPlug.GetHashCode();
if (this.CpuHotUnplug != null)
hash = hash * 59 + this.CpuHotUnplug.GetHashCode();
if (this.RamHotPlug != null)
hash = hash * 59 + this.RamHotPlug.GetHashCode();
if (this.RamHotUnplug != null)
hash = hash * 59 + this.RamHotUnplug.GetHashCode();
if (this.NicHotPlug != null)
hash = hash * 59 + this.NicHotPlug.GetHashCode();
if (this.NicHotUnplug != null)
hash = hash * 59 + this.NicHotUnplug.GetHashCode();
if (this.DiscVirtioHotPlug != null)
hash = hash * 59 + this.DiscVirtioHotPlug.GetHashCode();
if (this.DiscVirtioHotUnplug != null)
hash = hash * 59 + this.DiscVirtioHotUnplug.GetHashCode();
if (this.DiscScsiHotPlug != null)
hash = hash * 59 + this.DiscScsiHotPlug.GetHashCode();
if (this.DiscScsiHotUnplug != null)
hash = hash * 59 + this.DiscScsiHotUnplug.GetHashCode();
if (this.LicenceType != null)
hash = hash * 59 + this.LicenceType.GetHashCode();
return hash;
}
}
}
}
| |
// 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.Linq;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
using TestAttributes;
[module: Foo]
[module: Complicated(1, Stuff = 2)]
namespace TestAttributes
{
public class FooAttribute : Attribute
{
}
public class ComplicatedAttribute : Attribute
{
public int Stuff
{
get;
set;
}
public int Foo
{
get;
}
public ComplicatedAttribute(int foo)
{
Foo = foo;
}
}
}
namespace System.Reflection.Tests
{
public class ModuleTests
{
public static Module Module => typeof(ModuleTests).Module;
public static Module TestModule => typeof(TestModule.Dummy).Module;
[Fact]
public void TestAssembly()
{
Assert.Equal(Assembly.GetExecutingAssembly(), Module.Assembly);
}
[Fact]
public void ModuleHandle()
{
Assert.Equal(typeof(PointerTests).Module.ModuleHandle, Module.ModuleHandle);
}
[Fact]
public void CustomAttributes()
{
List<CustomAttributeData> customAttributes = Module.CustomAttributes.ToList();
Assert.True(customAttributes.Count >= 2);
CustomAttributeData fooAttribute = customAttributes.Single(a => a.AttributeType == typeof(FooAttribute));
Assert.Equal(typeof(FooAttribute).GetConstructors().First(), fooAttribute.Constructor);
Assert.Equal(0, fooAttribute.ConstructorArguments.Count);
Assert.Equal(0, fooAttribute.NamedArguments.Count);
CustomAttributeData complicatedAttribute = customAttributes.Single(a => a.AttributeType == typeof(ComplicatedAttribute));
Assert.Equal(typeof(ComplicatedAttribute).GetConstructors().First(), complicatedAttribute.Constructor);
Assert.Equal(1, complicatedAttribute.ConstructorArguments.Count);
Assert.Equal(typeof(int), complicatedAttribute.ConstructorArguments[0].ArgumentType);
Assert.Equal(1, (int)complicatedAttribute.ConstructorArguments[0].Value);
Assert.Equal(1, complicatedAttribute.NamedArguments.Count);
Assert.Equal(false, complicatedAttribute.NamedArguments[0].IsField);
Assert.Equal("Stuff", complicatedAttribute.NamedArguments[0].MemberName);
Assert.Equal(typeof(ComplicatedAttribute).GetProperty("Stuff"), complicatedAttribute.NamedArguments[0].MemberInfo);
Assert.Equal(typeof(int), complicatedAttribute.NamedArguments[0].TypedValue.ArgumentType);
Assert.Equal(2, complicatedAttribute.NamedArguments[0].TypedValue.Value);
}
[Fact]
public void FullyQualifiedName()
{
Assert.Equal(Assembly.GetExecutingAssembly().Location, Module.FullyQualifiedName);
}
[Fact]
public void Name()
{
Assert.Equal("system.runtime.tests.dll", Module.Name, ignoreCase: true);
}
[Fact]
public void Equality()
{
Assert.True(Assembly.GetExecutingAssembly().GetModules().First() == Module);
Assert.True(Module.Equals(Assembly.GetExecutingAssembly().GetModules().First()));
}
[Fact]
public void TestGetHashCode()
{
Assert.Equal(Assembly.GetExecutingAssembly().GetModules().First().GetHashCode(), Module.GetHashCode());
}
[Theory]
[InlineData(typeof(ModuleTests))]
[InlineData(typeof(PointerTests))]
public void TestGetType(Type type)
{
Assert.Equal(type, Module.GetType(type.FullName, true, true));
}
[Fact]
public void TestToString()
{
Assert.Equal("System.Runtime.Tests.dll", Module.ToString());
}
[Fact]
public void IsDefined_NullType()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("attributeType", () =>
{
Module.IsDefined(null, false);
});
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public void GetField_NullName()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("name", () =>
{
Module.GetField(null);
});
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
ex = AssertExtensions.Throws<ArgumentNullException>("name", () =>
{
Module.GetField(null, 0);
});
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public void GetField()
{
FieldInfo testInt = TestModule.GetField("TestInt", BindingFlags.Public | BindingFlags.Static);
Assert.Equal(1, (int)testInt.GetValue(null));
testInt.SetValue(null, 100);
Assert.Equal(100, (int)testInt.GetValue(null));
FieldInfo testLong = TestModule.GetField("TestLong", BindingFlags.NonPublic | BindingFlags.Static);
Assert.Equal(2L, (long)testLong.GetValue(null));
testLong.SetValue(null, 200);
Assert.Equal(200L, (long)testLong.GetValue(null));
}
[Fact]
public void GetFields()
{
List<FieldInfo> fields = TestModule.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static).OrderBy(f => f.Name).ToList();
Assert.Equal(2, fields.Count);
Assert.Equal(TestModule.GetField("TestInt"), fields[0]);
Assert.Equal(TestModule.GetField("TestLong", BindingFlags.NonPublic | BindingFlags.Static), fields[1]);
}
public static IEnumerable<object[]> Types =>
Module.GetTypes().Select(t => new object[] { t });
[Theory]
[MemberData(nameof(Types))]
public void ResolveType(Type t)
{
Assert.Equal(t, Module.ResolveType(t.MetadataToken));
}
public static IEnumerable<object[]> BadResolveTypes =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).GetMethod("ResolveType").MetadataToken },
};
[Theory]
[MemberData(nameof(BadResolveTypes))]
public void ResolveTypeFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveType(token);
});
}
public static IEnumerable<object[]> Methods =>
Module.GetMethods().Select(m => new object[] { m });
[Theory]
[MemberData(nameof(Methods))]
public void ResolveMethod(MethodInfo t)
{
Assert.Equal(t, Module.ResolveMethod(t.MetadataToken));
}
public static IEnumerable<object[]> BadResolveMethods =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).MetadataToken },
new object[] { typeof(ModuleTests).MetadataToken + 1000 },
};
[Theory]
[MemberData(nameof(BadResolveMethods))]
public void ResolveMethodFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveMethod(token);
});
}
public static IEnumerable<object[]> Fields =>
Module.GetFields().Select(f => new object[] { f });
[Theory]
[MemberData(nameof(Fields))]
public void ResolveField(FieldInfo t)
{
Assert.Equal(t, Module.ResolveField(t.MetadataToken));
}
public static IEnumerable<object[]> BadResolveFields =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).MetadataToken },
new object[] { typeof(ModuleTests).MetadataToken + 1000 },
};
[Theory]
[MemberData(nameof(BadResolveFields))]
public void ResolveFieldFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveField(token);
});
}
public static IEnumerable<object[]> BadResolveStrings =>
new[]
{
new object[] { 1234 },
new object[] { typeof(ModuleTests).MetadataToken },
new object[] { typeof(ModuleTests).MetadataToken + 1000 },
};
[Theory]
[MemberData(nameof(BadResolveStrings))]
public void ResolveStringFail(int token)
{
Assert.ThrowsAny<ArgumentException>(() =>
{
Module.ResolveString(token);
});
}
[Theory]
[MemberData(nameof(Types))]
[MemberData(nameof(Methods))]
[MemberData(nameof(Fields))]
public void ResolveMember(MemberInfo member)
{
Assert.Equal(member, Module.ResolveMember(member.MetadataToken));
}
[Fact]
public void ResolveMethodOfGenericClass()
{
Type t = typeof(Foo<>);
Module mod = t.Module;
MethodInfo method = t.GetMethod("Bar");
MethodBase actual = mod.ResolveMethod(method.MetadataToken);
Assert.Equal(method, actual);
}
[Fact]
public void GetTypes()
{
List<Type> types = TestModule.GetTypes().ToList();
Assert.Equal(1, types.Count);
Assert.Equal("System.Reflection.TestModule.Dummy, System.Reflection.TestModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", types[0].AssemblyQualifiedName);
}
}
public class Foo<T>
{
public void Bar(T t)
{
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using StructureMap;
using System.Text;
namespace Sep.Git.Tfs.Core
{
public class GitHelpers : IGitHelpers
{
private readonly TextWriter realStdout;
private readonly IContainer _container;
public GitHelpers(TextWriter stdout, IContainer container)
{
realStdout = stdout;
_container = container;
}
/// <summary>
/// Runs the given git command, and returns the contents of its STDOUT.
/// </summary>
public string Command(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadToEnd(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and returns the first line of its STDOUT.
/// </summary>
public string CommandOneline(params string[] command)
{
string retVal = null;
CommandOutputPipe(stdout => retVal = stdout.ReadLine(), command);
return retVal;
}
/// <summary>
/// Runs the given git command, and passes STDOUT through to the current process's STDOUT.
/// </summary>
public void CommandNoisy(params string[] command)
{
CommandOutputPipe(stdout => realStdout.Write(stdout.ReadToEnd()), command);
}
/// <summary>
/// Runs the given git command, and redirects STDOUT to the provided action.
/// </summary>
public void CommandOutputPipe(Action<TextReader> handleOutput, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
handleOutput(process.StandardOutput);
Close(process);
});
}
/// <summary>
/// Runs the given git command, and returns a reader for STDOUT. NOTE: The returned value MUST be disposed!
/// </summary>
public TextReader CommandOutputPipe(params string[] command)
{
AssertValidCommand(command);
var process = Start(command, RedirectStdout);
return new ProcessStdoutReader(this, process);
}
public class ProcessStdoutReader : TextReader
{
private readonly Process process;
private readonly GitHelpers helper;
public ProcessStdoutReader(GitHelpers helper, Process process)
{
this.helper = helper;
this.process = process;
}
public override void Close()
{
helper.Close(process);
}
public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
{
return process.StandardOutput.CreateObjRef(requestedType);
}
protected override void Dispose(bool disposing)
{
if(disposing && process != null)
{
Close();
}
base.Dispose(disposing);
}
public override bool Equals(object obj)
{
return process.StandardOutput.Equals(obj);
}
public override int GetHashCode()
{
return process.StandardOutput.GetHashCode();
}
public override object InitializeLifetimeService()
{
return process.StandardOutput.InitializeLifetimeService();
}
public override int Peek()
{
return process.StandardOutput.Peek();
}
public override int Read()
{
return process.StandardOutput.Read();
}
public override int Read(char[] buffer, int index, int count)
{
return process.StandardOutput.Read(buffer, index, count);
}
public override int ReadBlock(char[] buffer, int index, int count)
{
return process.StandardOutput.ReadBlock(buffer, index, count);
}
public override string ReadLine()
{
return process.StandardOutput.ReadLine();
}
public override string ReadToEnd()
{
return process.StandardOutput.ReadToEnd();
}
public override string ToString()
{
return process.StandardOutput.ToString();
}
}
public void CommandInputPipe(Action<TextWriter> action, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, RedirectStdin);
action(process.StandardInput.WithDefaultEncoding());
Close(process);
});
}
public void CommandInputOutputPipe(Action<TextWriter, TextReader> interact, params string[] command)
{
Time(command, () =>
{
AssertValidCommand(command);
var process = Start(command, Ext.And<ProcessStartInfo>(RedirectStdin, RedirectStdout));
var encoding = new UTF8Encoding(false);
interact(new StreamWriter(process.StandardInput.BaseStream, encoding), new StreamReader(process.StandardOutput.BaseStream, encoding));
Close(process);
});
}
private void Time(string[] command, Action action)
{
var start = DateTime.Now;
try
{
action();
}
finally
{
var end = DateTime.Now;
Trace.WriteLine(String.Format("[{0}] {1}", end - start, String.Join(" ", command)), "git command time");
}
}
private void Close(Process process)
{
// if caller doesn't read entire stdout to the EOF - it is possible that
// child process will hang waiting until there will be free space in stdout
// buffer to write the rest of the output. To prevent such situation we'll
// close stdout to indicate we're no more interested in it, thus allowing
// child process to proceed.
// See https://github.com/git-tfs/git-tfs/issues/121 for details.
if (process.StartInfo.RedirectStandardOutput)
process.StandardOutput.Close();
if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds))
throw new GitCommandException("Command did not terminate.", process);
if(process.ExitCode != 0)
throw new GitCommandException(string.Format("Command exited with error code: {0}", process.ExitCode), process);
}
private void RedirectStdout(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardOutput = true;
startInfo.StandardOutputEncoding = Encoding.Default;
}
private void RedirectStdin(ProcessStartInfo startInfo)
{
startInfo.RedirectStandardInput = true;
}
private Process Start(string[] command)
{
return Start(command, x => {});
}
protected virtual Process Start(string [] command, Action<ProcessStartInfo> initialize)
{
var startInfo = new ProcessStartInfo();
startInfo.FileName = "git";
startInfo.SetArguments(command);
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
initialize(startInfo);
Trace.WriteLine("Starting process: " + startInfo.FileName + " " + startInfo.Arguments, "git command");
var process = Process.Start(startInfo);
process.ErrorDataReceived += StdErrReceived;
process.BeginErrorReadLine();
return process;
}
private void StdErrReceived(object sender, DataReceivedEventArgs e)
{
if(e.Data != null && e.Data.Trim() != "")
{
Trace.WriteLine(e.Data.TrimEnd(), "git stderr");
}
}
/// <summary>
/// WrapGitCommandErrors the actions, and if there are any git exceptions, rethrow a new exception with the given message.
/// </summary>
/// <param name="exceptionMessage">A friendlier message to wrap the GitCommandException with. {0} is replaced with the command line and {1} is replaced with the exit code.</param>
/// <param name="action"></param>
public void WrapGitCommandErrors(string exceptionMessage, Action action)
{
try
{
action();
}
catch (GitCommandException e)
{
throw new Exception(String.Format(exceptionMessage, e.Process.StartInfo.FileName + " " + e.Process.StartInfo.Arguments, e.Process.ExitCode), e);
}
}
public IGitRepository MakeRepository(string dir)
{
return _container
.With("gitDir").EqualTo(dir)
.GetInstance<IGitRepository>();
}
private static readonly Regex ValidCommandName = new Regex("^[a-z0-9A-Z_-]+$");
private static void AssertValidCommand(string[] command)
{
if(command.Length < 1 || !ValidCommandName.IsMatch(command[0]))
throw new Exception("bad command: " + (command.Length == 0 ? "" : command[0]));
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Xml;
using System.Security;
namespace System.Runtime.Serialization
{
#if NET_NATIVE
public class DataMember
#else
internal class DataMember
#endif
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private CriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
public DataMember()
{
_helper = new CriticalHelper();
}
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal DataMember(MemberInfo memberInfo)
{
_helper = new CriticalHelper(memberInfo);
}
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal DataMember(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order)
{
_helper = new CriticalHelper(memberTypeContract, name, isNullable, isRequired, emitDefaultValue, order);
}
internal MemberInfo MemberInfo
{
[SecuritySafeCritical]
get
{ return _helper.MemberInfo; }
}
public string Name
{
[SecuritySafeCritical]
get
{ return _helper.Name; }
[SecurityCritical]
set
{ _helper.Name = value; }
}
public int Order
{
[SecuritySafeCritical]
get
{ return _helper.Order; }
[SecurityCritical]
set
{ _helper.Order = value; }
}
public bool IsRequired
{
[SecuritySafeCritical]
get
{ return _helper.IsRequired; }
[SecurityCritical]
set
{ _helper.IsRequired = value; }
}
public bool EmitDefaultValue
{
[SecuritySafeCritical]
get
{ return _helper.EmitDefaultValue; }
[SecurityCritical]
set
{ _helper.EmitDefaultValue = value; }
}
public bool IsNullable
{
[SecuritySafeCritical]
get
{ return _helper.IsNullable; }
[SecurityCritical]
set
{ _helper.IsNullable = value; }
}
public bool IsGetOnlyCollection
{
[SecuritySafeCritical]
get
{ return _helper.IsGetOnlyCollection; }
[SecurityCritical]
set
{ _helper.IsGetOnlyCollection = value; }
}
internal Type MemberType
{
[SecuritySafeCritical]
get
{ return _helper.MemberType; }
}
internal DataContract MemberTypeContract
{
[SecuritySafeCritical]
get
{ return _helper.MemberTypeContract; }
}
internal PrimitiveDataContract MemberPrimitiveContract
{
get
{
return _helper.MemberPrimitiveContract;
}
}
public bool HasConflictingNameAndType
{
[SecuritySafeCritical]
get
{ return _helper.HasConflictingNameAndType; }
[SecurityCritical]
set
{ _helper.HasConflictingNameAndType = value; }
}
internal DataMember ConflictingMember
{
[SecuritySafeCritical]
get
{ return _helper.ConflictingMember; }
[SecurityCritical]
set
{ _helper.ConflictingMember = value; }
}
private FastInvokerBuilder.Getter _getter;
internal FastInvokerBuilder.Getter Getter
{
get
{
if (_getter == null)
{
_getter = FastInvokerBuilder.CreateGetter(MemberInfo);
}
return _getter;
}
}
private FastInvokerBuilder.Setter _setter;
internal FastInvokerBuilder.Setter Setter
{
get
{
if (_setter == null)
{
_setter = FastInvokerBuilder.CreateSetter(MemberInfo);
}
return _setter;
}
}
[SecurityCritical]
/// <SecurityNote>
/// Critical
/// </SecurityNote>
private class CriticalHelper
{
private DataContract _memberTypeContract;
private string _name;
private int _order;
private bool _isRequired;
private bool _emitDefaultValue;
private bool _isNullable;
private bool _isGetOnlyCollection = false;
private MemberInfo _memberInfo;
private bool _hasConflictingNameAndType;
private DataMember _conflictingMember;
internal CriticalHelper()
{
_emitDefaultValue = Globals.DefaultEmitDefaultValue;
}
internal CriticalHelper(MemberInfo memberInfo)
{
_emitDefaultValue = Globals.DefaultEmitDefaultValue;
_memberInfo = memberInfo;
}
internal CriticalHelper(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order)
{
this.MemberTypeContract = memberTypeContract;
this.Name = name;
this.IsNullable = isNullable;
this.IsRequired = isRequired;
this.EmitDefaultValue = emitDefaultValue;
this.Order = order;
}
internal MemberInfo MemberInfo
{
get { return _memberInfo; }
}
internal string Name
{
get { return _name; }
set { _name = value; }
}
internal int Order
{
get { return _order; }
set { _order = value; }
}
internal bool IsRequired
{
get { return _isRequired; }
set { _isRequired = value; }
}
internal bool EmitDefaultValue
{
get { return _emitDefaultValue; }
set { _emitDefaultValue = value; }
}
internal bool IsNullable
{
get { return _isNullable; }
set { _isNullable = value; }
}
internal bool IsGetOnlyCollection
{
get { return _isGetOnlyCollection; }
set { _isGetOnlyCollection = value; }
}
private Type _memberType;
internal Type MemberType
{
get
{
if (_memberType == null)
{
FieldInfo field = MemberInfo as FieldInfo;
if (field != null)
_memberType = field.FieldType;
else
_memberType = ((PropertyInfo)MemberInfo).PropertyType;
}
return _memberType;
}
}
internal DataContract MemberTypeContract
{
get
{
if (_memberTypeContract == null)
{
if (MemberInfo != null)
{
if (this.IsGetOnlyCollection)
{
_memberTypeContract = DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(MemberType.TypeHandle), MemberType.TypeHandle, MemberType, SerializationMode.SharedContract);
}
else
{
_memberTypeContract = DataContract.GetDataContract(MemberType);
}
}
}
return _memberTypeContract;
}
set
{
_memberTypeContract = value;
}
}
internal bool HasConflictingNameAndType
{
get { return _hasConflictingNameAndType; }
set { _hasConflictingNameAndType = value; }
}
internal DataMember ConflictingMember
{
get { return _conflictingMember; }
set { _conflictingMember = value; }
}
private PrimitiveDataContract _memberPrimitiveContract = PrimitiveDataContract.NullContract;
internal PrimitiveDataContract MemberPrimitiveContract
{
get
{
if (_memberPrimitiveContract == PrimitiveDataContract.NullContract)
{
_memberPrimitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(MemberType);
}
return _memberPrimitiveContract;
}
}
}
/// <SecurityNote>
/// Review - checks member visibility to calculate if access to it requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForGet()
{
MemberInfo memberInfo = MemberInfo;
FieldInfo field = memberInfo as FieldInfo;
if (field != null)
{
return DataContract.FieldRequiresMemberAccess(field);
}
else
{
PropertyInfo property = (PropertyInfo)memberInfo;
MethodInfo getMethod = property.GetMethod;
if (getMethod != null)
{
return DataContract.MethodRequiresMemberAccess(getMethod) || !DataContract.IsTypeVisible(property.PropertyType);
}
}
return false;
}
/// <SecurityNote>
/// Review - checks member visibility to calculate if access to it requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForSet()
{
MemberInfo memberInfo = MemberInfo;
FieldInfo field = memberInfo as FieldInfo;
if (field != null)
{
return DataContract.FieldRequiresMemberAccess(field);
}
else
{
PropertyInfo property = (PropertyInfo)memberInfo;
MethodInfo setMethod = property.SetMethod;
if (setMethod != null)
{
return DataContract.MethodRequiresMemberAccess(setMethod) || !DataContract.IsTypeVisible(property.PropertyType);
}
}
return false;
}
}
}
| |
// 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 gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedKeywordPlanCampaignKeywordServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetKeywordPlanCampaignKeywordRequestObject()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
GetKeywordPlanCampaignKeywordRequest request = new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
};
gagvr::KeywordPlanCampaignKeyword expectedResponse = new gagvr::KeywordPlanCampaignKeyword
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
MatchType = gagve::KeywordMatchTypeEnum.Types.KeywordMatchType.Unspecified,
KeywordPlanCampaignAsKeywordPlanCampaignName = gagvr::KeywordPlanCampaignName.FromCustomerKeywordPlanCampaign("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_ID]"),
Id = -6774108720365892680L,
Text = "textec51b21c",
Negative = false,
};
mockGrpcClient.Setup(x => x.GetKeywordPlanCampaignKeyword(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
gagvr::KeywordPlanCampaignKeyword response = client.GetKeywordPlanCampaignKeyword(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetKeywordPlanCampaignKeywordRequestObjectAsync()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
GetKeywordPlanCampaignKeywordRequest request = new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
};
gagvr::KeywordPlanCampaignKeyword expectedResponse = new gagvr::KeywordPlanCampaignKeyword
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
MatchType = gagve::KeywordMatchTypeEnum.Types.KeywordMatchType.Unspecified,
KeywordPlanCampaignAsKeywordPlanCampaignName = gagvr::KeywordPlanCampaignName.FromCustomerKeywordPlanCampaign("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_ID]"),
Id = -6774108720365892680L,
Text = "textec51b21c",
Negative = false,
};
mockGrpcClient.Setup(x => x.GetKeywordPlanCampaignKeywordAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::KeywordPlanCampaignKeyword>(stt::Task.FromResult(expectedResponse), null, null, null, null));
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
gagvr::KeywordPlanCampaignKeyword responseCallSettings = await client.GetKeywordPlanCampaignKeywordAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::KeywordPlanCampaignKeyword responseCancellationToken = await client.GetKeywordPlanCampaignKeywordAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetKeywordPlanCampaignKeyword()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
GetKeywordPlanCampaignKeywordRequest request = new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
};
gagvr::KeywordPlanCampaignKeyword expectedResponse = new gagvr::KeywordPlanCampaignKeyword
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
MatchType = gagve::KeywordMatchTypeEnum.Types.KeywordMatchType.Unspecified,
KeywordPlanCampaignAsKeywordPlanCampaignName = gagvr::KeywordPlanCampaignName.FromCustomerKeywordPlanCampaign("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_ID]"),
Id = -6774108720365892680L,
Text = "textec51b21c",
Negative = false,
};
mockGrpcClient.Setup(x => x.GetKeywordPlanCampaignKeyword(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
gagvr::KeywordPlanCampaignKeyword response = client.GetKeywordPlanCampaignKeyword(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetKeywordPlanCampaignKeywordAsync()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
GetKeywordPlanCampaignKeywordRequest request = new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
};
gagvr::KeywordPlanCampaignKeyword expectedResponse = new gagvr::KeywordPlanCampaignKeyword
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
MatchType = gagve::KeywordMatchTypeEnum.Types.KeywordMatchType.Unspecified,
KeywordPlanCampaignAsKeywordPlanCampaignName = gagvr::KeywordPlanCampaignName.FromCustomerKeywordPlanCampaign("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_ID]"),
Id = -6774108720365892680L,
Text = "textec51b21c",
Negative = false,
};
mockGrpcClient.Setup(x => x.GetKeywordPlanCampaignKeywordAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::KeywordPlanCampaignKeyword>(stt::Task.FromResult(expectedResponse), null, null, null, null));
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
gagvr::KeywordPlanCampaignKeyword responseCallSettings = await client.GetKeywordPlanCampaignKeywordAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::KeywordPlanCampaignKeyword responseCancellationToken = await client.GetKeywordPlanCampaignKeywordAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetKeywordPlanCampaignKeywordResourceNames()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
GetKeywordPlanCampaignKeywordRequest request = new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
};
gagvr::KeywordPlanCampaignKeyword expectedResponse = new gagvr::KeywordPlanCampaignKeyword
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
MatchType = gagve::KeywordMatchTypeEnum.Types.KeywordMatchType.Unspecified,
KeywordPlanCampaignAsKeywordPlanCampaignName = gagvr::KeywordPlanCampaignName.FromCustomerKeywordPlanCampaign("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_ID]"),
Id = -6774108720365892680L,
Text = "textec51b21c",
Negative = false,
};
mockGrpcClient.Setup(x => x.GetKeywordPlanCampaignKeyword(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
gagvr::KeywordPlanCampaignKeyword response = client.GetKeywordPlanCampaignKeyword(request.ResourceNameAsKeywordPlanCampaignKeywordName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetKeywordPlanCampaignKeywordResourceNamesAsync()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
GetKeywordPlanCampaignKeywordRequest request = new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
};
gagvr::KeywordPlanCampaignKeyword expectedResponse = new gagvr::KeywordPlanCampaignKeyword
{
ResourceNameAsKeywordPlanCampaignKeywordName = gagvr::KeywordPlanCampaignKeywordName.FromCustomerKeywordPlanCampaignKeyword("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]"),
MatchType = gagve::KeywordMatchTypeEnum.Types.KeywordMatchType.Unspecified,
KeywordPlanCampaignAsKeywordPlanCampaignName = gagvr::KeywordPlanCampaignName.FromCustomerKeywordPlanCampaign("[CUSTOMER_ID]", "[KEYWORD_PLAN_CAMPAIGN_ID]"),
Id = -6774108720365892680L,
Text = "textec51b21c",
Negative = false,
};
mockGrpcClient.Setup(x => x.GetKeywordPlanCampaignKeywordAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::KeywordPlanCampaignKeyword>(stt::Task.FromResult(expectedResponse), null, null, null, null));
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
gagvr::KeywordPlanCampaignKeyword responseCallSettings = await client.GetKeywordPlanCampaignKeywordAsync(request.ResourceNameAsKeywordPlanCampaignKeywordName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::KeywordPlanCampaignKeyword responseCancellationToken = await client.GetKeywordPlanCampaignKeywordAsync(request.ResourceNameAsKeywordPlanCampaignKeywordName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateKeywordPlanCampaignKeywordsRequestObject()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
MutateKeywordPlanCampaignKeywordsRequest request = new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new KeywordPlanCampaignKeywordOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateKeywordPlanCampaignKeywordsResponse expectedResponse = new MutateKeywordPlanCampaignKeywordsResponse
{
Results =
{
new MutateKeywordPlanCampaignKeywordResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateKeywordPlanCampaignKeywords(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
MutateKeywordPlanCampaignKeywordsResponse response = client.MutateKeywordPlanCampaignKeywords(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateKeywordPlanCampaignKeywordsRequestObjectAsync()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
MutateKeywordPlanCampaignKeywordsRequest request = new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new KeywordPlanCampaignKeywordOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateKeywordPlanCampaignKeywordsResponse expectedResponse = new MutateKeywordPlanCampaignKeywordsResponse
{
Results =
{
new MutateKeywordPlanCampaignKeywordResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateKeywordPlanCampaignKeywordsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateKeywordPlanCampaignKeywordsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
MutateKeywordPlanCampaignKeywordsResponse responseCallSettings = await client.MutateKeywordPlanCampaignKeywordsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateKeywordPlanCampaignKeywordsResponse responseCancellationToken = await client.MutateKeywordPlanCampaignKeywordsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateKeywordPlanCampaignKeywords()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
MutateKeywordPlanCampaignKeywordsRequest request = new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new KeywordPlanCampaignKeywordOperation(),
},
};
MutateKeywordPlanCampaignKeywordsResponse expectedResponse = new MutateKeywordPlanCampaignKeywordsResponse
{
Results =
{
new MutateKeywordPlanCampaignKeywordResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateKeywordPlanCampaignKeywords(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
MutateKeywordPlanCampaignKeywordsResponse response = client.MutateKeywordPlanCampaignKeywords(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateKeywordPlanCampaignKeywordsAsync()
{
moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient> mockGrpcClient = new moq::Mock<KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient>(moq::MockBehavior.Strict);
MutateKeywordPlanCampaignKeywordsRequest request = new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new KeywordPlanCampaignKeywordOperation(),
},
};
MutateKeywordPlanCampaignKeywordsResponse expectedResponse = new MutateKeywordPlanCampaignKeywordsResponse
{
Results =
{
new MutateKeywordPlanCampaignKeywordResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateKeywordPlanCampaignKeywordsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateKeywordPlanCampaignKeywordsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
KeywordPlanCampaignKeywordServiceClient client = new KeywordPlanCampaignKeywordServiceClientImpl(mockGrpcClient.Object, null);
MutateKeywordPlanCampaignKeywordsResponse responseCallSettings = await client.MutateKeywordPlanCampaignKeywordsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateKeywordPlanCampaignKeywordsResponse responseCancellationToken = await client.MutateKeywordPlanCampaignKeywordsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if UNITY_IOS
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
namespace GoogleMobileAds.iOS
{
public class InterstitialClient : IInterstitialClient, IDisposable
{
private IntPtr interstitialPtr;
private IntPtr interstitialClientPtr;
#region Interstitial callback types
internal delegate void GADUInterstitialDidReceiveAdCallback(IntPtr interstitialClient);
internal delegate void GADUInterstitialDidFailToReceiveAdWithErrorCallback(
IntPtr interstitialClient, string error);
internal delegate void GADUInterstitialWillPresentScreenCallback(IntPtr interstitialClient);
internal delegate void GADUInterstitialDidDismissScreenCallback(IntPtr interstitialClient);
internal delegate void GADUInterstitialWillLeaveApplicationCallback(
IntPtr interstitialClient);
#endregion
public event EventHandler<EventArgs> OnAdLoaded;
public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;
public event EventHandler<EventArgs> OnAdOpening;
public event EventHandler<EventArgs> OnAdClosed;
public event EventHandler<EventArgs> OnAdLeavingApplication;
// This property should be used when setting the interstitialPtr.
private IntPtr InterstitialPtr
{
get
{
return this.interstitialPtr;
}
set
{
Externs.GADURelease(this.interstitialPtr);
this.interstitialPtr = value;
}
}
#region IInterstitialClient implementation
// Creates an interstitial ad.
public void CreateInterstitialAd(string adUnitId)
{
this.interstitialClientPtr = (IntPtr)GCHandle.Alloc(this);
this.InterstitialPtr = Externs.GADUCreateInterstitial(this.interstitialClientPtr, adUnitId);
Externs.GADUSetInterstitialCallbacks(
this.InterstitialPtr,
InterstitialDidReceiveAdCallback,
InterstitialDidFailToReceiveAdWithErrorCallback,
InterstitialWillPresentScreenCallback,
InterstitialDidDismissScreenCallback,
InterstitialWillLeaveApplicationCallback);
}
// Loads an ad.
public void LoadAd(AdRequest request)
{
IntPtr requestPtr = Utils.BuildAdRequest(request);
Externs.GADURequestInterstitial(this.InterstitialPtr, requestPtr);
Externs.GADURelease(requestPtr);
}
// Checks if interstitial has loaded.
public bool IsLoaded()
{
return Externs.GADUInterstitialReady(this.InterstitialPtr);
}
// Presents the interstitial ad on the screen
public void ShowInterstitial()
{
Externs.GADUShowInterstitial(this.InterstitialPtr);
}
// Destroys the interstitial ad.
public void DestroyInterstitial()
{
this.InterstitialPtr = IntPtr.Zero;
}
// Returns the mediation adapter class name.
public string MediationAdapterClassName()
{
return Externs.GADUMediationAdapterClassNameForInterstitial(this.InterstitialPtr);
}
public void Dispose()
{
this.DestroyInterstitial();
((GCHandle)this.interstitialClientPtr).Free();
}
~InterstitialClient()
{
this.Dispose();
}
#endregion
#region Interstitial callback methods
[MonoPInvokeCallback(typeof(GADUInterstitialDidReceiveAdCallback))]
private static void InterstitialDidReceiveAdCallback(IntPtr interstitialClient)
{
InterstitialClient client = IntPtrToInterstitialClient(interstitialClient);
if (client.OnAdLoaded != null)
{
client.OnAdLoaded(client, EventArgs.Empty);
}
}
[MonoPInvokeCallback(typeof(GADUInterstitialDidFailToReceiveAdWithErrorCallback))]
private static void InterstitialDidFailToReceiveAdWithErrorCallback(
IntPtr interstitialClient, string error)
{
InterstitialClient client = IntPtrToInterstitialClient(interstitialClient);
if (client.OnAdFailedToLoad != null)
{
AdFailedToLoadEventArgs args = new AdFailedToLoadEventArgs()
{
Message = error
};
client.OnAdFailedToLoad(client, args);
}
}
[MonoPInvokeCallback(typeof(GADUInterstitialWillPresentScreenCallback))]
private static void InterstitialWillPresentScreenCallback(IntPtr interstitialClient)
{
InterstitialClient client = IntPtrToInterstitialClient(interstitialClient);
if (client.OnAdOpening != null)
{
client.OnAdOpening(client, EventArgs.Empty);
}
}
[MonoPInvokeCallback(typeof(GADUInterstitialDidDismissScreenCallback))]
private static void InterstitialDidDismissScreenCallback(IntPtr interstitialClient)
{
InterstitialClient client = IntPtrToInterstitialClient(interstitialClient);
if (client.OnAdClosed != null)
{
client.OnAdClosed(client, EventArgs.Empty);
}
}
[MonoPInvokeCallback(typeof(GADUInterstitialWillLeaveApplicationCallback))]
private static void InterstitialWillLeaveApplicationCallback(IntPtr interstitialClient)
{
InterstitialClient client = IntPtrToInterstitialClient(interstitialClient);
if (client.OnAdLeavingApplication != null)
{
client.OnAdLeavingApplication(client, EventArgs.Empty);
}
}
private static InterstitialClient IntPtrToInterstitialClient(IntPtr interstitialClient)
{
GCHandle handle = (GCHandle)interstitialClient;
return handle.Target as InterstitialClient;
}
#endregion
}
}
#endif
| |
//------------------------------------------------------------------------------
// <copyright file="ToolStripControlHost.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms.Layout;
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost"]/*' />
/// <devdoc>
/// ToolStripItem that can host Controls.
/// </devdoc>
public class ToolStripControlHost : ToolStripItem {
private Control control;
private int suspendSyncSizeCount = 0;
private ContentAlignment controlAlign = ContentAlignment.MiddleCenter;
private bool inSetVisibleCore = false;
internal static readonly object EventGotFocus = new object();
internal static readonly object EventLostFocus = new object();
internal static readonly object EventKeyDown = new object();
internal static readonly object EventKeyPress = new object();
internal static readonly object EventKeyUp = new object();
internal static readonly object EventEnter = new object();
internal static readonly object EventLeave = new object();
internal static readonly object EventValidated = new object();
internal static readonly object EventValidating = new object();
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.ToolStripControlHost"]/*' />
/// <devdoc>
/// Constructs a ToolStripControlHost
/// </devdoc>
public ToolStripControlHost(Control c) {
if (c == null) {
throw new ArgumentNullException("c", SR.ControlCannotBeNull);
}
control = c;
SyncControlParent();
c.Visible = true;
SetBounds(c.Bounds);
// now that we have a control set in, update the bounds.
Rectangle bounds = this.Bounds;
CommonProperties.UpdateSpecifiedBounds(c, bounds.X, bounds.Y, bounds.Width, bounds.Height);
OnSubscribeControlEvents(c);
}
public ToolStripControlHost(Control c, string name) : this (c){
this.Name = name;
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.BackColor"]/*' />
public override Color BackColor {
get {
return Control.BackColor;
}
set {
Control.BackColor = value;
}
}
/// <include file='doc\ToolStripItem.uex' path='docs/doc[@for="ToolStripItem.Image"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the image that is displayed on a <see cref='System.Windows.Forms.Label'/>.
/// </para>
/// </devdoc>
[
Localizable(true),
SRCategory(SR.CatAppearance),
SRDescription(SR.ToolStripItemImageDescr),
DefaultValue(null)
]
public override Image BackgroundImage {
get {
return Control.BackgroundImage;
}
set {
Control.BackgroundImage = value;
}
}
/// <include file='doc\ToolStripItem.uex' path='docs/doc[@for="ToolStripItem.BackgroundImageLayout"]/*' />
[
SRCategory(SR.CatAppearance),
DefaultValue(ImageLayout.Tile),
Localizable(true),
SRDescription(SR.ControlBackgroundImageLayoutDescr)
]
public override ImageLayout BackgroundImageLayout {
get {
return Control.BackgroundImageLayout;
}
set {
Control.BackgroundImageLayout = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.CanSelect"]/*' />
/// <devdoc>
/// Overriden to return value from Control.CanSelect.
/// </devdoc>
public override bool CanSelect {
get {
if (control != null) {
return (DesignMode || this.Control.CanSelect);
}
return false;
}
}
[
SRCategory(SR.CatFocus),
DefaultValue(true),
SRDescription(SR.ControlCausesValidationDescr)
]
public bool CausesValidation {
get { return Control.CausesValidation; }
set { Control.CausesValidation = value; }
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.ControlAlign"]/*' />
[DefaultValue(ContentAlignment.MiddleCenter), Browsable(false)]
public ContentAlignment ControlAlign {
get { return controlAlign; }
set {
if (!WindowsFormsUtils.EnumValidator.IsValidContentAlignment(value)) {
throw new InvalidEnumArgumentException("value", (int)value, typeof(ContentAlignment));
}
if (controlAlign != value) {
controlAlign = value;
OnBoundsChanged();
}
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Control"]/*' />
/// <devdoc>
/// The control that this item is hosting.
/// </devdoc>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Control Control {
get {
return control;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.DefaultSize"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Size DefaultSize {
get {
if (Control != null) {
// When you create the control - it sets up its size as its default size.
// Since the property is protected we dont know for sure, but this is a pretty good guess.
return Control.Size;
}
return base.DefaultSize;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.DisplayStyle"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new ToolStripItemDisplayStyle DisplayStyle {
get {
return base.DisplayStyle;
}
set {
base.DisplayStyle = value;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler DisplayStyleChanged {
add {
Events.AddHandler(EventDisplayStyleChanged, value);
}
remove {
Events.RemoveHandler(EventDisplayStyleChanged, value);
}
}
/// <devdoc>
// For control hosts, this property has no effect
/// as they get their own clicks. Use ControlStyles.StandardClick
/// instead.
/// </devdoc>
[DefaultValue(false), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new bool DoubleClickEnabled {
get {
return base.DoubleClickEnabled;
}
set {
base.DoubleClickEnabled = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Font"]/*' />
public override Font Font {
get {
return Control.Font;
}
set {
Control.Font = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Enabled"]/*' />
public override bool Enabled {
get {
return Control.Enabled;
}
set {
Control.Enabled = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.GotFocus"]/*' />
[SRCategory(SR.CatFocus), SRDescription(SR.ControlOnEnterDescr)]
public event EventHandler Enter {
add {
Events.AddHandler(EventEnter, value);
}
remove {
Events.RemoveHandler(EventEnter, value);
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Focused"]/*' />
[
Browsable(false), EditorBrowsable(EditorBrowsableState.Always)
]
public virtual bool Focused {
get {
return Control.Focused;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.ForeColor"]/*' />
public override Color ForeColor {
get {
return Control.ForeColor;
}
set {
Control.ForeColor = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.GotFocus"]/*' />
[
SRCategory(SR.CatFocus),
SRDescription(SR.ToolStripItemOnGotFocusDescr),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced)
]
public event EventHandler GotFocus {
add {
Events.AddHandler(EventGotFocus, value);
}
remove {
Events.RemoveHandler(EventGotFocus, value);
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override Image Image {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
return base.Image;
}
set {
base.Image = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new ToolStripItemImageScaling ImageScaling {
get {
return base.ImageScaling;
}
set {
base.ImageScaling = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new Color ImageTransparentColor {
get {
return base.ImageTransparentColor;
}
set {
base.ImageTransparentColor = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new ContentAlignment ImageAlign {
get {
return base.ImageAlign;
}
set {
base.ImageAlign = value;
}
}
[SRCategory(SR.CatFocus), SRDescription(SR.ControlOnLeaveDescr)]
public event EventHandler Leave {
add {
Events.AddHandler(EventLeave, value);
}
remove {
Events.RemoveHandler(EventLeave, value);
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.LostFocus"]/*' />
/// <devdoc>
/// <para>Occurs when the control loses focus.</para>
/// </devdoc>
[
SRCategory(SR.CatFocus),
SRDescription(SR.ToolStripItemOnLostFocusDescr),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Advanced)
]
public event EventHandler LostFocus {
add {
Events.AddHandler(EventLostFocus, value);
}
remove {
Events.RemoveHandler(EventLostFocus, value);
}
}
/// <include file='doc\WinBarControlHost.uex' path='docs/doc[@for="ToolStripControlHost.KeyDown"]/*' />
/// <devdoc>
/// <para>Occurs when a key is pressed down while the control has focus.</para>
/// </devdoc>
[SRCategory(SR.CatKey), SRDescription(SR.ControlOnKeyDownDescr)]
public event KeyEventHandler KeyDown {
add {
Events.AddHandler(EventKeyDown, value);
}
remove {
Events.RemoveHandler(EventKeyDown, value);
}
}
/// <include file='doc\WinBarControlHost.uex' path='docs/doc[@for="ToolStripControlHost.KeyPress"]/*' />
/// <devdoc>
/// <para> Occurs when a key is pressed while the control has focus.</para>
/// </devdoc>
[SRCategory(SR.CatKey), SRDescription(SR.ControlOnKeyPressDescr)]
public event KeyPressEventHandler KeyPress {
add {
Events.AddHandler(EventKeyPress, value);
}
remove {
Events.RemoveHandler(EventKeyPress, value);
}
}
/// <include file='doc\WinBarControlHost.uex' path='docs/doc[@for="ToolStripControlHost.KeyUp"]/*' />
/// <devdoc>
/// <para> Occurs when a key is released while the control has focus.</para>
/// </devdoc>
[SRCategory(SR.CatKey), SRDescription(SR.ControlOnKeyUpDescr)]
public event KeyEventHandler KeyUp {
add {
Events.AddHandler(EventKeyUp, value);
}
remove {
Events.RemoveHandler(EventKeyUp, value);
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.RightToLeft"]/*' />
/// <devdoc>
/// This is used for international applications where the language
/// is written from RightToLeft. When this property is true,
/// control placement and text will be from right to left.
/// </devdoc>
public override RightToLeft RightToLeft {
get {
if (control != null) {
return control.RightToLeft;
}
return base.RightToLeft;
}
set {
if (control != null) {
control.RightToLeft = value;
}
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new bool RightToLeftAutoMirrorImage {
get {
return base.RightToLeftAutoMirrorImage;
}
set {
base.RightToLeftAutoMirrorImage = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Selected"]/*' />
public override bool Selected {
get {
if (Control != null)
{
return Control.Focused;
}
return false;
}
}
public override Size Size {
get {
return base.Size;
}
set {
Rectangle specifiedBounds = Rectangle.Empty;
if (control != null) {
// we dont normally update the specified bounds, but if someone explicitly sets
// the size we should.
specifiedBounds = control.Bounds;
specifiedBounds.Size = value;
CommonProperties.UpdateSpecifiedBounds(control, specifiedBounds.X, specifiedBounds.Y, specifiedBounds.Width, specifiedBounds.Height);
}
base.Size = value;
if (control != null) {
// checking again in case the control has adjusted the size.
Rectangle bounds = control.Bounds;
if (bounds != specifiedBounds) {
CommonProperties.UpdateSpecifiedBounds(control, bounds.X, bounds.Y, bounds.Width, bounds.Height);
}
}
}
}
/// <devdoc>
/// Overriden to set the Site for the control hosted. This is set at DesignTime when the component is added to the Container.
/// Refer to VsWhidbey : 390573.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public override ISite Site {
get {
return base.Site;
}
set {
base.Site = value;
if (value != null)
{
Control.Site = new StubSite(Control, this);
}
else
{
Control.Site = null;
}
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Text"]/*' />
/// <devdoc>
/// Overriden to modify hosted control's text.
/// </devdoc>
[DefaultValue("")]
public override string Text {
get {
return Control.Text;
}
set {
Control.Text = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.TextAlign"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new ContentAlignment TextAlign {
get {
return base.TextAlign;
}
set {
base.TextAlign = value;
}
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DefaultValue(ToolStripTextDirection.Horizontal)]
public override ToolStripTextDirection TextDirection {
get {
return base.TextDirection;
}
set {
base.TextDirection = value;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.TextImageRelation"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new TextImageRelation TextImageRelation {
get {
return base.TextImageRelation;
}
set {
base.TextImageRelation = value;
}
}
[SRCategory(SR.CatFocus), SRDescription(SR.ControlOnValidatingDescr)]
public event CancelEventHandler Validating {
add {
Events.AddHandler(EventValidating, value);
}
remove {
Events.RemoveHandler(EventValidating, value);
}
}
[SRCategory(SR.CatFocus), SRDescription(SR.ControlOnValidatedDescr)]
public event EventHandler Validated {
add {
Events.AddHandler(EventValidated, value);
}
remove {
Events.RemoveHandler(EventValidated, value);
}
}
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override AccessibleObject CreateAccessibilityInstance() {
return Control.AccessibilityObject;
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Dispose"]/*' />
/// <devdoc>
/// Cleans up and destroys the hosted control.
/// </devdoc>
protected override void Dispose(bool disposing) {
// Call base first so other things stop trying to talk to the control. This will
// unparent the host item which will cause a SyncControlParent, so the control
// will be correctly unparented before being disposed.
base.Dispose (disposing);
if (disposing && Control != null) {
OnUnsubscribeControlEvents(Control);
// we only call control.Dispose if we are NOT being disposed in the finalizer.
Control.Dispose();
control = null;
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.Focus"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void Focus()
{
Control.Focus();
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.GetPreferredSize"]/*' />
public override Size GetPreferredSize(Size constrainingSize) {
if (control != null) {
return Control.GetPreferredSize(constrainingSize - Padding.Size) + Padding.Size;
}
return base.GetPreferredSize(constrainingSize);
}
///
/// Handle* wrappers:
/// We [....] the event from the hosted control and call resurface it on ToolStripItem.
///
private void HandleClick(object sender, System.EventArgs e) {
OnClick(e);
}
private void HandleBackColorChanged(object sender, System.EventArgs e) {
OnBackColorChanged(e);
}
private void HandleDoubleClick(object sender, System.EventArgs e) {
OnDoubleClick(e);
}
private void HandleDragDrop(object sender, DragEventArgs e) {
OnDragDrop(e);
}
private void HandleDragEnter(object sender, DragEventArgs e) {
OnDragEnter(e);
}
private void HandleDragLeave(object sender, EventArgs e) {
OnDragLeave(e);
}
private void HandleDragOver(object sender, DragEventArgs e) {
OnDragOver(e);
}
private void HandleEnter(object sender, System.EventArgs e) {
OnEnter(e);
}
private void HandleEnabledChanged(object sender, System.EventArgs e) {
OnEnabledChanged(e);
}
private void HandleForeColorChanged(object sender, System.EventArgs e) {
OnForeColorChanged(e);
}
private void HandleGiveFeedback(object sender, GiveFeedbackEventArgs e) {
OnGiveFeedback(e);
}
private void HandleGotFocus(object sender, EventArgs e) {
OnGotFocus(e);
}
private void HandleLocationChanged(object sender, EventArgs e) {
OnLocationChanged(e);
}
private void HandleLostFocus(object sender, EventArgs e) {
OnLostFocus(e);
}
private void HandleKeyDown(object sender, KeyEventArgs e) {
OnKeyDown(e);
}
private void HandleKeyPress(object sender, KeyPressEventArgs e) {
OnKeyPress(e);
}
private void HandleKeyUp(object sender, KeyEventArgs e) {
OnKeyUp(e);
}
private void HandleLeave(object sender, System.EventArgs e) {
OnLeave(e);
}
private void HandleMouseDown(object sender, MouseEventArgs e) {
OnMouseDown(e);
RaiseMouseEvent(ToolStripItem.EventMouseDown, e);
}
private void HandleMouseEnter(object sender, EventArgs e) {
OnMouseEnter(e);
RaiseEvent(ToolStripItem.EventMouseEnter, e);
}
private void HandleMouseLeave(object sender, EventArgs e) {
OnMouseLeave(e);
RaiseEvent(ToolStripItem.EventMouseLeave, e);
}
private void HandleMouseHover(object sender, EventArgs e) {
OnMouseHover(e);
RaiseEvent(ToolStripItem.EventMouseHover, e);
}
private void HandleMouseMove(object sender, MouseEventArgs e) {
OnMouseMove(e);
RaiseMouseEvent(ToolStripItem.EventMouseMove, e);
}
private void HandleMouseUp(object sender, MouseEventArgs e) {
OnMouseUp(e);
RaiseMouseEvent(ToolStripItem.EventMouseUp, e);
}
private void HandlePaint(object sender, PaintEventArgs e) {
OnPaint(e);
RaisePaintEvent(ToolStripItem.EventPaint, e);
}
private void HandleQueryAccessibilityHelp(object sender, QueryAccessibilityHelpEventArgs e) {
QueryAccessibilityHelpEventHandler handler = (QueryAccessibilityHelpEventHandler)Events[ToolStripItem.EventQueryAccessibilityHelp];
if (handler != null) handler(this, e);
}
private void HandleQueryContinueDrag(object sender, QueryContinueDragEventArgs e) {
OnQueryContinueDrag(e);
}
private void HandleRightToLeftChanged(object sender, EventArgs e) {
OnRightToLeftChanged(e);
}
private void HandleResize(object sender, EventArgs e) {
if (suspendSyncSizeCount == 0) {
OnHostedControlResize(e);
}
}
private void HandleTextChanged(object sender, EventArgs e) {
OnTextChanged(e);
}
private void HandleControlVisibleChanged(object sender, EventArgs e) {
// check the STATE_VISIBLE flag rather than using Control.Visible.
// if we check while it's unparented it will return visible false.
// the easiest way to do this is to use ParticipatesInLayout.
bool controlVisibleStateFlag = ((IArrangedElement)Control).ParticipatesInLayout;
bool itemVisibleStateFlag = ((IArrangedElement)(this)).ParticipatesInLayout;
if (itemVisibleStateFlag != controlVisibleStateFlag) {
this.Visible = Control.Visible;
// this should fire the OnVisibleChanged and raise events appropriately.
};
}
private void HandleValidating(object sender, CancelEventArgs e) {
OnValidating(e);
}
private void HandleValidated(object sender, System.EventArgs e) {
OnValidated(e);
}
internal override void OnAccessibleDescriptionChanged(EventArgs e) {
Control.AccessibleDescription = AccessibleDescription;
}
internal override void OnAccessibleNameChanged(EventArgs e) {
Control.AccessibleName = AccessibleName;
}
internal override void OnAccessibleDefaultActionDescriptionChanged(EventArgs e) {
Control.AccessibleDefaultActionDescription = AccessibleDefaultActionDescription;
}
internal override void OnAccessibleRoleChanged(EventArgs e) {
Control.AccessibleRole = AccessibleRole;
}
protected virtual void OnEnter(EventArgs e) {
RaiseEvent(EventEnter, e);
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnGotFocus"]/*' />
/// <devdoc>
/// called when the control has lost focus
/// </devdoc>
protected virtual void OnGotFocus(EventArgs e) {
RaiseEvent(EventGotFocus, e);
}
protected virtual void OnLeave(EventArgs e) {
RaiseEvent(EventLeave, e);
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnLostFocus"]/*' />
/// <devdoc>
/// called when the control has lost focus
/// </devdoc >
protected virtual void OnLostFocus(EventArgs e) {
RaiseEvent(EventLostFocus, e);
}
/// <include file='doc\WinBarControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnKeyDown"]/*' />
protected virtual void OnKeyDown(KeyEventArgs e) {
RaiseKeyEvent(EventKeyDown, e);
}
/// <include file='doc\WinBarControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnKeyPress"]/*' />
protected virtual void OnKeyPress(KeyPressEventArgs e) {
RaiseKeyPressEvent(EventKeyPress, e);
}
/// <include file='doc\WinBarControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnKeyUp"]/*' />
protected virtual void OnKeyUp(KeyEventArgs e) {
RaiseKeyEvent(EventKeyUp, e);
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnBoundsChanged"]/*' />
/// <devdoc>
/// Called when the items bounds are changed. Here, we update the Control's bounds.
/// </devdoc>
protected override void OnBoundsChanged() {
if (control != null) {
SuspendSizeSync();
IArrangedElement element = control as IArrangedElement;
if (element == null) {
Debug.Fail("why are we here? control should not be null");
return;
}
Size size = LayoutUtils.DeflateRect(this.Bounds, this.Padding).Size;
Rectangle bounds = LayoutUtils.Align(size, this.Bounds, ControlAlign);
// use BoundsSpecified.None so we dont deal w/specified bounds - this way we can tell what someone has set the size to.
element.SetBounds(bounds, BoundsSpecified.None);
// sometimes a control can ignore the size passed in, use the adjustment
// to re-align.
if (bounds != control.Bounds) {
bounds = LayoutUtils.Align(control.Size, this.Bounds, ControlAlign);
element.SetBounds(bounds, BoundsSpecified.None);
}
ResumeSizeSync();
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnPaint"]/*' />
/// <devdoc>
/// Called when the control fires its Paint event.
/// </devdoc>
protected override void OnPaint(PaintEventArgs e) {
// do nothing....
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnLayout"]/*' />
protected internal override void OnLayout(LayoutEventArgs e) {
// do nothing... called via the controls collection
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnParentChanged"]/*' />
/// <devdoc>
/// Called when the item's parent has been changed.
/// </devdoc>
protected override void OnParentChanged(ToolStrip oldParent, ToolStrip newParent) {
if (oldParent != null && Owner == null && newParent == null && Control != null) {
// if we've really been removed from the item collection,
// politely remove ourselves from the control collection
WindowsFormsUtils.ReadOnlyControlCollection oldControlCollection
= GetControlCollection(Control.ParentInternal as ToolStrip);
if (oldControlCollection != null) {
oldControlCollection.RemoveInternal(Control);
}
}
else {
SyncControlParent();
}
base.OnParentChanged(oldParent, newParent);
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnSubscribeControlEvents"]/*' />
/// <devdoc>
/// The events from the hosted control are subscribed here.
/// Override to add/prevent syncing of control events.
/// NOTE: if you override and hook up events here, you should unhook in OnUnsubscribeControlEvents.
/// </devdoc>
protected virtual void OnSubscribeControlEvents(Control control) {
if (control != null) {
// Please keep this alphabetized and in [....] with Unsubscribe
//
control.Click += new EventHandler(HandleClick);
control.BackColorChanged += new EventHandler(HandleBackColorChanged);
control.DoubleClick += new EventHandler(HandleDoubleClick);
control.DragDrop += new DragEventHandler(HandleDragDrop);
control.DragEnter += new DragEventHandler(HandleDragEnter);
control.DragLeave += new EventHandler(HandleDragLeave);
control.DragOver += new DragEventHandler(HandleDragOver);
control.Enter += new EventHandler(HandleEnter);
control.EnabledChanged += new EventHandler(HandleEnabledChanged);
control.ForeColorChanged += new EventHandler(HandleForeColorChanged);
control.GiveFeedback += new GiveFeedbackEventHandler(HandleGiveFeedback);
control.GotFocus += new EventHandler(HandleGotFocus);
control.Leave += new EventHandler(HandleLeave);
control.LocationChanged += new EventHandler(HandleLocationChanged);
control.LostFocus += new EventHandler(HandleLostFocus);
control.KeyDown += new KeyEventHandler(HandleKeyDown);
control.KeyPress += new KeyPressEventHandler(HandleKeyPress);
control.KeyUp += new KeyEventHandler(HandleKeyUp);
control.MouseDown += new MouseEventHandler(HandleMouseDown);
control.MouseEnter += new EventHandler(HandleMouseEnter);
control.MouseHover += new EventHandler(HandleMouseHover);
control.MouseLeave += new EventHandler(HandleMouseLeave);
control.MouseMove += new MouseEventHandler(HandleMouseMove);
control.MouseUp += new MouseEventHandler(HandleMouseUp);
control.Paint += new PaintEventHandler(HandlePaint);
control.QueryAccessibilityHelp += new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp);
control.QueryContinueDrag += new QueryContinueDragEventHandler(HandleQueryContinueDrag);
control.Resize += new EventHandler(HandleResize);
control.RightToLeftChanged += new EventHandler(HandleRightToLeftChanged);
control.TextChanged += new EventHandler(HandleTextChanged);
control.VisibleChanged += new EventHandler(HandleControlVisibleChanged);
control.Validating += new CancelEventHandler(HandleValidating);
control.Validated += new EventHandler(HandleValidated);
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnUnsubscribeControlEvents"]/*' />
/// <devdoc>
/// The events from the hosted control are unsubscribed here.
/// Override to unhook events subscribed in OnSubscribeControlEvents.
/// </devdoc>
protected virtual void OnUnsubscribeControlEvents(Control control) {
if (control != null) {
// Please keep this alphabetized and in [....] with Subscribe
//
control.Click -= new EventHandler(HandleClick);
control.BackColorChanged -= new EventHandler(HandleBackColorChanged);
control.DoubleClick -= new EventHandler(HandleDoubleClick);
control.DragDrop -= new DragEventHandler(HandleDragDrop);
control.DragEnter -= new DragEventHandler(HandleDragEnter);
control.DragLeave -= new EventHandler(HandleDragLeave);
control.DragOver -= new DragEventHandler(HandleDragOver);
control.Enter -= new EventHandler(HandleEnter);
control.EnabledChanged -= new EventHandler(HandleEnabledChanged);
control.ForeColorChanged -= new EventHandler(HandleForeColorChanged);
control.GiveFeedback -= new GiveFeedbackEventHandler(HandleGiveFeedback);
control.GotFocus -= new EventHandler(HandleGotFocus);
control.Leave -= new EventHandler(HandleLeave);
control.LocationChanged -= new EventHandler(HandleLocationChanged);
control.LostFocus -= new EventHandler(HandleLostFocus);
control.KeyDown -= new KeyEventHandler(HandleKeyDown);
control.KeyPress -= new KeyPressEventHandler(HandleKeyPress);
control.KeyUp -= new KeyEventHandler(HandleKeyUp);
control.MouseDown -= new MouseEventHandler(HandleMouseDown);
control.MouseEnter -= new EventHandler(HandleMouseEnter);
control.MouseHover -= new EventHandler(HandleMouseHover);
control.MouseLeave -= new EventHandler(HandleMouseLeave);
control.MouseMove -= new MouseEventHandler(HandleMouseMove);
control.MouseUp -= new MouseEventHandler(HandleMouseUp);
control.Paint -= new PaintEventHandler(HandlePaint);
control.QueryAccessibilityHelp -= new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp);
control.QueryContinueDrag -= new QueryContinueDragEventHandler(HandleQueryContinueDrag);
control.Resize -= new EventHandler(HandleResize);
control.RightToLeftChanged -= new EventHandler(HandleRightToLeftChanged);
control.TextChanged -= new EventHandler(HandleTextChanged);
control.VisibleChanged -= new EventHandler(HandleControlVisibleChanged);
control.Validating -= new CancelEventHandler(HandleValidating);
control.Validated -= new EventHandler(HandleValidated);
}
}
protected virtual void OnValidating(CancelEventArgs e) {
RaiseCancelEvent(EventValidating, e);
}
protected virtual void OnValidated(EventArgs e) {
RaiseEvent(EventValidated, e);
}
private static WindowsFormsUtils.ReadOnlyControlCollection GetControlCollection(ToolStrip toolStrip) {
WindowsFormsUtils.ReadOnlyControlCollection newControls =
toolStrip != null ? (WindowsFormsUtils.ReadOnlyControlCollection) toolStrip.Controls : null;
return newControls;
}
// Ensures the hosted Control is parented to the ToolStrip hosting this ToolStripItem.
private void SyncControlParent() {
WindowsFormsUtils.ReadOnlyControlCollection newControls = GetControlCollection(ParentInternal);
if (newControls != null) {
newControls.AddInternal(Control);
}
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.OnHostedControlResize"]/*' />
protected virtual void OnHostedControlResize(EventArgs e) {
// support for syncing the wrapper when the control size has changed
this.Size = Control.Size;
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.ProcessCmdKey"]/*' />
// SECREVIEW: Technically full trust != unmanaged code, therefore this WndProc is at
// lesser permission that all the other members in the class. Practically speaking though
// they are the same - keeping UnmanagedCode to match the base class.
[SuppressMessage("Microsoft.Security", "CA2114:MethodSecurityShouldBeASupersetOfType")]
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) {
// Control will get this from being in the control collection.
return false;
}
[UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)]
[UIPermission(SecurityAction.InheritanceDemand, Window=UIPermissionWindow.AllWindows)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] // 'charCode' matches control.cs
protected internal override bool ProcessMnemonic(char charCode) {
if (control != null) {
return control.ProcessMnemonic( charCode );
}
return base.ProcessMnemonic( charCode );
}
/// <include file='doc\ToolStripControlHost.uex' path='docs/doc[@for="ToolStripControlHost.ProcessDialogKey"]/*' />
[SuppressMessage("Microsoft.Security", "CA2114:MethodSecurityShouldBeASupersetOfType")]
[UIPermission(SecurityAction.LinkDemand, Window=UIPermissionWindow.AllWindows)]
protected internal override bool ProcessDialogKey(Keys keyData) {
// Control will get this from being in the control collection.
return false;
}
protected override void SetVisibleCore(bool visible) {
// This is needed, because if you try and set set visible to true before the parent is visible,
// we will get called back into here, and set it back to false, since the parent is not visible.
if (inSetVisibleCore) {
return;
}
inSetVisibleCore = true;
Control.SuspendLayout();
try {
Control.Visible = visible;
}
finally {
Control.ResumeLayout(false);
// this will go ahead and perform layout.
base.SetVisibleCore(visible);
inSetVisibleCore = false;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ResetBackColor() {
Control.ResetBackColor();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ResetForeColor() {
Control.ResetForeColor();
}
private void SuspendSizeSync() {
this.suspendSyncSizeCount++;
}
private void ResumeSizeSync() {
this.suspendSyncSizeCount--;
}
internal override bool ShouldSerializeBackColor() {
if (control != null) {
return control.ShouldSerializeBackColor();
}
return base.ShouldSerializeBackColor();
}
internal override bool ShouldSerializeForeColor() {
if (control != null) {
return control.ShouldSerializeForeColor();
}
return base.ShouldSerializeForeColor();
}
internal override bool ShouldSerializeFont() {
if (control != null) {
return control.ShouldSerializeFont();
}
return base.ShouldSerializeFont();
}
internal override bool ShouldSerializeRightToLeft() {
if (control != null) {
return control.ShouldSerializeRightToLeft();
}
return base.ShouldSerializeRightToLeft();
}
// Our implementation of ISite:
// Since the Control which is wrapped by ToolStripControlHost is a runtime instance, there is no way of knowing
// whether the control is in runtime or designtime.
// This implementation of ISite would be set to Control.Site when ToolStripControlHost.Site is set at DesignTime. (Refer to Site property on ToolStripControlHost)
// This implementation just returns the DesigMode property to be ToolStripControlHost's DesignMode property.
// Everything else is pretty much default implementation.
private class StubSite : ISite, IDictionaryService
{
private Hashtable _dictionary = null;
IComponent comp = null;
IComponent owner = null;
public StubSite(Component control, Component host)
{
comp = control as IComponent;
owner = host as IComponent;
}
// The component sited by this component site.
/// <devdoc>
/// <para>When implemented by a class, gets the component associated with the <see cref='System.ComponentModel.ISite'/>.</para>
/// </devdoc>
IComponent ISite.Component {
get
{
return comp;
}
}
// The container in which the component is sited.
/// <devdoc>
/// <para>When implemented by a class, gets the container associated with the <see cref='System.ComponentModel.ISite'/>.</para>
/// </devdoc>
IContainer ISite.Container {
get {
return owner.Site.Container;
}
}
// Indicates whether the component is in design mode.
/// <devdoc>
/// <para>When implemented by a class, determines whether the component is in design mode.</para>
/// </devdoc>
bool ISite.DesignMode {
get {
return owner.Site.DesignMode;
}
}
// The name of the component.
//
/// <devdoc>
/// <para>When implemented by a class, gets or sets the name of
/// the component associated with the <see cref='System.ComponentModel.ISite'/>.</para>
/// </devdoc>
String ISite.Name {
get {
return owner.Site.Name;
}
set {
owner.Site.Name = value;
}
}
/// <summary>
/// Returns the requested service.
/// </summary>
object IServiceProvider.GetService(Type service) {
if (service == null) {
throw new ArgumentNullException("service");
}
// We have to implement our own dictionary service. If we don't,
// the properties of the underlying component will end up being
// overwritten by our own properties when GetProperties is called
if (service == typeof(IDictionaryService)) {
return this;
}
if (owner.Site != null) {
return owner.Site.GetService(service);
}
return null;
}
/// <devdoc>
/// Retrieves the key corresponding to the given value.
/// </devdoc>
object IDictionaryService.GetKey(object value) {
if (_dictionary != null) {
foreach (DictionaryEntry de in _dictionary) {
object o = de.Value;
if (value != null && value.Equals(o)) {
return de.Key;
}
}
}
return null;
}
/// <devdoc>
/// Retrieves the value corresponding to the given key.
/// </devdoc>
object IDictionaryService.GetValue(object key) {
if (_dictionary != null) {
return _dictionary[key];
}
return null;
}
/// <devdoc>
/// Stores the given key-value pair in an object's site. This key-value
/// pair is stored on a per-object basis, and is a handy place to save
/// additional information about a component.
/// </devdoc>
void IDictionaryService.SetValue(object key, object value) {
if (_dictionary == null) {
_dictionary = new Hashtable();
}
if (value == null) {
_dictionary.Remove(key);
} else {
_dictionary[key] = value;
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace NotificationHubs.Tests.ScenarioTests
{
using Microsoft.Azure.Management.NotificationHubs;
using Microsoft.Azure.Management.NotificationHubs.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using TestHelper;
using System;
using Xunit;
using System.Collections.Generic;
using System.Net;
using Microsoft.Rest.Azure;
using System.Linq;
public partial class ScenarioTests
{
[Fact]
public void NotificationHubCreateGetUpdateDelete()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
InitializeClients(context);
var location = NotificationHubsManagementHelper.DefaultLocation;
var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location);
if (string.IsNullOrWhiteSpace(resourceGroup))
{
resourceGroup = TestUtilities.GenerateName(NotificationHubsManagementHelper.ResourceGroupPrefix);
this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup);
}
var namespaceName = TestUtilities.GenerateName(NotificationHubsManagementHelper.NamespacePrefix);
var createNamespaceResponse = NotificationHubsManagementClient.Namespaces.CreateOrUpdate(resourceGroup, namespaceName,
new NamespaceCreateOrUpdateParameters()
{
Location = location
});
Assert.NotNull(createNamespaceResponse);
Assert.Equal(createNamespaceResponse.Name, namespaceName);
ActivateNamespace(resourceGroup, namespaceName);
//Get the created namespace
var getNamespaceResponse = NotificationHubsManagementClient.Namespaces.Get(resourceGroup, namespaceName);
Assert.NotNull(getNamespaceResponse);
Assert.Equal("Succeeded", getNamespaceResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
Assert.Equal("Active", getNamespaceResponse.Status, StringComparer.CurrentCultureIgnoreCase);
var createParameter = new NotificationHubCreateOrUpdateParameters()
{
Location = location,
WnsCredential = new WnsCredential()
{
PackageSid = "ms-app://s-1-15-2-1817505189-427745171-3213743798-2985869298-800724128-1004923984-4143860699",
SecretKey = "w7TBprR-9tJxn9mUOdK4PPHLCAzSYFhp",
WindowsLiveEndpoint = @"http://pushtestservice.cloudapp.net/LiveID/accesstoken.srf"
},
ApnsCredential = new ApnsCredential()
{
KeyId = "TXRXD9P6K7",
AppId = "EF9WEB9D5K",
AppName = "Sample",
Token = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgpVB15km4qskA5Ra5XvdtOwWPvaXIhVVQZdonzINh+hGgCgYIKoZIzj0DAQehRANCAASS3ek04J20BqA6WWDlD6+xd3dJEifhW87wI0nnkfUB8LDb424TiWlzGIgnxV79hb3QHCAUNsPdBfLLF+Od8yqL",
Endpoint = "https://api.push.apple.com:443/3/device"
}
};
//Create a notificationHub
var notificationHubList = CreateNotificationHubs(location, resourceGroup, namespaceName, 1, createParameter);
var notificationHubName = notificationHubList.FirstOrDefault();
//Get the created notificationHub
var getNotificationHubResponse = NotificationHubsManagementClient.NotificationHubs.Get(resourceGroup, namespaceName, notificationHubName);
Assert.NotNull(getNotificationHubResponse);
Assert.Equal(getNotificationHubResponse.Name, notificationHubName);
//Get all namespaces created within a namespace
var getAllNotificationHubsResponse = NotificationHubsManagementClient.NotificationHubs.List(resourceGroup, namespaceName);
Assert.NotNull(getAllNotificationHubsResponse);
Assert.True(getAllNotificationHubsResponse.Count() >= 1);
Assert.Contains(getAllNotificationHubsResponse, nh => string.Compare(nh.Name, notificationHubName, true) == 0);
Assert.True(getAllNotificationHubsResponse.All(nh => nh.Id.Contains(resourceGroup)));
var getNotificationHubPnsCredentialsResponse = NotificationHubsManagementClient.NotificationHubs.GetPnsCredentials(resourceGroup, namespaceName, notificationHubName);
Assert.NotNull(getNotificationHubPnsCredentialsResponse);
Assert.NotNull(getNotificationHubPnsCredentialsResponse);
Assert.Equal(notificationHubName, getNotificationHubPnsCredentialsResponse.Name);
Assert.NotNull(getNotificationHubPnsCredentialsResponse.WnsCredential);
Assert.Equal(getNotificationHubPnsCredentialsResponse.WnsCredential.PackageSid, createParameter.WnsCredential.PackageSid);
Assert.Equal(getNotificationHubPnsCredentialsResponse.WnsCredential.SecretKey, createParameter.WnsCredential.SecretKey);
Assert.Equal(getNotificationHubPnsCredentialsResponse.WnsCredential.WindowsLiveEndpoint, createParameter.WnsCredential.WindowsLiveEndpoint);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.KeyId, createParameter.ApnsCredential.KeyId);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.Token, createParameter.ApnsCredential.Token);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.AppId, createParameter.ApnsCredential.AppId);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.AppName, createParameter.ApnsCredential.AppName);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.Endpoint, createParameter.ApnsCredential.Endpoint);
//Update notificationHub tags and add PNS credentials
var updateNotificationHubParameter = new NotificationHubCreateOrUpdateParameters()
{
Location = location,
Tags = new Dictionary<string, string>()
{
{"tag1", "value1"},
{"tag2", "value2"},
{"tag3", "value3"},
},
WnsCredential = new WnsCredential()
{
PackageSid = "ms-app://s-1-15-2-1817505189-427745171-3213743798-2985869298-800724128-1004923984-4143860699",
SecretKey = "w7TBprR-9tJxn9mUOdK4PPHLCAzSYFhp",
WindowsLiveEndpoint = @"http://pushtestservice.cloudapp.net/LiveID/accesstoken.srf"
},
ApnsCredential = new ApnsCredential()
{
KeyId = "TXRXD9P6K7",
AppId = "EF9WEB9D5K",
AppName = "Sample2",
Token = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgpVB15km4qskA5Ra5XvdtOwWPvaXIhVVQZdonzINh+hGgCgYIKoZIzj0DAQehRANCAASS3ek04J20BqA6WWDlD6+xd3dJEifhW87wI0nnkfUB8LDb424TiWlzGIgnxV79hb3QHCAUNsPdBfLLF+Od8yqL",
Endpoint = "https://api.push.apple.com:443/3/device"
}
};
var jsonStr = NotificationHubsManagementHelper.ConvertObjectToJSon(updateNotificationHubParameter);
var updateNotificationHubResponse = NotificationHubsManagementClient.NotificationHubs.CreateOrUpdate(resourceGroup, namespaceName,
notificationHubName, updateNotificationHubParameter);
Assert.NotNull(updateNotificationHubResponse);
TestUtilities.Wait(TimeSpan.FromSeconds(30));
//Get the updated notificationHub
getNotificationHubResponse = NotificationHubsManagementClient.NotificationHubs.Get(resourceGroup, namespaceName, notificationHubName);
Assert.NotNull(getNotificationHubResponse);
Assert.Equal(3, getNotificationHubResponse.Tags.Count);
foreach (var tag in updateNotificationHubParameter.Tags)
{
Assert.Contains(getNotificationHubResponse.Tags, t => t.Key.Equals(tag.Key));
Assert.Contains(getNotificationHubResponse.Tags, t => t.Value.Equals(tag.Value));
}
//Get the updated notificationHub PNSCredentials
getNotificationHubPnsCredentialsResponse = NotificationHubsManagementClient.NotificationHubs.GetPnsCredentials(resourceGroup, namespaceName, notificationHubName);
Assert.NotNull(getNotificationHubPnsCredentialsResponse);
Assert.Equal(notificationHubName, getNotificationHubPnsCredentialsResponse.Name);
Assert.NotNull(getNotificationHubPnsCredentialsResponse.WnsCredential);
Assert.Equal(getNotificationHubPnsCredentialsResponse.WnsCredential.PackageSid, updateNotificationHubParameter.WnsCredential.PackageSid);
Assert.Equal(getNotificationHubPnsCredentialsResponse.WnsCredential.SecretKey, updateNotificationHubParameter.WnsCredential.SecretKey);
Assert.Equal(getNotificationHubPnsCredentialsResponse.WnsCredential.WindowsLiveEndpoint, updateNotificationHubParameter.WnsCredential.WindowsLiveEndpoint);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.KeyId, updateNotificationHubParameter.ApnsCredential.KeyId);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.Token, updateNotificationHubParameter.ApnsCredential.Token);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.AppId, updateNotificationHubParameter.ApnsCredential.AppId);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.AppName, updateNotificationHubParameter.ApnsCredential.AppName);
Assert.Equal(getNotificationHubPnsCredentialsResponse.ApnsCredential.Endpoint, updateNotificationHubParameter.ApnsCredential.Endpoint);
//Delete notificationHub
NotificationHubsManagementClient.NotificationHubs.Delete(resourceGroup, namespaceName, notificationHubName);
TestUtilities.Wait(TimeSpan.FromSeconds(30));
try
{
NotificationHubsManagementClient.NotificationHubs.Get(resourceGroup, namespaceName, notificationHubName);
Assert.True(false, "this step should have failed");
}
catch (CloudException ex)
{
Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode);
}
try
{
//Delete namespace
NotificationHubsManagementClient.Namespaces.Delete(resourceGroup, namespaceName);
}
catch (Exception ex)
{
Assert.Contains("NotFound", ex.Message);
}
}
}
private List<string> CreateNotificationHubs(string location, string resourceGroup, string namespaceName, int count, NotificationHubCreateOrUpdateParameters parameter)
{
List<string> notificationHubNameList = new List<string>();
for (int i = 0; i < count; i++)
{
var notificationHubName = TestUtilities.GenerateName(NotificationHubsManagementHelper.NotificationHubPrefix) + TestUtilities.GenerateName();
notificationHubNameList.Add(notificationHubName);
Console.WriteLine(notificationHubName);
var jsonStr = NotificationHubsManagementHelper.ConvertObjectToJSon(parameter);
var createNotificationHubResponse = NotificationHubsManagementClient.NotificationHubs.CreateOrUpdate(resourceGroup, namespaceName,
notificationHubName, parameter);
Assert.NotNull(createNotificationHubResponse);
}
return notificationHubNameList;
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Text;
namespace System.Net
{
/// <devdoc>
/// <para>
/// An HTTP-specific implementation of the
/// <see cref='System.Net.WebResponse'/> class.
/// </para>
/// </devdoc>
public class HttpWebResponse : WebResponse, ISerializable
{
private HttpResponseMessage _httpResponseMessage;
private Uri _requestUri;
private CookieCollection _cookies;
private WebHeaderCollection _webHeaderCollection = null;
private string _characterSet = null;
private bool _isVersionHttp11 = true;
public HttpWebResponse() { }
[ObsoleteAttribute("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?linkid=14202")]
protected HttpWebResponse(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
internal HttpWebResponse(HttpResponseMessage _message, Uri requestUri, CookieContainer cookieContainer)
{
_httpResponseMessage = _message;
_requestUri = requestUri;
// Match Desktop behavior. If the request didn't set a CookieContainer, we don't populate the response's CookieCollection.
if (cookieContainer != null)
{
_cookies = cookieContainer.GetCookies(requestUri);
}
else
{
_cookies = new CookieCollection();
}
}
public override bool IsMutuallyAuthenticated
{
get
{
return base.IsMutuallyAuthenticated;
}
}
public override long ContentLength
{
get
{
CheckDisposed();
long? length = _httpResponseMessage.Content.Headers.ContentLength;
return length.HasValue ? length.Value : -1;
}
}
public override string ContentType
{
get
{
CheckDisposed();
// We use TryGetValues() instead of the strongly type Headers.ContentType property so that
// we return a string regardless of it being fully RFC conformant. This matches current
// .NET Framework behavior.
IEnumerable<string> values;
if (_httpResponseMessage.Content.Headers.TryGetValues("Content-Type", out values))
{
// In most cases, there is only one media type value as per RFC. But for completeness, we
// return all values in cases of overly malformed strings.
var builder = new StringBuilder();
int ndx = 0;
foreach (string value in values)
{
if (ndx > 0)
{
builder.Append(',');
}
builder.Append(value);
ndx++;
}
return builder.ToString();
}
else
{
return string.Empty;
}
}
}
public string ContentEncoding
{
get
{
CheckDisposed();
return GetHeaderValueAsString(_httpResponseMessage.Content.Headers.ContentEncoding);
}
}
public virtual CookieCollection Cookies
{
get
{
CheckDisposed();
return _cookies;
}
set
{
CheckDisposed();
_cookies = value;
}
}
public DateTime LastModified
{
get
{
CheckDisposed();
string lastmodHeaderValue = Headers["Last-Modified"];
if (string.IsNullOrEmpty(lastmodHeaderValue))
{
return DateTime.Now;
}
if (HttpDateParser.TryStringToDate(lastmodHeaderValue, out var dateTimeOffset))
{
return dateTimeOffset.LocalDateTime;
}
else
{
throw new ProtocolViolationException(SR.net_baddate);
}
}
}
/// <devdoc>
/// <para>
/// Gets the name of the server that sent the response.
/// </para>
/// </devdoc>
public string Server
{
get
{
CheckDisposed();
return string.IsNullOrEmpty(Headers["Server"]) ? string.Empty : Headers["Server"];
}
}
// HTTP Version
/// <devdoc>
/// <para>
/// Gets
/// the version of the HTTP protocol used in the response.
/// </para>
/// </devdoc>
public Version ProtocolVersion
{
get
{
CheckDisposed();
return _isVersionHttp11 ? HttpVersion.Version11 : HttpVersion.Version10;
}
}
public override WebHeaderCollection Headers
{
get
{
CheckDisposed();
if (_webHeaderCollection == null)
{
_webHeaderCollection = new WebHeaderCollection();
foreach (var header in _httpResponseMessage.Headers)
{
_webHeaderCollection[header.Key] = GetHeaderValueAsString(header.Value);
}
if (_httpResponseMessage.Content != null)
{
foreach (var header in _httpResponseMessage.Content.Headers)
{
_webHeaderCollection[header.Key] = GetHeaderValueAsString(header.Value);
}
}
}
return _webHeaderCollection;
}
}
public virtual string Method
{
get
{
CheckDisposed();
return _httpResponseMessage.RequestMessage.Method.Method;
}
}
public override Uri ResponseUri
{
get
{
CheckDisposed();
// The underlying System.Net.Http API will automatically update
// the .RequestUri property to be the final URI of the response.
return _httpResponseMessage.RequestMessage.RequestUri;
}
}
public virtual HttpStatusCode StatusCode
{
get
{
CheckDisposed();
return _httpResponseMessage.StatusCode;
}
}
public virtual string StatusDescription
{
get
{
CheckDisposed();
return _httpResponseMessage.ReasonPhrase;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string CharacterSet
{
get
{
CheckDisposed();
string contentType = Headers["Content-Type"];
if (_characterSet == null && !string.IsNullOrWhiteSpace(contentType))
{
//sets characterset so the branch is never executed again.
_characterSet = string.Empty;
//first string is the media type
string srchString = contentType.ToLower();
//media subtypes of text type has a default as specified by rfc 2616
if (srchString.Trim().StartsWith("text/"))
{
_characterSet = "ISO-8859-1";
}
//one of the parameters may be the character set
//there must be at least a mediatype for this to be valid
int i = srchString.IndexOf(";");
if (i > 0)
{
//search the parameters
while ((i = srchString.IndexOf("charset", i)) >= 0)
{
i += 7;
//make sure the word starts with charset
if (srchString[i - 8] == ';' || srchString[i - 8] == ' ')
{
//skip whitespace
while (i < srchString.Length && srchString[i] == ' ')
i++;
//only process if next character is '='
//and there is a character after that
if (i < srchString.Length - 1 && srchString[i] == '=')
{
i++;
//get and trim character set substring
int j = srchString.IndexOf(';', i);
//In the past we used
//Substring(i, j). J is the offset not the length
//the qfe is to fix the second parameter so that this it is the
//length. since j points to the next ; the operation j -i
//gives the length of the charset
if (j > i)
_characterSet = contentType.Substring(i, j - i).Trim();
else
_characterSet = contentType.Substring(i).Trim();
//done
break;
}
}
}
}
}
return _characterSet;
}
}
public override bool SupportsHeaders
{
get
{
return true;
}
}
public override Stream GetResponseStream()
{
CheckDisposed();
return _httpResponseMessage.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
}
public string GetResponseHeader(string headerName)
{
CheckDisposed();
string headerValue = Headers[headerName];
return ((headerValue == null) ? string.Empty : headerValue);
}
public override void Close()
{
Dispose(true);
}
protected override void Dispose(bool disposing)
{
var httpResponseMessage = _httpResponseMessage;
if (httpResponseMessage != null)
{
httpResponseMessage.Dispose();
_httpResponseMessage = null;
}
}
private void CheckDisposed()
{
if (_httpResponseMessage == null)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
private string GetHeaderValueAsString(IEnumerable<string> values)
{
// There is always at least one value even if it is an empty string.
var enumerator = values.GetEnumerator();
bool success = enumerator.MoveNext();
Debug.Assert(success, "There should be at least one value");
string headerValue = enumerator.Current;
if (enumerator.MoveNext())
{
// Multi-valued header
var buffer = new StringBuilder(headerValue);
do
{
buffer.Append(", ");
buffer.Append(enumerator.Current);
} while (enumerator.MoveNext());
return buffer.ToString();
}
return headerValue;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using OLEDB.Test.ModuleCore;
using System.IO;
namespace System.Xml.Tests
{
/////////////////////////////////////////////////////////////////////////
// TestCase ReadOuterXml
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadToFollowing : TCXMLReaderBaseGeneral
{
#region XMLSTR
private string _xmlStr = @"<?xml version='1.0'?>
<root><!--Comment-->
<elem><!-- Comment -->
<child1 att='1'><?pi target?>
<child2 xmlns='child2'>
<child3/>
blahblahblah<![CDATA[ blah ]]>
<child4/>
</child2>
<?pi target1?>
</child1>
</elem>
<elem att='1'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah
<child4/>
</child2>
<?pi target1?>
</child1>
</elem>
<elem xmlns='elem'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah2
<child4/>
</child2>
</child1>
</elem>
<elem xmlns='elem' att='1'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah2
<child4/>
</child2>
</child1>
</elem>
<e:elem xmlns:e='elem2'>
<e:child1 att='1'>
<e:child2 xmlns='child2'>
<e:child3/>
blahblahblah2
<e:child4/>
</e:child2>
</e:child1>
</e:elem>
<e:elem xmlns:e='elem2' att='1'>
<e:child1 att='1'>
<e:child2 xmlns='child2'>
<e:child3/>
blahblahblah2
<e:child4/>
</e:child2>
</e:child1>
</e:elem>
</root>";
#endregion
//[Variation("Simple positive test", Pri = 0, Params = new object[] { "NNS" })]
//[Variation("Simple positive test", Pri = 0, Params = new object[] { "DNS" })]
//[Variation("Simple positive test", Pri = 0, Params = new object[] { "NS" })]
public int v1()
{
string type = CurVariation.Params[0].ToString();
CError.WriteLine("Test Type : " + type);
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
switch (type)
{
case "NNS":
DataReader.ReadToFollowing("elem");
CError.Compare(DataReader.HasAttributes, false, "Positioned on wrong element");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
case "DNS":
DataReader.ReadToFollowing("elem", "elem");
if (DataReader.HasAttributes)
CError.Compare(DataReader.GetAttribute("xmlns") != null, "Positioned on wrong element");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
case "NS":
DataReader.ReadToFollowing("e:elem");
if (DataReader.HasAttributes)
CError.Compare(DataReader.GetAttribute("xmlns:e") != null, "Positioned on wrong element");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
default:
throw new CTestFailedException("Error in Test type");
}
}
//[Variation("Read on following with same names", Pri = 1, Params = new object[] { "NNS" })]
//[Variation("Read on following with same names", Pri = 1, Params = new object[] { "DNS" })]
//[Variation("Read on following with same names", Pri = 1, Params = new object[] { "NS" })]
public int v2()
{
string type = CurVariation.Params[0].ToString();
CError.WriteLine("Test Type : " + type);
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
//Doing a sequential read.
switch (type)
{
case "NNS":
DataReader.ReadToFollowing("elem");
int depth = DataReader.Depth;
CError.Compare(DataReader.HasAttributes, false, "Positioned on wrong element");
CError.Compare(DataReader.ReadToFollowing("elem"), true, "There are no more elem nodes");
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
case "DNS":
DataReader.ReadToFollowing("elem", "elem");
if (DataReader.HasAttributes)
CError.Compare(DataReader.GetAttribute("xmlns") != null, "Positioned on wrong element, not on NS");
CError.Compare(DataReader.ReadToFollowing("elem", "elem"), true, "There are no more elem,elem nodes");
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
case "NS":
DataReader.ReadToFollowing("e:elem");
if (DataReader.HasAttributes)
CError.Compare(DataReader.GetAttribute("xmlns:e") != null, "Positioned on wrong element, not on NS");
CError.Compare(DataReader.ReadToFollowing("e:elem"), true, "There are no more descendants");
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
default:
throw new CTestFailedException("Error in Test type");
}
}
[Variation("If name not found, go to eof", Pri = 1)]
public int v4()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("elem");
CError.Compare(DataReader.ReadToFollowing("abc"), false, "Reader returned true for an invalid name");
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("If localname not found go to eof", Pri = 1)]
public int v5_1()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("elem");
CError.Compare(DataReader.ReadToFollowing("abc", "elem"), false, "Reader returned true for an invalid localname");
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("If uri not found, go to eof", Pri = 1)]
public int v5_2()
{
ReloadSource(new StringReader(_xmlStr));
CError.Compare(DataReader.ReadToFollowing("elem", "abc"), false, "Reader returned true for an invalid uri");
CError.Compare(DataReader.NodeType, XmlNodeType.None, "Wrong node type");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Read to Following on one level and again to level below it", Pri = 1)]
public int v6()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
CError.Compare(DataReader.ReadToFollowing("elem"), true, "Cant find elem");
CError.Compare(DataReader.ReadToFollowing("child1"), true, "Cant find child1");
CError.Compare(DataReader.ReadToFollowing("child2"), true, "Cant find child2");
CError.Compare(DataReader.ReadToFollowing("child3"), true, "Cant find child3");
CError.Compare(DataReader.ReadToFollowing("child4"), true, "shouldnt find child4");
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on Element");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Read to Following on one level and again to level below it, with namespace", Pri = 1)]
public int v7()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
CError.Compare(DataReader.ReadToFollowing("elem", "elem"), true, "Cant find elem");
CError.Compare(DataReader.ReadToFollowing("child1", "elem"), true, "Cant find child1");
CError.Compare(DataReader.ReadToFollowing("child2", "child2"), true, "Cant find child2");
CError.Compare(DataReader.ReadToFollowing("child3", "child2"), true, "Cant find child3");
CError.Compare(DataReader.ReadToFollowing("child4", "child2"), true, "Cant find child4");
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on Element");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Read to Following on one level and again to level below it, with prefix", Pri = 1)]
public int v8()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
CError.Compare(DataReader.ReadToFollowing("e:elem"), true, "Cant find elem");
CError.Compare(DataReader.ReadToFollowing("e:child1"), true, "Cant find child1");
CError.Compare(DataReader.ReadToFollowing("e:child2"), true, "Cant find child2");
CError.Compare(DataReader.ReadToFollowing("e:child3"), true, "Cant find child3");
CError.Compare(DataReader.ReadToFollowing("e:child4"), true, "Cant fine child4");
CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on Element");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Multiple Reads to children and then next siblings, NNS", Pri = 2)]
public int v9()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
CError.Compare(DataReader.ReadToFollowing("elem"), true, "Read fails elem");
CError.Compare(DataReader.ReadToFollowing("child3"), true, "Read fails child3");
CError.Compare(DataReader.ReadToNextSibling("child4"), true, "Read fails child4");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Multiple Reads to children and then next siblings, DNS", Pri = 2)]
public int v10()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
CError.Compare(DataReader.ReadToFollowing("elem", "elem"), true, "Read fails elem");
CError.Compare(DataReader.ReadToFollowing("child3", "child2"), true, "Read fails child3");
CError.Compare(DataReader.ReadToNextSibling("child4", "child2"), true, "Read fails child4");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Multiple Reads to children and then next siblings, NS", Pri = 2)]
public int v11()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
CError.Compare(DataReader.ReadToFollowing("e:elem"), true, "Read fails elem");
CError.Compare(DataReader.ReadToFollowing("e:child3"), true, "Read fails child3");
CError.Compare(DataReader.ReadToNextSibling("e:child4"), true, "Read fails child4");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Only child has namespaces and read to it", Pri = 2)]
public int v14()
{
ReloadSource(new StringReader(_xmlStr));
DataReader.PositionOnElement("root");
CError.Compare(DataReader.ReadToFollowing("child2", "child2"), true, "Fails on child2");
DataReader.Close();
return TEST_PASS;
}
[Variation("Pass null to both arguments throws ArgumentException", Pri = 2)]
public int v15()
{
ReloadSource(new StringReader("<root><b/></root>"));
DataReader.Read();
if (IsBinaryReader())
DataReader.Read();
try
{
DataReader.ReadToFollowing(null);
}
catch (ArgumentNullException)
{
CError.WriteLine("Caught for single param");
}
try
{
DataReader.ReadToFollowing("b", null);
}
catch (ArgumentNullException)
{
CError.WriteLine("Caught for single param");
}
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
[Variation("Different names, same uri works correctly", Pri = 2)]
public int v17()
{
ReloadSource(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>"));
DataReader.Read();
if (IsBinaryReader())
DataReader.Read();
DataReader.ReadToFollowing("child1", "bar");
CError.Compare(DataReader.IsEmptyElement, false, "Not on the correct node");
while (DataReader.Read()) ;
DataReader.Close();
return TEST_PASS;
}
}
}
| |
/*
* MSR Tools - tools for mining software repositories
*
* Copyright (C) 2010-2011 Semyon Kirnosenko
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ZedGraph;
namespace MSR.Tools.Visualizer
{
public interface IGraphView
{
void PrepairPointsForDateScale(double[] points, DateTime startDate);
void ShowPoints(string legend, double[] x, double[] y);
void ShowLine(string legend, double[] x, double[] y);
void ShowLineWithPoints(string legend, double[] x, double[] y);
void ShowHistogram(string legend, double[] x, double[] y);
void CleanUp();
string Title { get; set; }
string XAxisTitle { get; set; }
string YAxisTitle { get; set; }
bool XAxisLogScale { get; set; }
bool YAxisLogScale { get; set; }
bool XAxisDayScale { get; set; }
bool YAxisDayScale { get; set; }
float XAxisFontAngle { get; set; }
float YAxisFontAngle { get; set; }
bool BlackAndWhite { get; set; }
IDictionary<double[],double[]> Points { get; }
}
public class GraphView : ZedGraphControl, IGraphView
{
private Dictionary<double[],double[]> points = new Dictionary<double[],double[]>();
private Queue<Color> differentColors;
private Queue<SymbolType> differentSymbols;
private bool blackAndWhite;
public GraphView(Control parent)
{
Parent = parent;
Dock = DockStyle.Fill;
Title = "";
XAxisTitle = "";
YAxisTitle = "";
InitColorsAndSymbols();
}
public void PrepairPointsForDateScale(double[] points, DateTime startDate)
{
for (int i = 0; i < points.Length; i++)
{
points[i] = new XDate(startDate.AddDays(points[i]));
}
}
public void ShowPoints(string legend, double[] x, double[] y)
{
points.Add(x, y);
ShowCurve(legend, x, y, false, true);
}
public void ShowLine(string legend, double[] x, double[] y)
{
ShowCurve(legend, x, y, true, false);
}
public void ShowLineWithPoints(string legend, double[] x, double[] y)
{
ShowCurve(legend, x, y, true, true);
}
public void ShowHistogram(string legend, double[] x, double[] y)
{
BarItem bar = GraphPane.AddBar(legend, x, y, NextColor());
AxisChange();
Invalidate();
}
public void CleanUp()
{
GraphPane.CurveList.Clear();
Invalidate();
points.Clear();
InitColorsAndSymbols();
}
public string Title
{
get { return GraphPane.Title.Text; }
set { GraphPane.Title.Text = value; }
}
public string XAxisTitle
{
get { return GraphPane.XAxis.Title.Text; }
set { GraphPane.XAxis.Title.Text = value; }
}
public string YAxisTitle
{
get { return GraphPane.YAxis.Title.Text; }
set { GraphPane.YAxis.Title.Text = value; }
}
public bool XAxisLogScale
{
get { return IsScale(GraphPane.XAxis, AxisType.Log); }
set { SetScale(GraphPane.XAxis, value ? AxisType.Log : AxisType.Linear); }
}
public bool YAxisLogScale
{
get { return IsScale(GraphPane.YAxis, AxisType.Log); }
set { SetScale(GraphPane.YAxis, value ? AxisType.Log : AxisType.Linear); }
}
public bool XAxisDayScale
{
get { return IsScale(GraphPane.XAxis, AxisType.Date); }
set { SetScale(GraphPane.XAxis, value ? AxisType.Date : AxisType.Linear); }
}
public bool YAxisDayScale
{
get { return IsScale(GraphPane.YAxis, AxisType.Date); }
set { SetScale(GraphPane.YAxis, value ? AxisType.Date : AxisType.Linear); }
}
public float XAxisFontAngle
{
get { return GraphPane.XAxis.Scale.FontSpec.Angle; }
set { GraphPane.XAxis.Scale.FontSpec.Angle = value; }
}
public float YAxisFontAngle
{
get { return GraphPane.YAxis.Scale.FontSpec.Angle; }
set { GraphPane.YAxis.Scale.FontSpec.Angle = value; }
}
public bool BlackAndWhite
{
get { return blackAndWhite; }
set
{
if (blackAndWhite != value)
{
blackAndWhite = value;
InitColorsAndSymbols();
var curves = GraphPane.CurveList.Where(x => x.Tag != null).ToArray();
foreach (var curve in curves)
{
GraphPane.CurveList.Remove(curve);
Color color = BlackAndWhite ? Color.Black : NextColor();
SymbolType symbol = BlackAndWhite ? NextSymbol() : SymbolType.Circle;
LineItem myCurve = GraphPane.AddCurve(curve.Label.Text, curve.Points, color, symbol);
myCurve.Symbol.Fill = new Fill(color);
myCurve.Line.IsVisible = true;
myCurve.Tag = this;
}
Invalidate();
}
}
}
public IDictionary<double[],double[]> Points
{
get { return points; }
}
private void ShowCurve(string legend, double[] x, double[] y, bool line, bool points)
{
Color color = BlackAndWhite ? Color.Black : NextColor();
SymbolType symbol = BlackAndWhite ? NextSymbol() : SymbolType.Circle;
if (! points)
{
symbol = SymbolType.None;
}
LineItem myCurve = GraphPane.AddCurve(legend, x, y, color, symbol);
myCurve.Symbol.Fill = new Fill(line ? color : Color.White);
myCurve.Line.IsVisible = line;
myCurve.Tag = (line && points) ? this : null;
AxisChange();
Invalidate();
}
private void InitColorsAndSymbols()
{
differentColors = new Queue<Color>(new Color[]
{
Color.Black,
Color.Blue,
Color.Red,
Color.Green,
Color.Brown,
Color.Gray,
Color.Orange,
Color.Pink,
Color.Purple,
Color.Silver
});
differentSymbols = new Queue<SymbolType>(new SymbolType[]
{
SymbolType.None,
SymbolType.Diamond,
SymbolType.Triangle,
SymbolType.TriangleDown,
SymbolType.Square,
SymbolType.Circle
});
}
private Color NextColor()
{
Color result = differentColors.Dequeue();
differentColors.Enqueue(result);
return result;
}
private SymbolType NextSymbol()
{
SymbolType result = differentSymbols.Dequeue();
differentSymbols.Enqueue(result);
return result;
}
private bool IsScale(Axis axis, AxisType scale)
{
return axis.Type == scale;
}
private void SetScale(Axis axis, AxisType scale)
{
axis.Type = scale;
AxisChange();
Invalidate();
}
}
}
| |
// 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.Globalization;
using System.Threading;
namespace System.Text
{
public abstract class DecoderFallback
{
private static DecoderFallback s_replacementFallback; // Default fallback, uses no best fit & "?"
private static DecoderFallback s_exceptionFallback;
public static DecoderFallback ReplacementFallback =>
s_replacementFallback ?? Interlocked.CompareExchange(ref s_replacementFallback, new DecoderReplacementFallback(), null) ?? s_replacementFallback;
public static DecoderFallback ExceptionFallback =>
s_exceptionFallback ?? Interlocked.CompareExchange<DecoderFallback>(ref s_exceptionFallback, new DecoderExceptionFallback(), null) ?? s_exceptionFallback;
// Fallback
//
// Return the appropriate unicode string alternative to the character that need to fall back.
// Most implementations will be:
// return new MyCustomDecoderFallbackBuffer(this);
public abstract DecoderFallbackBuffer CreateFallbackBuffer();
// Maximum number of characters that this instance of this fallback could return
public abstract int MaxCharCount { get; }
}
public abstract class DecoderFallbackBuffer
{
// Most implementations will probably need an implementation-specific constructor
// internal methods that cannot be overridden that let us do our fallback thing
// These wrap the internal methods so that we can check for people doing stuff that's incorrect
public abstract bool Fallback(byte[] bytesUnknown, int index);
// Get next character
public abstract char GetNextChar();
// Back up a character
public abstract bool MovePrevious();
// How many chars left in this fallback?
public abstract int Remaining { get; }
// Clear the buffer
public virtual void Reset()
{
while (GetNextChar() != (char)0) ;
}
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
internal unsafe byte* byteStart;
internal unsafe char* charEnd;
// Internal Reset
internal unsafe void InternalReset()
{
byteStart = null;
Reset();
}
// Set the above values
// This can't be part of the constructor because DecoderFallbacks would have to know how to implement these.
internal unsafe void InternalInitialize(byte* byteStart, char* charEnd)
{
this.byteStart = byteStart;
this.charEnd = charEnd;
}
// Fallback the current byte by sticking it into the remaining char buffer.
// This can only be called by our encodings (other have to use the public fallback methods), so
// we can use our DecoderNLS here too (except we don't).
// Returns true if we are successful, false if we can't fallback the character (no buffer space)
// So caller needs to throw buffer space if return false.
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
// Don't touch ref chars unless we succeed
internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars)
{
Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
{
// Copy the chars to our output
char ch;
char* charTemp = chars;
bool bHighSurrogate = false;
while ((ch = GetNextChar()) != 0)
{
// Make sure no mixed up surrogates
if (Char.IsSurrogate(ch))
{
if (Char.IsHighSurrogate(ch))
{
// High Surrogate
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = true;
}
else
{
// Low surrogate
if (bHighSurrogate == false)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = false;
}
}
if (charTemp >= charEnd)
{
// No buffer space
return false;
}
*(charTemp++) = ch;
}
// Need to make sure that bHighSurrogate isn't true
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
// Now we aren't going to be false, so its OK to update chars
chars = charTemp;
}
return true;
}
// This version just counts the fallback and doesn't actually copy anything.
internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes)
// Right now this has both bytes and bytes[], since we might have extra bytes, hence the
// array, and we might need the index, hence the byte*
{
Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
// See if there's a fallback character and we have an output buffer then copy our string.
if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
{
int count = 0;
char ch;
bool bHighSurrogate = false;
while ((ch = GetNextChar()) != 0)
{
// Make sure no mixed up surrogates
if (Char.IsSurrogate(ch))
{
if (Char.IsHighSurrogate(ch))
{
// High Surrogate
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = true;
}
else
{
// Low surrogate
if (bHighSurrogate == false)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = false;
}
}
count++;
}
// Need to make sure that bHighSurrogate isn't true
if (bHighSurrogate)
throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
return count;
}
// If no fallback return 0
return 0;
}
// private helper methods
internal void ThrowLastBytesRecursive(byte[] bytesUnknown)
{
// Create a string representation of our bytes.
StringBuilder strBytes = new StringBuilder(bytesUnknown.Length * 3);
int i;
for (i = 0; i < bytesUnknown.Length && i < 20; i++)
{
if (strBytes.Length > 0)
strBytes.Append(' ');
strBytes.AppendFormat(CultureInfo.InvariantCulture, "\\x{0:X2}", bytesUnknown[i]);
}
// In case the string's really long
if (i == 20)
strBytes.Append(" ...");
// Throw it, using our complete bytes
throw new ArgumentException(
SR.Format(SR.Argument_RecursiveFallbackBytes,
strBytes.ToString()), nameof(bytesUnknown));
}
}
}
| |
using System.Runtime.InteropServices;
using IL2CPU.API.Attribs;
namespace Cosmos.Core {
/// <summary>
/// INTs (INTerruptS) class.
/// </summary>
public class INTs {
#region Enums
// TODO: Protect IRQs like memory and ports are
// TODO: Make IRQs so they are not hookable, and instead release high priority threads like FreeBSD (When we get threading)
/// <summary>
/// EFlags Enum.
/// </summary>
public enum EFlagsEnum : uint {
/// <summary>
/// Set by arithmetic instructions, can be carry or borrow.
/// </summary>
Carry = 1,
/// <summary>
/// Set by most CPU instructions if the LSB of the destination operand contain an even number of 1's.
/// </summary>
Parity = 1 << 2,
/// <summary>
/// Set when an arithmetic carry or borrow has been generated out of the four LSBs.
/// </summary>
AuxilliaryCarry = 1 << 4,
/// <summary>
/// Set to 1 if an arithmetic result is zero, and reset otherwise.
/// </summary>
Zero = 1 << 6,
/// <summary>
/// Set to 1 if the last arithmetic result was positive, and reset otherwise.
/// </summary>
Sign = 1 << 7,
/// <summary>
/// When set to 1, permits single step operations.
/// </summary>
Trap = 1 << 8,
/// <summary>
/// When set to 1, maskable hardware interrupts will be handled, and ignored otherwise.
/// </summary>
InterruptEnable = 1 << 9,
/// <summary>
/// When set to 1, strings is processed from highest address to lowest, and from lowest to highest otherwise.
/// </summary>
Direction = 1 << 10,
/// <summary>
/// Set to 1 if arithmetic overflow has occurred in the last operation.
/// </summary>
Overflow = 1 << 11,
/// <summary>
/// Set to 1 when one system task invoke another by CALL instruction.
/// </summary>
NestedTag = 1 << 14,
/// <summary>
/// When set to 1, enables the option turn off certain exceptions while debugging.
/// </summary>
Resume = 1 << 16,
/// <summary>
/// When set to 1, Virtual8086Mode is enabled.
/// </summary>
Virtual8086Mode = 1 << 17,
/// <summary>
/// When set to 1, enables alignment check.
/// </summary>
AlignmentCheck = 1 << 18,
/// <summary>
/// When set, the program will receive hardware interrupts.
/// </summary>
VirtualInterrupt = 1 << 19,
/// <summary>
/// When set, indicate that there is deferred interrupt pending.
/// </summary>
VirtualInterruptPending = 1 << 20,
/// <summary>
/// When set, indicate that CPUID instruction is available.
/// </summary>
ID = 1 << 21
}
/// <summary>
/// TSS (Task State Segment) struct.
/// </summary>
[StructLayout(LayoutKind.Explicit, Size = 0x68)]
public struct TSS {
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(0)]
public ushort Link;
[FieldOffset(4)]
public uint ESP0;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(8)]
public ushort SS0;
[FieldOffset(12)]
public uint ESP1;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(16)]
public ushort SS1;
[FieldOffset(20)]
public uint ESP2;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(24)]
public ushort SS2;
[FieldOffset(28)]
public uint CR3;
[FieldOffset(32)]
public uint EIP;
[FieldOffset(36)]
public EFlagsEnum EFlags;
[FieldOffset(40)]
public uint EAX;
[FieldOffset(44)]
public uint ECX;
[FieldOffset(48)]
public uint EDX;
[FieldOffset(52)]
public uint EBX;
[FieldOffset(56)]
public uint ESP;
[FieldOffset(60)]
public uint EBP;
[FieldOffset(64)]
public uint ESI;
[FieldOffset(68)]
public uint EDI;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(72)]
public ushort ES;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(76)]
public ushort CS;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(80)]
public ushort SS;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(84)]
public ushort DS;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(88)]
public ushort FS;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(92)]
public ushort GS;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(96)]
public ushort LDTR;
/// <summary>
/// Reserved.
/// </summary>
[FieldOffset(102)]
public ushort IOPBOffset;
}
[StructLayout(LayoutKind.Explicit, Size = 512)]
public struct MMXContext {
}
[StructLayout(LayoutKind.Explicit, Size = 80)]
public struct IRQContext {
[FieldOffset(0)]
public unsafe MMXContext* MMXContext;
[FieldOffset(4)]
public uint EDI;
[FieldOffset(8)]
public uint ESI;
[FieldOffset(12)]
public uint EBP;
[FieldOffset(16)]
public uint ESP;
[FieldOffset(20)]
public uint EBX;
[FieldOffset(24)]
public uint EDX;
[FieldOffset(28)]
public uint ECX;
[FieldOffset(32)]
public uint EAX;
[FieldOffset(36)]
public uint Interrupt;
[FieldOffset(40)]
public uint Param;
[FieldOffset(44)]
public uint EIP;
[FieldOffset(48)]
public uint CS;
[FieldOffset(52)]
public EFlagsEnum EFlags;
[FieldOffset(56)]
public uint UserESP;
}
#endregion
/// <summary>
/// Last known address.
/// </summary>
[AsmMarker(AsmMarker.Type.Int_LastKnownAddress)]
private static uint mLastKnownAddress = 0;
/// <summary>
/// IRQ handlers.
/// </summary>
private static IRQDelegate[] mIRQ_Handlers = new IRQDelegate[256];
// We used to use:
//Interrupts.IRQ01 += HandleKeyboardInterrupt;
// But at one point we had issues with multi cast delegates, so we changed to this single cast option.
// [1:48:37 PM] Matthijs ter Woord: the issues were: "they didn't work, would crash kernel". not sure if we still have them..
/// <summary>
/// Set interrupt handler.
/// </summary>
/// <param name="aIntNo">Interrupt index.</param>
/// <param name="aHandler">IRQ handler.</param>
public static void SetIntHandler(byte aIntNo, IRQDelegate aHandler) {
mIRQ_Handlers[aIntNo] = aHandler;
}
/// <summary>
/// Set IRQ handler.
/// </summary>
/// <param name="aIrqNo">IRQ index.</param>
/// <param name="aHandler">IRQ handler.</param>
public static void SetIrqHandler(byte aIrqNo, IRQDelegate aHandler) {
SetIntHandler((byte)(0x20 + aIrqNo), aHandler);
}
/// <summary>
/// Set IRQ context to IRQ handler.
/// </summary>
/// <param name="irq">IRQ handler index.</param>
/// <param name="aContext">IRQ context.</param>
private static void IRQ(uint irq, ref IRQContext aContext) {
var xCallback = mIRQ_Handlers[irq];
if (xCallback != null) {
xCallback(ref aContext);
}
}
/// <summary>
/// Handle default interrupt.
/// </summary>
/// <param name="aContext">A IEQ context.</param>
public static void HandleInterrupt_Default(ref IRQContext aContext) {
if (aContext.Interrupt >= 0x20 && aContext.Interrupt <= 0x2F) {
if (aContext.Interrupt >= 0x28) {
Global.PIC.EoiSlave();
} else {
Global.PIC.EoiMaster();
}
}
}
/// <summary>
/// IRQ delegate.
/// </summary>
/// <param name="aContext">IRQ context.</param>
public delegate void IRQDelegate(ref IRQContext aContext);
/// <summary>
/// Exception interrupt delegate.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <param name="aHandled">True if handled.</param>
public delegate void ExceptionInterruptDelegate(ref IRQContext aContext, ref bool aHandled);
#region Default Interrupt Handlers
/// <summary>
/// IRQ 0 - System timer. Reserved for the system. Cannot be changed by a user.
/// </summary>
/// <param name="aContext">IRQ context.</param>
public static void HandleInterrupt_20(ref IRQContext aContext) {
IRQ(0x20, ref aContext);
Global.PIC.EoiMaster();
}
//public static IRQDelegate IRQ01;
/// <summary>
/// IRQ 1 - Keyboard. Reserved for the system. Cannot be altered even if no keyboard is present or needed.
/// </summary>
/// <param name="aContext">IRQ context.</param>
public static void HandleInterrupt_21(ref IRQContext aContext) {
IRQ(0x21, ref aContext);
Global.PIC.EoiMaster();
}
public static void HandleInterrupt_22(ref IRQContext aContext) {
IRQ(0x22, ref aContext);
Global.PIC.EoiMaster();
}
public static void HandleInterrupt_23(ref IRQContext aContext) {
IRQ(0x23, ref aContext);
Global.PIC.EoiMaster();
}
public static void HandleInterrupt_24(ref IRQContext aContext) {
IRQ(0x24, ref aContext);
Global.PIC.EoiMaster();
}
public static void HandleInterrupt_25(ref IRQContext aContext) {
IRQ(0x25, ref aContext);
Global.PIC.EoiMaster();
}
public static void HandleInterrupt_26(ref IRQContext aContext) {
IRQ(0x26, ref aContext);
Global.PIC.EoiMaster();
}
public static void HandleInterrupt_27(ref IRQContext aContext) {
IRQ(0x27, ref aContext);
Global.PIC.EoiMaster();
}
public static void HandleInterrupt_28(ref IRQContext aContext) {
IRQ(0x28, ref aContext);
Global.PIC.EoiSlave();
}
/// <summary>
/// IRQ 09 - (Added for AMD PCNet network card).
/// </summary>
/// <param name="aContext">IRQ context.</param>
public static void HandleInterrupt_29(ref IRQContext aContext) {
IRQ(0x29, ref aContext);
Global.PIC.EoiSlave();
}
/// <summary>
/// IRQ 10 - (Added for VIA Rhine network card).
/// </summary>
/// <param name="aContext">IRQ context.</param>
public static void HandleInterrupt_2A(ref IRQContext aContext) {
IRQ(0x2A, ref aContext);
Global.PIC.EoiSlave();
}
/// <summary>
/// IRQ 11 - (Added for RTL8139 network card).
/// </summary>
/// <param name="aContext">IRQ context.</param>
public static void HandleInterrupt_2B(ref IRQContext aContext) {
IRQ(0x2B, ref aContext);
Global.PIC.EoiSlave();
}
public static void HandleInterrupt_2C(ref IRQContext aContext) {
IRQ(0x2C, ref aContext);
Global.PIC.EoiSlave();
}
public static void HandleInterrupt_2D(ref IRQContext aContext) {
IRQ(0x2D, ref aContext);
Global.PIC.EoiSlave();
}
/// <summary>
/// IRQ 14 - Primary IDE. If no Primary IDE this can be changed.
/// </summary>
/// <param name="aContext">IRQ context.</param>
public static void HandleInterrupt_2E(ref IRQContext aContext) {
IRQ(0x2E, ref aContext);
Global.PIC.EoiSlave();
}
/// <summary>
/// IRQ 15 - Secondary IDE.
/// </summary>
/// <param name="aContext">IRQ context.</param>
public static void HandleInterrupt_2F(ref IRQContext aContext) {
IRQ(0x2F, ref aContext);
Global.PIC.EoiSlave();
}
public static event IRQDelegate Interrupt30;
// Interrupt 0x30, enter VMM
public static void HandleInterrupt_30(ref IRQContext aContext) {
if (Interrupt30 != null) {
Interrupt30(ref aContext);
}
}
public static void HandleInterrupt_35(ref IRQContext aContext) {
aContext.EAX *= 2;
aContext.EBX *= 2;
aContext.ECX *= 2;
aContext.EDX *= 2;
}
public static void HandleInterrupt_40(ref IRQContext aContext) {
IRQ(0x40, ref aContext);
}
public static void HandleInterrupt_41(ref IRQContext aContext) {
IRQ(0x41, ref aContext);
}
public static void HandleInterrupt_42(ref IRQContext aContext) {
IRQ(0x42, ref aContext);
}
public static void HandleInterrupt_43(ref IRQContext aContext) {
IRQ(0x43, ref aContext);
}
public static void HandleInterrupt_44(ref IRQContext aContext) {
IRQ(0x44, ref aContext);
}
public static void HandleInterrupt_45(ref IRQContext aContext) {
IRQ(0x45, ref aContext);
}
public static void HandleInterrupt_46(ref IRQContext aContext) {
IRQ(0x46, ref aContext);
}
public static void HandleInterrupt_47(ref IRQContext aContext) {
IRQ(0x47, ref aContext);
}
public static void HandleInterrupt_48(ref IRQContext aContext) {
IRQ(0x48, ref aContext);
}
public static void HandleInterrupt_49(ref IRQContext aContext) {
IRQ(0x49, ref aContext);
}
#endregion
#region CPU Exceptions
/// <summary>
/// General protection fault IRQ delegate.
/// </summary>
public static IRQDelegate GeneralProtectionFault;
/// <summary>
/// Divide By Zero Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_00(ref IRQContext aContext) {
HandleException(aContext.EIP, "Divide by zero", "EDivideByZero", ref aContext, aContext.EIP);
}
/// <summary>
/// Debug Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_01(ref IRQContext aContext) {
HandleException(aContext.EIP, "Debug Exception", "Debug Exception", ref aContext);
}
/// <summary>
/// Non Maskable Interrupt Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_02(ref IRQContext aContext) {
HandleException(aContext.EIP, "Non Maskable Interrupt Exception", "Non Maskable Interrupt Exception", ref aContext);
}
/// <summary>
/// Breakpoint Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_03(ref IRQContext aContext) {
HandleException(aContext.EIP, "Breakpoint Exception", "Breakpoint Exception", ref aContext);
}
/// <summary>
/// Into Detected Overflow Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_04(ref IRQContext aContext) {
HandleException(aContext.EIP, "Into Detected Overflow Exception", "Into Detected Overflow Exception", ref aContext);
}
/// <summary>
/// Out of Bounds Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_05(ref IRQContext aContext) {
HandleException(aContext.EIP, "Out of Bounds Exception", "Out of Bounds Exception", ref aContext);
}
/// <summary>
/// Invalid Opcode.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_06(ref IRQContext aContext) {
// although mLastKnownAddress is a static, we need to get it here, any subsequent calls will change the value!!!
var xLastKnownAddress = mLastKnownAddress;
HandleException(aContext.EIP, "Invalid Opcode", "EInvalidOpcode", ref aContext, xLastKnownAddress);
}
/// <summary>
/// No Coprocessor Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_07(ref IRQContext aContext) {
HandleException(aContext.EIP, "No Coprocessor Exception", "No Coprocessor Exception", ref aContext);
}
/// <summary>
/// Double Fault Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_08(ref IRQContext aContext) {
HandleException(aContext.EIP, "Double Fault Exception", "Double Fault Exception", ref aContext);
}
/// <summary>
/// Coprocessor Segment Overrun Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_09(ref IRQContext aContext) {
HandleException(aContext.EIP, "Coprocessor Segment Overrun Exception", "Coprocessor Segment Overrun Exception", ref aContext);
}
/// <summary>
/// Bad TSS Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_0A(ref IRQContext aContext) {
HandleException(aContext.EIP, "Bad TSS Exception", "Bad TSS Exception", ref aContext);
}
/// <summary>
/// Segment Not Present.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_0B(ref IRQContext aContext) {
HandleException(aContext.EIP, "Segment Not Present", "Segment Not Present", ref aContext);
}
/// <summary>
/// Stack Fault Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_0C(ref IRQContext aContext) {
HandleException(aContext.EIP, "Stack Fault Exception", "Stack Fault Exception", ref aContext);
}
/// <summary>
/// General Protection Fault.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_0D(ref IRQContext aContext) {
if (GeneralProtectionFault != null) {
GeneralProtectionFault(ref aContext);
} else {
HandleException(aContext.EIP, "General Protection Fault", "GPF", ref aContext);
}
}
/// <summary>
/// Page Fault Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_0E(ref IRQContext aContext) {
HandleException(aContext.EIP, "Page Fault Exception", "Page Fault Exception", ref aContext);
}
/// <summary>
/// Unknown Interrupt Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_0F(ref IRQContext aContext) {
HandleException(aContext.EIP, "Unknown Interrupt Exception", "Unknown Interrupt Exception", ref aContext);
}
/// <summary>
/// x87 Floating Point Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_10(ref IRQContext aContext) {
HandleException(aContext.EIP, "x87 Floating Point Exception", "Coprocessor Fault Exception", ref aContext);
}
/// <summary>
/// Alignment Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_11(ref IRQContext aContext) {
HandleException(aContext.EIP, "Alignment Exception", "Alignment Exception", ref aContext);
}
/// <summary>
/// Machine Check Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_12(ref IRQContext aContext) {
HandleException(aContext.EIP, "Machine Check Exception", "Machine Check Exception", ref aContext);
}
/// <summary>
/// SIMD Floating Point Exception.
/// </summary>
/// <param name="aContext">IRQ context.</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void HandleInterrupt_13(ref IRQContext aContext) {
HandleException(aContext.EIP, "SIMD Floating Point Exception", "SIMD Floating Point Exception", ref aContext);
}
#endregion
/// <summary>
/// Handle exception.
/// </summary>
/// <param name="aEIP">Unused.</param>
/// <param name="aDescription">Unused.</param>
/// <param name="aName">Unused.</param>
/// <param name="ctx">IRQ context.</param>
/// <param name="lastKnownAddressValue">Last known address value. (default = 0)</param>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
private static void HandleException(uint aEIP, string aDescription, string aName, ref IRQContext ctx, uint lastKnownAddressValue = 0) {
// At this point we are in a very unstable state.
// Try not to use any Cosmos routines, just
// report a crash dump.
const string xHex = "0123456789ABCDEF";
uint xPtr = ctx.EIP;
// we're printing exception info to the screen now:
// 0/0: x
// 1/0: exception number in hex
unsafe
{
byte* xAddress = (byte*)0xB8000;
PutErrorChar(0, 00, ' ');
PutErrorChar(0, 01, '*');
PutErrorChar(0, 02, '*');
PutErrorChar(0, 03, '*');
PutErrorChar(0, 04, ' ');
PutErrorChar(0, 05, 'C');
PutErrorChar(0, 06, 'P');
PutErrorChar(0, 07, 'U');
PutErrorChar(0, 08, ' ');
PutErrorChar(0, 09, 'E');
PutErrorChar(0, 10, 'x');
PutErrorChar(0, 11, 'c');
PutErrorChar(0, 12, 'e');
PutErrorChar(0, 13, 'p');
PutErrorChar(0, 14, 't');
PutErrorChar(0, 15, 'i');
PutErrorChar(0, 16, 'o');
PutErrorChar(0, 17, 'n');
PutErrorChar(0, 18, ' ');
PutErrorChar(0, 19, 'x');
PutErrorChar(0, 20, xHex[(int)((ctx.Interrupt >> 4) & 0xF)]);
PutErrorChar(0, 21, xHex[(int)(ctx.Interrupt & 0xF)]);
PutErrorChar(0, 22, ' ');
PutErrorChar(0, 23, '*');
PutErrorChar(0, 24, '*');
PutErrorChar(0, 25, '*');
PutErrorChar(0, 26, ' ');
if (lastKnownAddressValue != 0) {
PutErrorString(1, 0, "Last known address: 0x");
PutErrorChar(1, 22, xHex[(int)((lastKnownAddressValue >> 28) & 0xF)]);
PutErrorChar(1, 23, xHex[(int)((lastKnownAddressValue >> 24) & 0xF)]);
PutErrorChar(1, 24, xHex[(int)((lastKnownAddressValue >> 20) & 0xF)]);
PutErrorChar(1, 25, xHex[(int)((lastKnownAddressValue >> 16) & 0xF)]);
PutErrorChar(1, 26, xHex[(int)((lastKnownAddressValue >> 12) & 0xF)]);
PutErrorChar(1, 27, xHex[(int)((lastKnownAddressValue >> 8) & 0xF)]);
PutErrorChar(1, 28, xHex[(int)((lastKnownAddressValue >> 4) & 0xF)]);
PutErrorChar(1, 29, xHex[(int)(lastKnownAddressValue & 0xF)]);
}
}
// lock up
while (true) {
}
}
/// <summary>
/// Put error char.
/// </summary>
/// <param name="line">Line to put the error char at.</param>
/// <param name="col">Column to put the error char at.</param>
/// <param name="c">Char to put.</param>
private static void PutErrorChar(int line, int col, char c) {
unsafe
{
byte* xAddress = (byte*)0xB8000;
xAddress += ((line * 80) + col) * 2;
xAddress[0] = (byte)c;
xAddress[1] = 0x0C;
}
}
/// <summary>
/// Put error string.
/// </summary>
/// <param name="line">Line to put the error string at.</param>
/// <param name="startCol">Starting column to put the error string at.</param>
/// <param name="error">Error string to put.</param>
/// <exception cref="System.OverflowException">Thrown if error length in greater then Int32.MaxValue.</exception>
private static void PutErrorString(int line, int startCol, string error) {
for (int i = 0; i < error.Length; i++) {
PutErrorChar(line, startCol + i, error[i]);
}
}
// This is to trick IL2CPU to compile it in
//TODO: Make a new attribute that IL2CPU sees when scanning to force inclusion so we dont have to do this.
// We dont actually need to call this method
/// <summary>
/// Dummy function, used by the bootstrap.
/// </summary>
/// <remarks>This is to trick IL2CPU to compile it in.</remarks>
/// <exception cref="System.IndexOutOfRangeException">Thrown on fatal error, contact support.</exception>
/// <exception cref="System.OverflowException">Thrown on fatal error, contact support.</exception>
public static void Dummy() {
// Compiler magic
bool xTest = false;
if (xTest) {
unsafe
{
var xCtx = new IRQContext();
HandleInterrupt_Default(ref xCtx);
HandleInterrupt_00(ref xCtx);
HandleInterrupt_01(ref xCtx);
HandleInterrupt_02(ref xCtx);
HandleInterrupt_03(ref xCtx);
HandleInterrupt_04(ref xCtx);
HandleInterrupt_05(ref xCtx);
HandleInterrupt_06(ref xCtx);
HandleInterrupt_07(ref xCtx);
HandleInterrupt_08(ref xCtx);
HandleInterrupt_09(ref xCtx);
HandleInterrupt_0A(ref xCtx);
HandleInterrupt_0B(ref xCtx);
HandleInterrupt_0C(ref xCtx);
HandleInterrupt_0D(ref xCtx);
HandleInterrupt_0E(ref xCtx);
HandleInterrupt_0F(ref xCtx);
HandleInterrupt_10(ref xCtx);
HandleInterrupt_11(ref xCtx);
HandleInterrupt_12(ref xCtx);
HandleInterrupt_13(ref xCtx);
HandleInterrupt_20(ref xCtx);
HandleInterrupt_21(ref xCtx);
HandleInterrupt_22(ref xCtx);
HandleInterrupt_23(ref xCtx);
HandleInterrupt_24(ref xCtx);
HandleInterrupt_25(ref xCtx);
HandleInterrupt_26(ref xCtx);
HandleInterrupt_27(ref xCtx);
HandleInterrupt_28(ref xCtx);
HandleInterrupt_29(ref xCtx);
HandleInterrupt_2A(ref xCtx);
HandleInterrupt_2B(ref xCtx);
HandleInterrupt_2C(ref xCtx);
HandleInterrupt_2D(ref xCtx);
HandleInterrupt_2E(ref xCtx);
HandleInterrupt_2F(ref xCtx);
HandleInterrupt_30(ref xCtx);
HandleInterrupt_35(ref xCtx);
HandleInterrupt_40(ref xCtx);
HandleInterrupt_41(ref xCtx);
HandleInterrupt_42(ref xCtx);
HandleInterrupt_43(ref xCtx);
HandleInterrupt_44(ref xCtx);
HandleInterrupt_45(ref xCtx);
HandleInterrupt_46(ref xCtx);
HandleInterrupt_47(ref xCtx);
HandleInterrupt_48(ref xCtx);
HandleInterrupt_49(ref xCtx);
}
}
}
}
}
| |
//
// 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;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Database data
/// masking. Contains operations to: Create, Retrieve, Update, and Delete
/// data masking rules, as well as Create, Retreive and Update data
/// masking policy.
/// </summary>
internal partial class DataMaskingOperations : IServiceOperations<SqlManagementClient>, IDataMaskingOperations
{
/// <summary>
/// Initializes a new instance of the DataMaskingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DataMaskingOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Database data masking policy
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a
/// firewall rule.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdatePolicyAsync(string resourceGroupName, string serverName, string databaseName, DataMaskingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.DataMaskingState == null)
{
throw new ArgumentNullException("parameters.Properties.DataMaskingState");
}
if (parameters.Properties.ExemptPrincipals == null)
{
throw new ArgumentNullException("parameters.Properties.ExemptPrincipals");
}
// 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("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdatePolicyAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/dataMaskingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject dataMaskingPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = dataMaskingPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
dataMaskingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["dataMaskingState"] = parameters.Properties.DataMaskingState;
propertiesValue["exemptPrincipals"] = parameters.Properties.ExemptPrincipals;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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>
/// Creates or updates an Azure SQL Database Server Firewall rule.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='dataMaskingRule'>
/// Required. The name of the Azure SQL Database data masking rule.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a data
/// masking rule.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> CreateOrUpdateRuleAsync(string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, DataMaskingRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (dataMaskingRule == null)
{
throw new ArgumentNullException("dataMaskingRule");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.Id == null)
{
throw new ArgumentNullException("parameters.Properties.Id");
}
if (parameters.Properties.MaskingFunction == null)
{
throw new ArgumentNullException("parameters.Properties.MaskingFunction");
}
if (parameters.Properties.RuleState == null)
{
throw new ArgumentNullException("parameters.Properties.RuleState");
}
// 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("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("dataMaskingRule", dataMaskingRule);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateRuleAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/dataMaskingPolicies/Default/rules/";
url = url + Uri.EscapeDataString(dataMaskingRule);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject dataMaskingRuleCreateOrUpdateParametersValue = new JObject();
requestDoc = dataMaskingRuleCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
dataMaskingRuleCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["id"] = parameters.Properties.Id;
propertiesValue["ruleState"] = parameters.Properties.RuleState;
if (parameters.Properties.SchemaName != null)
{
propertiesValue["schemaName"] = parameters.Properties.SchemaName;
}
if (parameters.Properties.TableName != null)
{
propertiesValue["tableName"] = parameters.Properties.TableName;
}
if (parameters.Properties.ColumnName != null)
{
propertiesValue["columnName"] = parameters.Properties.ColumnName;
}
propertiesValue["maskingFunction"] = parameters.Properties.MaskingFunction;
if (parameters.Properties.NumberFrom != null)
{
propertiesValue["numberFrom"] = parameters.Properties.NumberFrom;
}
if (parameters.Properties.NumberTo != null)
{
propertiesValue["numberTo"] = parameters.Properties.NumberTo;
}
if (parameters.Properties.PrefixSize != null)
{
propertiesValue["prefixSize"] = parameters.Properties.PrefixSize;
}
if (parameters.Properties.SuffixSize != null)
{
propertiesValue["suffixSize"] = parameters.Properties.SuffixSize;
}
if (parameters.Properties.ReplacementString != null)
{
propertiesValue["replacementString"] = parameters.Properties.ReplacementString;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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>
/// Deletes an Azure SQL Server data masking rule.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rule applies.
/// </param>
/// <param name='dataMaskingRule'>
/// Required. The name of the Azure SQL Database data masking rule.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (dataMaskingRule == null)
{
throw new ArgumentNullException("dataMaskingRule");
}
// 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("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("dataMaskingRule", dataMaskingRule);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/dataMaskingPolicies/Default/rules/";
url = url + Uri.EscapeDataString(dataMaskingRule);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// 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 && 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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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>
/// Returns an Azure SQL Database data masking policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking policy applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a data masking policy get request.
/// </returns>
public async Task<DataMaskingPolicyGetResponse> GetPolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// 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("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetPolicyAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/dataMaskingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DataMaskingPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataMaskingPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DataMaskingPolicy dataMaskingPolicyInstance = new DataMaskingPolicy();
result.DataMaskingPolicy = dataMaskingPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DataMaskingPolicyProperties propertiesInstance = new DataMaskingPolicyProperties();
dataMaskingPolicyInstance.Properties = propertiesInstance;
JToken dataMaskingStateValue = propertiesValue["dataMaskingState"];
if (dataMaskingStateValue != null && dataMaskingStateValue.Type != JTokenType.Null)
{
string dataMaskingStateInstance = ((string)dataMaskingStateValue);
propertiesInstance.DataMaskingState = dataMaskingStateInstance;
}
JToken exemptPrincipalsValue = propertiesValue["exemptPrincipals"];
if (exemptPrincipalsValue != null && exemptPrincipalsValue.Type != JTokenType.Null)
{
string exemptPrincipalsInstance = ((string)exemptPrincipalsValue);
propertiesInstance.ExemptPrincipals = exemptPrincipalsInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dataMaskingPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataMaskingPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dataMaskingPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dataMaskingPolicyInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dataMaskingPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
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>
/// Returns a list of Azure SQL Database data masking rules.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the data
/// masking rules applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List data masking rules request.
/// </returns>
public async Task<DataMaskingRuleListResponse> ListAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// 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("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/dataMaskingPolicies/Default/Rules";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DataMaskingRuleListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DataMaskingRuleListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DataMaskingRule dataMaskingRuleInstance = new DataMaskingRule();
result.DataMaskingRules.Add(dataMaskingRuleInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DataMaskingRuleProperties propertiesInstance = new DataMaskingRuleProperties();
dataMaskingRuleInstance.Properties = propertiesInstance;
JToken idValue = propertiesValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
propertiesInstance.Id = idInstance;
}
JToken ruleStateValue = propertiesValue["ruleState"];
if (ruleStateValue != null && ruleStateValue.Type != JTokenType.Null)
{
string ruleStateInstance = ((string)ruleStateValue);
propertiesInstance.RuleState = ruleStateInstance;
}
JToken schemaNameValue = propertiesValue["schemaName"];
if (schemaNameValue != null && schemaNameValue.Type != JTokenType.Null)
{
string schemaNameInstance = ((string)schemaNameValue);
propertiesInstance.SchemaName = schemaNameInstance;
}
JToken tableNameValue = propertiesValue["tableName"];
if (tableNameValue != null && tableNameValue.Type != JTokenType.Null)
{
string tableNameInstance = ((string)tableNameValue);
propertiesInstance.TableName = tableNameInstance;
}
JToken columnNameValue = propertiesValue["columnName"];
if (columnNameValue != null && columnNameValue.Type != JTokenType.Null)
{
string columnNameInstance = ((string)columnNameValue);
propertiesInstance.ColumnName = columnNameInstance;
}
JToken maskingFunctionValue = propertiesValue["maskingFunction"];
if (maskingFunctionValue != null && maskingFunctionValue.Type != JTokenType.Null)
{
string maskingFunctionInstance = ((string)maskingFunctionValue);
propertiesInstance.MaskingFunction = maskingFunctionInstance;
}
JToken numberFromValue = propertiesValue["numberFrom"];
if (numberFromValue != null && numberFromValue.Type != JTokenType.Null)
{
string numberFromInstance = ((string)numberFromValue);
propertiesInstance.NumberFrom = numberFromInstance;
}
JToken numberToValue = propertiesValue["numberTo"];
if (numberToValue != null && numberToValue.Type != JTokenType.Null)
{
string numberToInstance = ((string)numberToValue);
propertiesInstance.NumberTo = numberToInstance;
}
JToken prefixSizeValue = propertiesValue["prefixSize"];
if (prefixSizeValue != null && prefixSizeValue.Type != JTokenType.Null)
{
string prefixSizeInstance = ((string)prefixSizeValue);
propertiesInstance.PrefixSize = prefixSizeInstance;
}
JToken suffixSizeValue = propertiesValue["suffixSize"];
if (suffixSizeValue != null && suffixSizeValue.Type != JTokenType.Null)
{
string suffixSizeInstance = ((string)suffixSizeValue);
propertiesInstance.SuffixSize = suffixSizeInstance;
}
JToken replacementStringValue = propertiesValue["replacementString"];
if (replacementStringValue != null && replacementStringValue.Type != JTokenType.Null)
{
string replacementStringInstance = ((string)replacementStringValue);
propertiesInstance.ReplacementString = replacementStringInstance;
}
}
JToken idValue2 = valueValue["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
dataMaskingRuleInstance.Id = idInstance2;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dataMaskingRuleInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dataMaskingRuleInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dataMaskingRuleInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dataMaskingRuleInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
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();
}
}
}
}
}
| |
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
namespace ClosedXML_Examples
{
public class PivotTables : IXLExample
{
private class Pastry
{
public Pastry(string name, int numberOfOrders, double quality, string month, DateTime bakeDate)
{
Name = name;
NumberOfOrders = numberOfOrders;
Quality = quality;
Month = month;
BakeDate = bakeDate;
}
public string Name { get; set; }
public int NumberOfOrders { get; set; }
public double Quality { get; set; }
public string Month { get; set; }
public DateTime BakeDate { get; set; }
}
public void Create(String filePath)
{
var pastries = new List<Pastry>
{
new Pastry("Croissant", 150, 60.2, "Apr", new DateTime(2016, 04, 21)),
new Pastry("Croissant", 250, 50.42, "May", new DateTime(2016, 05, 03)),
new Pastry("Croissant", 134, 22.12, "Jun", new DateTime(2016, 06, 24)),
new Pastry("Doughnut", 250, 89.99, "Apr", new DateTime(2017, 04, 23)),
new Pastry("Doughnut", 225, 70, "May", new DateTime(2016, 05, 24)),
new Pastry("Doughnut", 210, 75.33, "Jun", new DateTime(2016, 06, 02)),
new Pastry("Bearclaw", 134, 10.24, "Apr", new DateTime(2016, 04, 27)),
new Pastry("Bearclaw", 184, 33.33, "May", new DateTime(2016, 05, 20)),
new Pastry("Bearclaw", 124, 25, "Jun", new DateTime(2017, 06, 05)),
new Pastry("Danish", 394, -20.24, "Apr", new DateTime(2017, 04, 24)),
new Pastry("Danish", 190, 60, "May", new DateTime(2017, 05, 08)),
new Pastry("Danish", 221, 24.76, "Jun", new DateTime(2016, 06, 21)),
// Deliberately add different casings of same string to ensure pivot table doesn't duplicate it.
new Pastry("Scone", 135, 0, "Apr", new DateTime(2017, 04, 22)),
new Pastry("SconE", 122, 5.19, "May", new DateTime(2017, 05, 03)),
new Pastry("SCONE", 243, 44.2, "Jun", new DateTime(2017, 06, 14)),
};
using (var wb = new XLWorkbook())
{
var sheet = wb.Worksheets.Add("PastrySalesData");
// Insert our list of pastry data into the "PastrySalesData" sheet at cell 1,1
var source = sheet.Cell(1, 1).InsertTable(pastries, "PastrySalesData", true);
sheet.Columns().AdjustToContents();
// Create a range that includes our table, including the header row
var range = source.DataRange;
var header = sheet.Range(1, 1, 1, 3);
var dataRange = sheet.Range(header.FirstCell(), range.LastCell());
IXLWorksheet ptSheet;
IXLPivotTable pt;
#region Pivots
for (int i = 1; i <= 3; i++)
{
// Add a new sheet for our pivot table
ptSheet = wb.Worksheets.Add("pvt" + i);
// Create the pivot table, using the data from the "PastrySalesData" table
pt = ptSheet.PivotTables.AddNew("pvt", ptSheet.Cell(1, 1), dataRange);
// The rows in our pivot table will be the names of the pastries
pt.RowLabels.Add("Name");
if (i == 2) pt.RowLabels.Add(XLConstants.PivotTableValuesSentinalLabel);
// The columns will be the months
pt.ColumnLabels.Add("Month");
if (i == 3) pt.ColumnLabels.Add(XLConstants.PivotTableValuesSentinalLabel);
// The values in our table will come from the "NumberOfOrders" field
// The default calculation setting is a total of each row/column
pt.Values.Add("NumberOfOrders", "NumberOfOrdersPercentageOfBearclaw")
.ShowAsPercentageFrom("Name").And("Bearclaw")
.NumberFormat.Format = "0%";
if (i > 1)
{
pt.Values.Add("Quality", "Sum of Quality")
.NumberFormat.SetFormat("#,##0.00");
}
if (i > 2)
{
pt.Values.Add("NumberOfOrders", "Sum of NumberOfOrders");
}
ptSheet.Columns().AdjustToContents();
}
#endregion Pivots
#region Different kind of pivot
ptSheet = wb.Worksheets.Add("pvtNoColumnLabels");
pt = ptSheet.PivotTables.AddNew("pvtNoColumnLabels", ptSheet.Cell(1, 1), dataRange);
pt.RowLabels.Add("Name");
pt.RowLabels.Add("Month");
pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum);
pt.Values.Add("Quality").SetSummaryFormula(XLPivotSummary.Sum);
pt.SetRowHeaderCaption("Pastry name");
#endregion Different kind of pivot
#region Pivot table with collapsed fields
ptSheet = wb.Worksheets.Add("pvtCollapsedFields");
pt = ptSheet.PivotTables.AddNew("pvtCollapsedFields", ptSheet.Cell(1, 1), dataRange);
pt.RowLabels.Add("Name").SetCollapsed();
pt.RowLabels.Add("Month").SetCollapsed();
pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum);
pt.Values.Add("Quality").SetSummaryFormula(XLPivotSummary.Sum);
#endregion Pivot table with collapsed fields
#region Pivot table with a field both as a value and as a row/column/filter label
ptSheet = wb.Worksheets.Add("pvtFieldAsValueAndLabel");
pt = ptSheet.PivotTables.AddNew("pvtFieldAsValueAndLabel", ptSheet.Cell(1, 1), dataRange);
pt.RowLabels.Add("Name");
pt.RowLabels.Add("Month");
pt.Values.Add("Name").SetSummaryFormula(XLPivotSummary.Count);//.NumberFormat.Format = "#0.00";
#endregion Pivot table with a field both as a value and as a row/column/filter label
#region Pivot table with subtotals disabled
ptSheet = wb.Worksheets.Add("pvtHideSubTotals");
// Create the pivot table, using the data from the "PastrySalesData" table
pt = ptSheet.PivotTables.AddNew("pvtHidesubTotals", ptSheet.Cell(1, 1), dataRange);
// The rows in our pivot table will be the names of the pastries
pt.RowLabels.Add(XLConstants.PivotTableValuesSentinalLabel);
// The columns will be the months
pt.ColumnLabels.Add("Month");
pt.ColumnLabels.Add("Name");
// The values in our table will come from the "NumberOfOrders" field
// The default calculation setting is a total of each row/column
pt.Values.Add("NumberOfOrders", "NumberOfOrdersPercentageOfBearclaw")
.ShowAsPercentageFrom("Name").And("Bearclaw")
.NumberFormat.Format = "0%";
pt.Values.Add("Quality", "Sum of Quality")
.NumberFormat.SetFormat("#,##0.00");
pt.Subtotals = XLPivotSubtotals.DoNotShow;
pt.SetColumnHeaderCaption("Measures");
ptSheet.Columns().AdjustToContents();
#endregion Pivot table with subtotals disabled
#region Pivot Table with filter
ptSheet = wb.Worksheets.Add("pvtFilter");
pt = ptSheet.PivotTables.AddNew("pvtFilter", ptSheet.Cell(1, 1), dataRange);
pt.RowLabels.Add("Month");
pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum);
pt.ReportFilters.Add("Name")
.AddSelectedValue("Scone")
.AddSelectedValue("Doughnut");
pt.ReportFilters.Add("Quality")
.AddSelectedValue(5.19);
pt.ReportFilters.Add("BakeDate")
.AddSelectedValue(new DateTime(2017, 05, 03));
#endregion Pivot Table with filter
wb.SaveAs(filePath);
}
}
}
}
| |
#region Header
/**
* JsonMapper.cs
* JSON to .Net object and object to JSON conversions.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace LitJson
{
// [XtraLife] Will cause obj's attributed fields/properties to be skipped while using JsonMapper.ToJson(obj)...
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class SkipToJson : Attribute {}
// [XtraLife] Will cause obj's attributed fields/properties to be treated with its ToString() method while using JsonMapper.ToJson(obj)...
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class SimpleToJson : Attribute {}
internal struct PropertyMetadata
{
public MemberInfo Info;
public bool IsField;
public Type Type;
}
internal struct ArrayMetadata
{
private Type element_type;
private bool is_array;
private bool is_list;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsArray {
get { return is_array; }
set { is_array = value; }
}
public bool IsList {
get { return is_list; }
set { is_list = value; }
}
}
internal struct ObjectMetadata
{
private Type element_type;
private bool is_dictionary;
private IDictionary<string, PropertyMetadata> properties;
public Type ElementType {
get {
if (element_type == null)
return typeof (JsonData);
return element_type;
}
set { element_type = value; }
}
public bool IsDictionary {
get { return is_dictionary; }
set { is_dictionary = value; }
}
public IDictionary<string, PropertyMetadata> Properties {
get { return properties; }
set { properties = value; }
}
}
internal delegate void ExporterFunc (object obj, JsonWriter writer);
public delegate void ExporterFunc<T> (T obj, JsonWriter writer);
internal delegate object ImporterFunc (object input);
public delegate TValue ImporterFunc<TJson, TValue> (TJson input);
public delegate IJsonWrapper WrapperFactory ();
public class JsonMapper
{
#region Fields
private static readonly int max_nesting_depth;
private static readonly IFormatProvider datetime_format;
private static readonly IDictionary<Type, ExporterFunc> base_exporters_table;
private static readonly IDictionary<Type, ExporterFunc> custom_exporters_table;
private static readonly IDictionary<Type,
IDictionary<Type, ImporterFunc>> base_importers_table;
private static readonly IDictionary<Type,
IDictionary<Type, ImporterFunc>> custom_importers_table;
private static readonly IDictionary<Type, ArrayMetadata> array_metadata;
private static readonly object array_metadata_lock = new Object ();
private static readonly IDictionary<Type,
IDictionary<Type, MethodInfo>> conv_ops;
private static readonly object conv_ops_lock = new Object ();
private static readonly IDictionary<Type, ObjectMetadata> object_metadata;
private static readonly object object_metadata_lock = new Object ();
private static readonly IDictionary<Type,
IList<PropertyMetadata>> type_properties;
private static readonly object type_properties_lock = new Object ();
private static readonly JsonWriter static_writer;
private static readonly object static_writer_lock = new Object ();
#endregion
#region Constructors
static JsonMapper ()
{
max_nesting_depth = 100;
array_metadata = new Dictionary<Type, ArrayMetadata> ();
conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> ();
object_metadata = new Dictionary<Type, ObjectMetadata> ();
type_properties = new Dictionary<Type,
IList<PropertyMetadata>> ();
static_writer = new JsonWriter ();
datetime_format = DateTimeFormatInfo.InvariantInfo;
base_exporters_table = new Dictionary<Type, ExporterFunc> ();
custom_exporters_table = new Dictionary<Type, ExporterFunc> ();
base_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
custom_importers_table = new Dictionary<Type,
IDictionary<Type, ImporterFunc>> ();
RegisterBaseExporters ();
RegisterBaseImporters ();
}
#endregion
#region Private Methods
private static void AddArrayMetadata (Type type)
{
if (array_metadata.ContainsKey (type))
return;
ArrayMetadata data = new ArrayMetadata ();
data.IsArray = type.IsArray;
#if WINDOWS_UWP
if (typeof(IList).IsAssignableFrom(type) && type.GetTypeInfo().IsClass)
#else
if (type.GetInterface ("System.Collections.IList") != null)
#endif
data.IsList = true;
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name != "Item")
continue;
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (int))
data.ElementType = p_info.PropertyType;
}
lock (array_metadata_lock) {
try {
array_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddObjectMetadata (Type type)
{
if (object_metadata.ContainsKey (type))
return;
ObjectMetadata data = new ObjectMetadata ();
#if WINDOWS_UWP
if (typeof(IDictionary).IsAssignableFrom(type) && type.GetTypeInfo().IsClass)
#else
if (type.GetInterface ("System.Collections.IDictionary") != null)
#endif
data.IsDictionary = true;
data.Properties = new Dictionary<string, PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item") {
ParameterInfo[] parameters = p_info.GetIndexParameters ();
if (parameters.Length != 1)
continue;
if (parameters[0].ParameterType == typeof (string))
data.ElementType = p_info.PropertyType;
continue;
}
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.Type = p_info.PropertyType;
data.Properties.Add (p_info.Name, p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
p_data.Type = f_info.FieldType;
data.Properties.Add (f_info.Name, p_data);
}
lock (object_metadata_lock) {
try {
object_metadata.Add (type, data);
} catch (ArgumentException) {
return;
}
}
}
private static void AddTypeProperties (Type type)
{
if (type_properties.ContainsKey (type))
return;
IList<PropertyMetadata> props = new List<PropertyMetadata> ();
foreach (PropertyInfo p_info in type.GetProperties ()) {
if (p_info.Name == "Item")
continue;
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = p_info;
p_data.IsField = false;
props.Add (p_data);
}
foreach (FieldInfo f_info in type.GetFields ()) {
PropertyMetadata p_data = new PropertyMetadata ();
p_data.Info = f_info;
p_data.IsField = true;
props.Add (p_data);
}
lock (type_properties_lock) {
try {
type_properties.Add (type, props);
} catch (ArgumentException) {
return;
}
}
}
private static MethodInfo GetConvOp (Type t1, Type t2)
{
lock (conv_ops_lock) {
if (! conv_ops.ContainsKey (t1))
conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ());
}
if (conv_ops[t1].ContainsKey (t2))
return conv_ops[t1][t2];
MethodInfo op = t1.GetMethod (
"op_Implicit", new Type[] { t2 });
lock (conv_ops_lock) {
try {
conv_ops[t1].Add (t2, op);
} catch (ArgumentException) {
return conv_ops[t1][t2];
}
}
return op;
}
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null) {
#if WINDOWS_UWP
if (inst_type.GetTypeInfo().IsClass || underlying_type != null)
#elif NETSTANDARD1_5
if (inst_type.IsClass() || underlying_type != null)
#else
if (inst_type.IsClass || underlying_type != null)
#endif
return null;
throw new JsonException (String.Format (
"Can't assign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType ();
if (value_type.IsAssignableFrom (json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
value_type)) {
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer (reader.Value);
}
// Maybe it's an enum
#if WINDOWS_UWP
if (value_type.GetTypeInfo().IsEnum)
#elif NETSTANDARD1_5
if (value_type.IsEnum())
#else
if (value_type.IsEnum)
#endif
return Enum.ToObject (value_type, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (value_type, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// [XtraLife] Try to convert to the expected value type, no matter the original value type
// (not the best way, but better than nothing... should only fail if the value is out of expected type's values range)
try {
if (value_type == typeof(double)) {
double n_double = Convert.ToDouble(reader.Value);
if (double.IsInfinity(n_double) || double.IsNaN(n_double)) {
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2} (gives 'infinity' or 'NaN' result)",
reader.Value, json_type, inst_type));
}
return n_double;
}
else if (value_type == typeof(float)) {
float n_single = Convert.ToSingle(reader.Value);
if (float.IsInfinity(n_single) || float.IsNaN(n_single)) {
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2} (gives 'infinity' or 'NaN' result)",
reader.Value, json_type, inst_type));
}
return n_single;
}
else if (value_type == typeof(long))
return Convert.ToInt64(reader.Value);
else if (value_type == typeof(int))
return Convert.ToInt32(reader.Value);
else if (value_type == typeof(short))
return Convert.ToInt16(reader.Value);
else if (value_type == typeof(bool))
return Convert.ToBoolean(reader.Value);
else if (value_type == typeof(string))
return Convert.ToString(reader.Value);
else if (value_type == typeof(ulong))
return Convert.ToUInt64(reader.Value);
else if (value_type == typeof(uint))
return Convert.ToUInt32(reader.Value);
else if (value_type == typeof(ushort))
return Convert.ToUInt16(reader.Value);
}
catch (Exception e) {
// Unhandled expected value type
if (e is JsonException) {
throw e;
}
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
// No luck
throw new JsonException (String.Format (
"Can't assign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart) {
AddObjectMetadata (value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance (value_type);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey (property)) {
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField) {
((FieldInfo) prop_data.Info).SetValue (
instance, ReadValue (prop_data.Type, reader));
} else {
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue (
instance,
ReadValue (prop_data.Type, reader),
null);
else
ReadValue (prop_data.Type, reader);
}
} else {
if (! t_data.IsDictionary) {
if (! reader.SkipNonMembers) {
throw new JsonException (String.Format (
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
} else {
ReadSkip (reader);
continue;
}
}
((IDictionary) instance).Add (
property, ReadValue (
t_data.ElementType, reader));
}
}
}
return instance;
}
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
private static void ReadSkip (JsonReader reader)
{
ToWrapper (
delegate { return new JsonMockWrapper (); }, reader);
}
private static void RegisterBaseExporters ()
{
base_exporters_table[typeof (byte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((byte) obj));
};
base_exporters_table[typeof (char)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((char) obj));
};
base_exporters_table[typeof (DateTime)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToString ((DateTime) obj,
datetime_format));
};
base_exporters_table[typeof (decimal)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((decimal) obj);
};
base_exporters_table[typeof (sbyte)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((sbyte) obj));
};
base_exporters_table[typeof (short)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((short) obj));
};
base_exporters_table[typeof (ushort)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToInt32 ((ushort) obj));
};
base_exporters_table[typeof (uint)] =
delegate (object obj, JsonWriter writer) {
writer.Write (Convert.ToUInt64 ((uint) obj));
};
base_exporters_table[typeof (ulong)] =
delegate (object obj, JsonWriter writer) {
writer.Write ((ulong) obj);
};
}
private static void RegisterBaseImporters ()
{
ImporterFunc importer;
importer = delegate (object input) {
return Convert.ToByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (byte), importer);
importer = delegate (object input) {
return Convert.ToUInt64 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ulong), importer);
importer = delegate (object input) {
return Convert.ToInt64((int)input);
};
RegisterImporter(base_importers_table, typeof(int),
typeof(long), importer);
importer = delegate (object input) {
return Convert.ToSByte ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (sbyte), importer);
importer = delegate (object input) {
return Convert.ToInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (short), importer);
importer = delegate (object input) {
return Convert.ToUInt16 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (ushort), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToSingle ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (float), importer);
importer = delegate (object input) {
return Convert.ToDouble ((int) input);
};
RegisterImporter (base_importers_table, typeof (int),
typeof (double), importer);
importer = delegate (object input) {
return Convert.ToDecimal ((double) input);
};
RegisterImporter (base_importers_table, typeof (double),
typeof (decimal), importer);
importer = delegate (object input) {
return Convert.ToUInt32 ((long) input);
};
RegisterImporter (base_importers_table, typeof (long),
typeof (uint), importer);
importer = delegate (object input) {
return Convert.ToChar ((string) input);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (char), importer);
importer = delegate (object input) {
return Convert.ToDateTime ((string) input, datetime_format);
};
RegisterImporter (base_importers_table, typeof (string),
typeof (DateTime), importer);
importer = delegate (object input) {
return DateTimeOffset.Parse((string)input, datetime_format);
};
RegisterImporter(base_importers_table, typeof(string),
typeof(DateTimeOffset), importer);
}
private static void RegisterImporter (
IDictionary<Type, IDictionary<Type, ImporterFunc>> table,
Type json_type, Type value_type, ImporterFunc importer)
{
if (! table.ContainsKey (json_type))
table.Add (json_type, new Dictionary<Type, ImporterFunc> ());
table[json_type][value_type] = importer;
}
private static void WriteValue (object obj, JsonWriter writer,
bool writer_is_private,
int depth)
{
if (depth > max_nesting_depth)
throw new JsonException (
String.Format ("Max allowed object depth reached while " +
"trying to export from type {0}",
obj.GetType ()));
if (obj == null) {
writer.Write (null);
return;
}
if (obj is IJsonWrapper) {
if (writer_is_private)
writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ());
else
((IJsonWrapper) obj).ToJson (writer);
return;
}
if (obj is String) {
writer.Write ((string) obj);
return;
}
// [XtraLife] Add missing float write...
if (obj is Single) {
writer.Write ((float) obj);
return;
}
if (obj is Double) {
writer.Write ((double) obj);
return;
}
if (obj is Int32) {
writer.Write ((int) obj);
return;
}
if (obj is Boolean) {
writer.Write ((bool) obj);
return;
}
if (obj is Int64) {
writer.Write ((long) obj);
return;
}
if (obj is Array) {
writer.WriteArrayStart ();
foreach (object elem in (Array) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IList) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteValue (elem, writer, writer_is_private, depth + 1);
writer.WriteArrayEnd ();
return;
}
if (obj is IDictionary) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in (IDictionary) obj) {
writer.WritePropertyName ((string) entry.Key);
WriteValue (entry.Value, writer, writer_is_private,
depth + 1);
}
writer.WriteObjectEnd ();
return;
}
Type obj_type = obj.GetType ();
// See if there's a custom exporter for the object
if (custom_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = custom_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// If not, maybe there's a base exporter
if (base_exporters_table.ContainsKey (obj_type)) {
ExporterFunc exporter = base_exporters_table[obj_type];
exporter (obj, writer);
return;
}
// Last option, let's see if it's an enum
if (obj is Enum) {
Type e_type = Enum.GetUnderlyingType (obj_type);
if (e_type == typeof (long)
|| e_type == typeof (uint)
|| e_type == typeof (ulong))
writer.Write ((ulong) obj);
else
writer.Write ((int) obj);
return;
}
// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();
foreach (PropertyMetadata p_data in props) {
// [XtraLife] Skip object write if it has the [SkipToJson] attribute...
#if WINDOWS_UWP
IEnumerable<Attribute> attribs = p_data.Info.GetCustomAttributes<SkipToJson>();
if (attribs.GetEnumerator().MoveNext())
#else
if (p_data.Info.GetCustomAttributes(typeof(SkipToJson), false).Length > 0)
#endif
continue;
// [XtraLife] Write object with its ToString() if it has the [SimpleToJson] attribute...
#if WINDOWS_UWP
IEnumerable<Attribute> simpleToJsonAttribs = p_data.Info.GetCustomAttributes<SimpleToJson>();
if (simpleToJsonAttribs.GetEnumerator().MoveNext()) {
#else
if (p_data.Info.GetCustomAttributes(typeof(SimpleToJson), false).Length > 0) {
#endif
writer.WritePropertyName (p_data.Info.Name);
object fieldValue = ((FieldInfo) p_data.Info).GetValue (obj);
WriteValue (fieldValue != null ? fieldValue.ToString () : null,
writer, writer_is_private, depth + 1);
continue;
}
if (p_data.IsField) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (((FieldInfo) p_data.Info).GetValue (obj),
writer, writer_is_private, depth + 1);
}
else {
PropertyInfo p_info = (PropertyInfo) p_data.Info;
if (p_info.CanRead) {
writer.WritePropertyName (p_data.Info.Name);
WriteValue (p_info.GetValue (obj, null),
writer, writer_is_private, depth + 1);
}
}
}
writer.WriteObjectEnd ();
}
#endregion
public static string ToJson (object obj)
{
lock (static_writer_lock) {
static_writer.Reset ();
WriteValue (obj, static_writer, true, 0);
return static_writer.ToString ();
}
}
public static void ToJson (object obj, JsonWriter writer)
{
WriteValue (obj, writer, false, 0);
}
public static JsonData ToObject (JsonReader reader)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, reader);
}
public static JsonData ToObject (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json_reader);
}
public static JsonData ToObject (string json)
{
return (JsonData) ToWrapper (
delegate { return new JsonData (); }, json);
}
public static T ToObject<T> (JsonReader reader)
{
return (T) ReadValue (typeof (T), reader);
}
public static T ToObject<T> (TextReader reader)
{
JsonReader json_reader = new JsonReader (reader);
return (T) ReadValue (typeof (T), json_reader);
}
public static T ToObject<T> (string json)
{
JsonReader reader = new JsonReader (json);
return (T) ReadValue (typeof (T), reader);
}
public static object ToObject(string json, Type ConvertType )
{
JsonReader reader = new JsonReader(json);
return ReadValue(ConvertType, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
JsonReader reader)
{
return ReadValue (factory, reader);
}
public static IJsonWrapper ToWrapper (WrapperFactory factory,
string json)
{
JsonReader reader = new JsonReader (json);
return ReadValue (factory, reader);
}
public static void RegisterExporter<T> (ExporterFunc<T> exporter)
{
ExporterFunc exporter_wrapper =
delegate (object obj, JsonWriter writer) {
exporter ((T) obj, writer);
};
custom_exporters_table[typeof (T)] = exporter_wrapper;
}
public static void RegisterImporter<TJson, TValue> (
ImporterFunc<TJson, TValue> importer)
{
ImporterFunc importer_wrapper =
delegate (object input) {
return importer ((TJson) input);
};
RegisterImporter (custom_importers_table, typeof (TJson),
typeof (TValue), importer_wrapper);
}
public static void UnregisterExporters ()
{
custom_exporters_table.Clear ();
}
public static void UnregisterImporters ()
{
custom_importers_table.Clear ();
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
// ReSharper disable once CheckNamespace
namespace Fluent
{
using System.Windows.Input;
using System.Windows.Media;
using Fluent.Extensions;
using Fluent.Helpers;
using Fluent.Internal.KnownBoxes;
//using WindowChrome = ControlzEx.Microsoft.Windows.Shell.WindowChrome;
using WindowChrome = Microsoft.Windows.Shell.WindowChrome;
/// <summary>
/// Represents title bar
/// </summary>
[StyleTypedProperty(Property = nameof(ItemContainerStyle), StyleTargetType = typeof(RibbonContextualTabGroup))]
[TemplatePart(Name = "PART_QuickAccessToolbarHolder", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_HeaderHolder", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "PART_ItemsContainer", Type = typeof(Panel))]
public class RibbonTitleBar : HeaderedItemsControl
{
#region Fields
// Quick access toolbar holder
private FrameworkElement quickAccessToolbarHolder;
// Header holder
private FrameworkElement headerHolder;
// Items container
private Panel itemsContainer;
// Quick access toolbar rect
private Rect quickAccessToolbarRect;
// Header rect
private Rect headerRect;
// Items rect
private Rect itemsRect;
#endregion
#region Properties
/// <summary>
/// Gets or sets quick access toolbar
/// </summary>
public FrameworkElement QuickAccessToolBar
{
get { return (FrameworkElement)this.GetValue(QuickAccessToolBarProperty); }
set { this.SetValue(QuickAccessToolBarProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for QuickAccessToolBar. This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty QuickAccessToolBarProperty =
DependencyProperty.Register(nameof(QuickAccessToolBar), typeof(UIElement), typeof(RibbonTitleBar), new PropertyMetadata(OnQuickAccessToolbarChanged));
// Handles QuickAccessToolBar property chages
private static void OnQuickAccessToolbarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var titleBar = (RibbonTitleBar)d;
titleBar.ForceMeasureAndArrange();
}
/// <summary>
/// Gets or sets header alignment
/// </summary>
public HorizontalAlignment HeaderAlignment
{
get { return (HorizontalAlignment)this.GetValue(HeaderAlignmentProperty); }
set { this.SetValue(HeaderAlignmentProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for HeaderAlignment. This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty HeaderAlignmentProperty =
DependencyProperty.Register(nameof(HeaderAlignment), typeof(HorizontalAlignment), typeof(RibbonTitleBar), new PropertyMetadata(HorizontalAlignment.Center));
/// <summary>
/// Defines whether title bar is collapsed
/// </summary>
public bool IsCollapsed
{
get { return (bool)this.GetValue(IsCollapsedProperty); }
set { this.SetValue(IsCollapsedProperty, value); }
}
/// <summary>
/// DependencyProperty for <see cref="IsCollapsed"/>
/// </summary>
public static readonly DependencyProperty IsCollapsedProperty =
DependencyProperty.Register(nameof(IsCollapsed), typeof(bool), typeof(RibbonTitleBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
private bool isAtLeastOneRequiredControlPresent;
/// <summary>
/// Using a DependencyProperty as the backing store for HideContextTabs. This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty HideContextTabsProperty =
DependencyProperty.Register(nameof(HideContextTabs), typeof(bool), typeof(RibbonTitleBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
/// <summary>
/// Gets or sets whether context tabs are hidden.
/// </summary>
public bool HideContextTabs
{
get { return (bool)this.GetValue(HideContextTabsProperty); }
set { this.SetValue(HideContextTabsProperty, value); }
}
#endregion
#region Initialize
/// <summary>
/// Static constructor
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810")]
static RibbonTitleBar()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(RibbonTitleBar), new FrameworkPropertyMetadata(typeof(RibbonTitleBar)));
HeaderProperty.OverrideMetadata(typeof(RibbonTitleBar), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure));
}
/// <summary>
/// Creates a new instance.
/// </summary>
public RibbonTitleBar()
{
WindowChrome.SetIsHitTestVisibleInChrome(this, true);
}
#endregion
#region Overrides
/// <inheritdoc />
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
var baseResult = base.HitTestCore(hitTestParameters);
if (baseResult == null)
{
return new PointHitTestResult(this, hitTestParameters.HitPoint);
}
return baseResult;
}
/// <inheritdoc />
protected override void OnMouseRightButtonUp(MouseButtonEventArgs e)
{
base.OnMouseRightButtonUp(e);
if (e.Handled
|| this.IsMouseDirectlyOver == false)
{
return;
}
WindowSteeringHelper.ShowSystemMenu(this, e);
}
/// <inheritdoc />
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
if (e.Handled)
{
return;
}
// Contextual groups shall handle mouse events
if (e.Source is RibbonContextualGroupsContainer
|| e.Source is RibbonContextualTabGroup)
{
return;
}
WindowSteeringHelper.HandleMouseLeftButtonDown(e, true, true);
}
/// <summary>
/// Creates or identifies the element that is used to display the given item.
/// </summary>
/// <returns>The element that is used to display the given item.</returns>
protected override DependencyObject GetContainerForItemOverride()
{
return new RibbonContextualTabGroup();
}
/// <summary>
/// Determines if the specified item is (or is eligible to be) its own container.
/// </summary>
/// <param name="item"> The item to check.</param>
/// <returns>true if the item is (or is eligible to be) its own container; otherwise, false.</returns>
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is RibbonContextualTabGroup;
}
/// <summary>
/// When overridden in a derived class, is invoked whenever application code or internal processes
/// call System.Windows.FrameworkElement.ApplyTemplate().
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.quickAccessToolbarHolder = this.GetTemplateChild("PART_QuickAccessToolbarHolder") as FrameworkElement;
this.headerHolder = this.GetTemplateChild("PART_HeaderHolder") as FrameworkElement;
this.itemsContainer = this.GetTemplateChild("PART_ItemsContainer") as Panel;
this.isAtLeastOneRequiredControlPresent = this.quickAccessToolbarHolder != null
|| this.headerHolder != null
|| this.itemsContainer != null;
if (this.quickAccessToolbarHolder != null)
{
WindowChrome.SetIsHitTestVisibleInChrome(this.quickAccessToolbarHolder, true);
}
}
/// <summary>
/// Called to remeasure a control.
/// </summary>
/// <param name="constraint">The maximum size that the method can return.</param>
/// <returns>The size of the control, up to the maximum specified by constraint.</returns>
protected override Size MeasureOverride(Size constraint)
{
if (this.isAtLeastOneRequiredControlPresent == false)
{
return base.MeasureOverride(constraint);
}
var resultSize = constraint;
if (double.IsPositiveInfinity(resultSize.Width)
|| double.IsPositiveInfinity(resultSize.Height))
{
resultSize = base.MeasureOverride(resultSize);
}
this.Update(resultSize);
this.itemsContainer.Measure(this.itemsRect.Size);
this.headerHolder.Measure(this.headerRect.Size);
this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size);
var maxHeight = Math.Max(Math.Max(this.itemsRect.Height, this.headerRect.Height), this.quickAccessToolbarRect.Height);
var width = this.itemsRect.Width + this.headerRect.Width + this.quickAccessToolbarRect.Width;
return new Size(width, maxHeight);
}
/// <summary>
/// Called to arrange and size the content of a System.Windows.Controls.Control object.
/// </summary>
/// <param name="arrangeBounds">The computed size that is used to arrange the content.</param>
/// <returns>The size of the control.</returns>
protected override Size ArrangeOverride(Size arrangeBounds)
{
if (this.isAtLeastOneRequiredControlPresent == false)
{
return base.ArrangeOverride(arrangeBounds);
}
this.itemsContainer.Arrange(this.itemsRect);
this.headerHolder.Arrange(this.headerRect);
this.quickAccessToolbarHolder.Arrange(this.quickAccessToolbarRect);
this.EnsureCorrectLayoutAfterArrange();
return arrangeBounds;
}
#endregion
#region Private methods
/// <summary>
/// Sometimes the relative position only changes after the arrange phase.
/// To compensate such sitiations we issue a second layout pass by invalidating our measure.
/// This situation can occur if, for example, the icon of a ribbon window has it's visibility changed.
/// </summary>
private void EnsureCorrectLayoutAfterArrange()
{
var currentRelativePosition = this.GetCurrentRelativePosition();
this.RunInDispatcherAsync(() => this.CheckPosition(currentRelativePosition, this.GetCurrentRelativePosition()));
}
private void CheckPosition(Point previousRelativePosition, Point currentRelativePositon)
{
if (previousRelativePosition != currentRelativePositon)
{
this.InvalidateMeasure();
}
}
private Point GetCurrentRelativePosition()
{
var parentUIElement = this.Parent as UIElement;
if (parentUIElement == null)
{
return new Point();
}
return this.TranslatePoint(new Point(), parentUIElement);
}
// Update items size and positions
private void Update(Size constraint)
{
var visibleGroups = this.Items.OfType<RibbonContextualTabGroup>()
.Where(group => group.InnerVisibility == Visibility.Visible && group.Items.Count > 0)
.ToList();
var infinity = new Size(double.PositiveInfinity, double.PositiveInfinity);
var canRibbonTabControlScroll = false;
// Defensively try to find out if the RibbonTabControl can scroll
if (visibleGroups.Count > 0)
{
var firstVisibleItem = visibleGroups.First().FirstVisibleItem;
if (firstVisibleItem?.Parent != null)
{
canRibbonTabControlScroll = ((RibbonTabControl)firstVisibleItem.Parent).CanScroll;
}
}
if (this.IsCollapsed)
{
// Collapse QuickAccessToolbar
this.quickAccessToolbarRect = new Rect(0, 0, 0, 0);
// Collapse itemRect
this.itemsRect = new Rect(0, 0, 0, 0);
this.headerHolder.Measure(new Size(constraint.Width, constraint.Height));
this.headerRect = new Rect(0, 0, this.headerHolder.DesiredSize.Width, constraint.Height);
}
else if (visibleGroups.Count == 0
|| canRibbonTabControlScroll)
{
// Collapse itemRect
this.itemsRect = new Rect(0, 0, 0, 0);
// Set quick launch toolbar and header position and size
this.quickAccessToolbarHolder.Measure(infinity);
if (constraint.Width <= this.quickAccessToolbarHolder.DesiredSize.Width + 50)
{
this.quickAccessToolbarRect = new Rect(0, 0, Math.Max(0, constraint.Width - 50), this.quickAccessToolbarHolder.DesiredSize.Height);
this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size);
}
if (constraint.Width > this.quickAccessToolbarHolder.DesiredSize.Width + 50)
{
this.quickAccessToolbarRect = new Rect(0, 0, this.quickAccessToolbarHolder.DesiredSize.Width, this.quickAccessToolbarHolder.DesiredSize.Height);
this.headerHolder.Measure(infinity);
var allTextWidth = constraint.Width - this.quickAccessToolbarHolder.DesiredSize.Width;
if (this.HeaderAlignment == HorizontalAlignment.Left)
{
this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width, 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height);
}
else if (this.HeaderAlignment == HorizontalAlignment.Center)
{
this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidth / 2 - this.headerHolder.DesiredSize.Width / 2), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height);
}
else if (this.HeaderAlignment == HorizontalAlignment.Right)
{
this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidth - this.headerHolder.DesiredSize.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height);
}
else if (this.HeaderAlignment == HorizontalAlignment.Stretch)
{
this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width, 0, allTextWidth, constraint.Height);
}
}
else
{
this.headerRect = new Rect(Math.Max(0, constraint.Width - 50), 0, 50, constraint.Height);
}
}
else
{
var pointZero = new Point();
// get initial StartX value
var startX = visibleGroups.First().FirstVisibleItem.TranslatePoint(pointZero, this).X;
var endX = 0D;
//Get minimum x point (workaround)
foreach (var group in visibleGroups)
{
var currentStartX = group.FirstVisibleItem.TranslatePoint(pointZero, this).X;
if (currentStartX < startX)
{
startX = currentStartX;
}
var lastItem = group.LastVisibleItem;
var currentEndX = lastItem.TranslatePoint(new Point(lastItem.DesiredSize.Width, 0), this).X;
if (currentEndX > endX)
{
endX = currentEndX;
}
}
// Ensure that startX and endX are never negative
startX = Math.Max(0, startX);
endX = Math.Max(0, endX);
// Ensure that startX respect min width of QuickAccessToolBar
startX = Math.Max(startX, this.QuickAccessToolBar?.MinWidth ?? 0);
// Set contextual groups position and size
this.itemsContainer.Measure(infinity);
var itemsRectWidth = Math.Min(this.itemsContainer.DesiredSize.Width, Math.Max(0, Math.Min(endX, constraint.Width) - startX));
this.itemsRect = new Rect(startX, 0, itemsRectWidth, constraint.Height);
// Set quick launch toolbar position and size
this.quickAccessToolbarHolder.Measure(infinity);
var quickAccessToolbarWidth = this.quickAccessToolbarHolder.DesiredSize.Width;
this.quickAccessToolbarRect = new Rect(0, 0, Math.Min(quickAccessToolbarWidth, startX), this.quickAccessToolbarHolder.DesiredSize.Height);
if (quickAccessToolbarWidth > startX)
{
this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size);
this.quickAccessToolbarRect = new Rect(0, 0, this.quickAccessToolbarHolder.DesiredSize.Width, this.quickAccessToolbarHolder.DesiredSize.Height);
quickAccessToolbarWidth = this.quickAccessToolbarHolder.DesiredSize.Width;
}
// Set header
this.headerHolder.Measure(infinity);
switch (this.HeaderAlignment)
{
case HorizontalAlignment.Left:
{
if (startX - quickAccessToolbarWidth > 150)
{
var allTextWidth = startX - quickAccessToolbarWidth;
this.headerRect = new Rect(this.quickAccessToolbarRect.Width, 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height);
}
else
{
var allTextWidth = Math.Max(0, constraint.Width - endX);
this.headerRect = new Rect(Math.Min(endX, constraint.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height);
}
}
break;
case HorizontalAlignment.Center:
{
var allTextWidthRight = Math.Max(0, constraint.Width - endX);
var allTextWidthLeft = Math.Max(0, startX - quickAccessToolbarWidth);
var fitsRightButNotLeft = allTextWidthRight >= this.headerHolder.DesiredSize.Width && allTextWidthLeft < this.headerHolder.DesiredSize.Width;
if (((startX - quickAccessToolbarWidth < 150 || fitsRightButNotLeft) && (startX - quickAccessToolbarWidth > 0) && (startX - quickAccessToolbarWidth < constraint.Width - endX)) || (endX < constraint.Width / 2))
{
this.headerRect = new Rect(Math.Min(Math.Max(endX, constraint.Width / 2 - this.headerHolder.DesiredSize.Width / 2), constraint.Width), 0, Math.Min(allTextWidthRight, this.headerHolder.DesiredSize.Width), constraint.Height);
}
else
{
this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidthLeft / 2 - this.headerHolder.DesiredSize.Width / 2), 0, Math.Min(allTextWidthLeft, this.headerHolder.DesiredSize.Width), constraint.Height);
}
}
break;
case HorizontalAlignment.Right:
{
if (startX - quickAccessToolbarWidth > 150)
{
var allTextWidth = Math.Max(0, startX - quickAccessToolbarWidth);
this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidth - this.headerHolder.DesiredSize.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height);
}
else
{
var allTextWidth = Math.Max(0, constraint.Width - endX);
this.headerRect = new Rect(Math.Min(Math.Max(endX, constraint.Width - this.headerHolder.DesiredSize.Width), constraint.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height);
}
}
break;
case HorizontalAlignment.Stretch:
{
if (startX - quickAccessToolbarWidth > 150)
{
var allTextWidth = startX - quickAccessToolbarWidth;
this.headerRect = new Rect(this.quickAccessToolbarRect.Width, 0, allTextWidth, constraint.Height);
}
else
{
var allTextWidth = Math.Max(0, constraint.Width - endX);
this.headerRect = new Rect(Math.Min(endX, constraint.Width), 0, allTextWidth, constraint.Height);
}
}
break;
}
}
this.headerRect.Width = this.headerRect.Width + 2;
}
#endregion
}
}
| |
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 Northwind
{
/// <summary>
/// Strongly-typed collection for the Supplier class.
/// </summary>
[Serializable]
public partial class SupplierCollection : ActiveList<Supplier, SupplierCollection>
{
public SupplierCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SupplierCollection</returns>
public SupplierCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Supplier 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 Suppliers table.
/// </summary>
[Serializable]
public partial class Supplier : ActiveRecord<Supplier>, IActiveRecord
{
#region .ctors and Default Settings
public Supplier()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Supplier(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Supplier(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Supplier(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("Suppliers", TableType.Table, DataService.GetInstance("Northwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarSupplierID = new TableSchema.TableColumn(schema);
colvarSupplierID.ColumnName = "SupplierID";
colvarSupplierID.DataType = DbType.Int32;
colvarSupplierID.MaxLength = 0;
colvarSupplierID.AutoIncrement = true;
colvarSupplierID.IsNullable = false;
colvarSupplierID.IsPrimaryKey = true;
colvarSupplierID.IsForeignKey = false;
colvarSupplierID.IsReadOnly = false;
colvarSupplierID.DefaultSetting = @"";
colvarSupplierID.ForeignKeyTableName = "";
schema.Columns.Add(colvarSupplierID);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = false;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
colvarCompanyName.DefaultSetting = @"";
colvarCompanyName.ForeignKeyTableName = "";
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema);
colvarContactName.ColumnName = "ContactName";
colvarContactName.DataType = DbType.String;
colvarContactName.MaxLength = 30;
colvarContactName.AutoIncrement = false;
colvarContactName.IsNullable = true;
colvarContactName.IsPrimaryKey = false;
colvarContactName.IsForeignKey = false;
colvarContactName.IsReadOnly = false;
colvarContactName.DefaultSetting = @"";
colvarContactName.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactName);
TableSchema.TableColumn colvarContactTitle = new TableSchema.TableColumn(schema);
colvarContactTitle.ColumnName = "ContactTitle";
colvarContactTitle.DataType = DbType.String;
colvarContactTitle.MaxLength = 30;
colvarContactTitle.AutoIncrement = false;
colvarContactTitle.IsNullable = true;
colvarContactTitle.IsPrimaryKey = false;
colvarContactTitle.IsForeignKey = false;
colvarContactTitle.IsReadOnly = false;
colvarContactTitle.DefaultSetting = @"";
colvarContactTitle.ForeignKeyTableName = "";
schema.Columns.Add(colvarContactTitle);
TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema);
colvarAddress.ColumnName = "Address";
colvarAddress.DataType = DbType.String;
colvarAddress.MaxLength = 60;
colvarAddress.AutoIncrement = false;
colvarAddress.IsNullable = true;
colvarAddress.IsPrimaryKey = false;
colvarAddress.IsForeignKey = false;
colvarAddress.IsReadOnly = false;
colvarAddress.DefaultSetting = @"";
colvarAddress.ForeignKeyTableName = "";
schema.Columns.Add(colvarAddress);
TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema);
colvarCity.ColumnName = "City";
colvarCity.DataType = DbType.String;
colvarCity.MaxLength = 15;
colvarCity.AutoIncrement = false;
colvarCity.IsNullable = true;
colvarCity.IsPrimaryKey = false;
colvarCity.IsForeignKey = false;
colvarCity.IsReadOnly = false;
colvarCity.DefaultSetting = @"";
colvarCity.ForeignKeyTableName = "";
schema.Columns.Add(colvarCity);
TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema);
colvarRegion.ColumnName = "Region";
colvarRegion.DataType = DbType.String;
colvarRegion.MaxLength = 15;
colvarRegion.AutoIncrement = false;
colvarRegion.IsNullable = true;
colvarRegion.IsPrimaryKey = false;
colvarRegion.IsForeignKey = false;
colvarRegion.IsReadOnly = false;
colvarRegion.DefaultSetting = @"";
colvarRegion.ForeignKeyTableName = "";
schema.Columns.Add(colvarRegion);
TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema);
colvarPostalCode.ColumnName = "PostalCode";
colvarPostalCode.DataType = DbType.String;
colvarPostalCode.MaxLength = 10;
colvarPostalCode.AutoIncrement = false;
colvarPostalCode.IsNullable = true;
colvarPostalCode.IsPrimaryKey = false;
colvarPostalCode.IsForeignKey = false;
colvarPostalCode.IsReadOnly = false;
colvarPostalCode.DefaultSetting = @"";
colvarPostalCode.ForeignKeyTableName = "";
schema.Columns.Add(colvarPostalCode);
TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema);
colvarCountry.ColumnName = "Country";
colvarCountry.DataType = DbType.String;
colvarCountry.MaxLength = 15;
colvarCountry.AutoIncrement = false;
colvarCountry.IsNullable = true;
colvarCountry.IsPrimaryKey = false;
colvarCountry.IsForeignKey = false;
colvarCountry.IsReadOnly = false;
colvarCountry.DefaultSetting = @"";
colvarCountry.ForeignKeyTableName = "";
schema.Columns.Add(colvarCountry);
TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema);
colvarPhone.ColumnName = "Phone";
colvarPhone.DataType = DbType.String;
colvarPhone.MaxLength = 24;
colvarPhone.AutoIncrement = false;
colvarPhone.IsNullable = true;
colvarPhone.IsPrimaryKey = false;
colvarPhone.IsForeignKey = false;
colvarPhone.IsReadOnly = false;
colvarPhone.DefaultSetting = @"";
colvarPhone.ForeignKeyTableName = "";
schema.Columns.Add(colvarPhone);
TableSchema.TableColumn colvarFax = new TableSchema.TableColumn(schema);
colvarFax.ColumnName = "Fax";
colvarFax.DataType = DbType.String;
colvarFax.MaxLength = 24;
colvarFax.AutoIncrement = false;
colvarFax.IsNullable = true;
colvarFax.IsPrimaryKey = false;
colvarFax.IsForeignKey = false;
colvarFax.IsReadOnly = false;
colvarFax.DefaultSetting = @"";
colvarFax.ForeignKeyTableName = "";
schema.Columns.Add(colvarFax);
TableSchema.TableColumn colvarHomePage = new TableSchema.TableColumn(schema);
colvarHomePage.ColumnName = "HomePage";
colvarHomePage.DataType = DbType.String;
colvarHomePage.MaxLength = 1073741823;
colvarHomePage.AutoIncrement = false;
colvarHomePage.IsNullable = true;
colvarHomePage.IsPrimaryKey = false;
colvarHomePage.IsForeignKey = false;
colvarHomePage.IsReadOnly = false;
colvarHomePage.DefaultSetting = @"";
colvarHomePage.ForeignKeyTableName = "";
schema.Columns.Add(colvarHomePage);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Northwind"].AddSchema("Suppliers",schema);
}
}
#endregion
#region Props
[XmlAttribute("SupplierID")]
[Bindable(true)]
public int SupplierID
{
get { return GetColumnValue<int>(Columns.SupplierID); }
set { SetColumnValue(Columns.SupplierID, value); }
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get { return GetColumnValue<string>(Columns.CompanyName); }
set { SetColumnValue(Columns.CompanyName, value); }
}
[XmlAttribute("ContactName")]
[Bindable(true)]
public string ContactName
{
get { return GetColumnValue<string>(Columns.ContactName); }
set { SetColumnValue(Columns.ContactName, value); }
}
[XmlAttribute("ContactTitle")]
[Bindable(true)]
public string ContactTitle
{
get { return GetColumnValue<string>(Columns.ContactTitle); }
set { SetColumnValue(Columns.ContactTitle, value); }
}
[XmlAttribute("Address")]
[Bindable(true)]
public string Address
{
get { return GetColumnValue<string>(Columns.Address); }
set { SetColumnValue(Columns.Address, value); }
}
[XmlAttribute("City")]
[Bindable(true)]
public string City
{
get { return GetColumnValue<string>(Columns.City); }
set { SetColumnValue(Columns.City, value); }
}
[XmlAttribute("Region")]
[Bindable(true)]
public string Region
{
get { return GetColumnValue<string>(Columns.Region); }
set { SetColumnValue(Columns.Region, value); }
}
[XmlAttribute("PostalCode")]
[Bindable(true)]
public string PostalCode
{
get { return GetColumnValue<string>(Columns.PostalCode); }
set { SetColumnValue(Columns.PostalCode, value); }
}
[XmlAttribute("Country")]
[Bindable(true)]
public string Country
{
get { return GetColumnValue<string>(Columns.Country); }
set { SetColumnValue(Columns.Country, value); }
}
[XmlAttribute("Phone")]
[Bindable(true)]
public string Phone
{
get { return GetColumnValue<string>(Columns.Phone); }
set { SetColumnValue(Columns.Phone, value); }
}
[XmlAttribute("Fax")]
[Bindable(true)]
public string Fax
{
get { return GetColumnValue<string>(Columns.Fax); }
set { SetColumnValue(Columns.Fax, value); }
}
[XmlAttribute("HomePage")]
[Bindable(true)]
public string HomePage
{
get { return GetColumnValue<string>(Columns.HomePage); }
set { SetColumnValue(Columns.HomePage, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
public Northwind.ProductCollection Products()
{
return new Northwind.ProductCollection().Where(Product.Columns.SupplierID, SupplierID).Load();
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCompanyName,string varContactName,string varContactTitle,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varPhone,string varFax,string varHomePage)
{
Supplier item = new Supplier();
item.CompanyName = varCompanyName;
item.ContactName = varContactName;
item.ContactTitle = varContactTitle;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.Phone = varPhone;
item.Fax = varFax;
item.HomePage = varHomePage;
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 varSupplierID,string varCompanyName,string varContactName,string varContactTitle,string varAddress,string varCity,string varRegion,string varPostalCode,string varCountry,string varPhone,string varFax,string varHomePage)
{
Supplier item = new Supplier();
item.SupplierID = varSupplierID;
item.CompanyName = varCompanyName;
item.ContactName = varContactName;
item.ContactTitle = varContactTitle;
item.Address = varAddress;
item.City = varCity;
item.Region = varRegion;
item.PostalCode = varPostalCode;
item.Country = varCountry;
item.Phone = varPhone;
item.Fax = varFax;
item.HomePage = varHomePage;
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 SupplierIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CompanyNameColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn ContactNameColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ContactTitleColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn AddressColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn CityColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn RegionColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn PostalCodeColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CountryColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn PhoneColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn FaxColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn HomePageColumn
{
get { return Schema.Columns[11]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string SupplierID = @"SupplierID";
public static string CompanyName = @"CompanyName";
public static string ContactName = @"ContactName";
public static string ContactTitle = @"ContactTitle";
public static string Address = @"Address";
public static string City = @"City";
public static string Region = @"Region";
public static string PostalCode = @"PostalCode";
public static string Country = @"Country";
public static string Phone = @"Phone";
public static string Fax = @"Fax";
public static string HomePage = @"HomePage";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
}
#endregion
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Text;
using System.Xml;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class SQLCtl : System.Windows.Forms.Form
{
DesignXmlDraw _Draw;
string _DataSource;
DataTable _QueryParameters;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private SplitContainer splitContainer1;
private TreeView tvTablesColumns;
private TextBox tbSQL;
private Button bMove;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal SQLCtl(DesignXmlDraw dxDraw, string datasource, string sql, DataTable queryParameters)
{
_Draw = dxDraw;
_DataSource = datasource;
_QueryParameters = queryParameters;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(sql);
}
private void InitValues(string sql)
{
this.tbSQL.Text = sql;
// Fill out the tables, columns and parameters
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
// Get the schema information
List<SqlSchemaInfo> si = DesignerUtility.GetSchemaInfo(_Draw, _DataSource);
if (si != null && si.Count > 0)
{
TreeNode ndRoot = new TreeNode("Tables");
tvTablesColumns.Nodes.Add(ndRoot);
if (si == null) // Nothing to initialize
return;
bool bView = false;
foreach (SqlSchemaInfo ssi in si)
{
if (!bView && ssi.Type == "VIEW")
{ // Switch over to views
ndRoot = new TreeNode("Views");
tvTablesColumns.Nodes.Add(ndRoot);
bView=true;
}
// Add the node to the tree
TreeNode aRoot = new TreeNode(ssi.Name);
ndRoot.Nodes.Add(aRoot);
aRoot.Nodes.Add("");
}
}
// Now do parameters
TreeNode qpRoot = null;
foreach (DataRow dr in _QueryParameters.Rows)
{
if (dr[0] == DBNull.Value || dr[1] == null)
continue;
string pName = (string) dr[0];
if (pName.Length == 0)
continue;
if (qpRoot == null)
{
qpRoot = new TreeNode("Query Parameters");
tvTablesColumns.Nodes.Add(qpRoot);
}
if (pName[0] == '@')
pName = "@" + pName;
// Add the node to the tree
TreeNode aRoot = new TreeNode(pName);
qpRoot.Nodes.Add(aRoot);
}
tvTablesColumns.EndUpdate();
}
internal string SQL
{
get {return tbSQL.Text;}
set {tbSQL.Text = value;}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tvTablesColumns = new System.Windows.Forms.TreeView();
this.tbSQL = new System.Windows.Forms.TextBox();
this.bMove = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.Controls.Add(this.bOK);
this.panel1.Controls.Add(this.bCancel);
this.panel1.Location = new System.Drawing.Point(0, 215);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(468, 40);
this.panel1.TabIndex = 6;
//
// bOK
//
this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bOK.Location = new System.Drawing.Point(300, 8);
this.bOK.Name = "bOK";
this.bOK.Size = new System.Drawing.Size(75, 23);
this.bOK.TabIndex = 2;
this.bOK.Text = "OK";
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(388, 8);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 3;
this.bCancel.Text = "Cancel";
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tvTablesColumns);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.tbSQL);
this.splitContainer1.Panel2.Controls.Add(this.bMove);
this.splitContainer1.Size = new System.Drawing.Size(468, 215);
this.splitContainer1.SplitterDistance = 123;
this.splitContainer1.TabIndex = 9;
//
// tvTablesColumns
//
this.tvTablesColumns.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvTablesColumns.FullRowSelect = true;
this.tvTablesColumns.Location = new System.Drawing.Point(0, 0);
this.tvTablesColumns.Name = "tvTablesColumns";
this.tvTablesColumns.Size = new System.Drawing.Size(123, 215);
this.tvTablesColumns.TabIndex = 5;
this.tvTablesColumns.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvTablesColumns_BeforeExpand);
//
// tbSQL
//
this.tbSQL.AcceptsReturn = true;
this.tbSQL.AcceptsTab = true;
this.tbSQL.AllowDrop = true;
this.tbSQL.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbSQL.Location = new System.Drawing.Point(37, 0);
this.tbSQL.Multiline = true;
this.tbSQL.Name = "tbSQL";
this.tbSQL.Size = new System.Drawing.Size(299, 215);
this.tbSQL.TabIndex = 10;
//
// bMove
//
this.bMove.Location = new System.Drawing.Point(3, 3);
this.bMove.Name = "bMove";
this.bMove.Size = new System.Drawing.Size(32, 23);
this.bMove.TabIndex = 9;
this.bMove.Text = ">>";
this.bMove.Click += new System.EventHandler(this.bMove_Click);
//
// SQLCtl
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(468, 255);
this.ControlBox = false;
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.panel1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SQLCtl";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "SQL Syntax Helper";
this.panel1.ResumeLayout(false);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void bOK_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void tvTablesColumns_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
{
tvTablesColumns_ExpandTable(e.Node);
}
private void tvTablesColumns_ExpandTable(TreeNode tNode)
{
if (tNode.Parent == null) // Check for Tables or Views
return;
if (tNode.FirstNode.Text != "") // Have we already filled it out?
return;
// Need to obtain the column information for the requested table/view
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
string sql = "SELECT * FROM " + DesignerUtility.NormalizeSqlName(tNode.Text);
List<SqlColumn> tColumns = DesignerUtility.GetSqlColumns(_Draw, _DataSource, sql);
bool bFirstTime=true;
foreach (SqlColumn sc in tColumns)
{
if (bFirstTime)
{
bFirstTime = false;
tNode.FirstNode.Text = sc.Name;
}
else
tNode.Nodes.Add(sc.Name);
}
tvTablesColumns.EndUpdate();
}
private void bMove_Click(object sender, System.EventArgs e)
{
if (tvTablesColumns.SelectedNode == null ||
tvTablesColumns.SelectedNode.Parent == null)
return; // this is the Tables/Views node
TreeNode node = tvTablesColumns.SelectedNode;
string t = node.Text;
if (tbSQL.Text == "")
{
if (node.Parent.Parent == null)
{ // select table; generate full select for table
tvTablesColumns_ExpandTable(node); // make sure we've obtained the columns
StringBuilder sb = new StringBuilder("SELECT ");
TreeNode next = node.FirstNode;
while (true)
{
sb.Append(DesignerUtility.NormalizeSqlName(next.Text));
next = next.NextNode;
if (next == null)
break;
sb.Append(", ");
}
sb.Append(" FROM ");
sb.Append(DesignerUtility.NormalizeSqlName(node.Text));
t = sb.ToString();
}
else
{ // select column; generate select of that column
t = "SELECT " + DesignerUtility.NormalizeSqlName(node.Text) + " FROM " + DesignerUtility.NormalizeSqlName(node.Parent.Text);
}
}
tbSQL.SelectedText = t;
}
}
}
| |
using AVDump3Lib.Processing.BlockConsumers.Matroska.Segment.Tracks;
using BXmlLib;
using BXmlLib.DocTypes.Matroska;
using ExtKnot.StringInvariants;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace AVDump3Lib.Processing.BlockConsumers.Matroska.Segment.Cluster;
public class ClusterSection : Section {
public Dictionary<int, Track> Tracks { get; private set; }
public ClusterSection() { Tracks = new Dictionary<int, Track>(); }
public ulong TimeCodeScale { get; set; }
private long timecode;
public void AddTracks(IEnumerable<TrackEntrySection> tracks) {
foreach(var track in tracks) {
var trackNumber = (int)track.TrackNumber.Value;
if(Tracks.TryGetValue(~trackNumber, out var clusterTrack)) {
var replaceTrack = new Track(trackNumber, track.TrackTimecodeScale ?? 1d, track);
replaceTrack.Timecodes.AddRange(clusterTrack.Timecodes);
Tracks.Add(trackNumber, replaceTrack);
Tracks.Remove(~trackNumber);
} else {
Tracks.Add(trackNumber, new Track(trackNumber, track.TrackTimecodeScale ?? 1d, track));
}
}
}
protected override bool ProcessElement(IBXmlReader reader) {
if(reader.DocElement == MatroskaDocType.SimpleBlock || reader.DocElement == MatroskaDocType.Block) {
MatroskaDocType.RetrieveMatroskaHeaderBlock(reader, out var matroskaBlock);
if(
!Tracks.TryGetValue(matroskaBlock.TrackNumber, out var track) &&
!Tracks.TryGetValue(~matroskaBlock.TrackNumber, out track)
) {
Tracks.Add(~matroskaBlock.TrackNumber, track = new Track(~matroskaBlock.TrackNumber, 1, null));
}
track.Timecodes.Add(new TrackTimecode((ulong)((matroskaBlock.TimeCode + timecode) * track.TimecodeScale * TimeCodeScale), matroskaBlock.FrameCountMinusOne, (int)(reader.Header.DataLength - matroskaBlock.HeaderLength)));
} else if(reader.DocElement == MatroskaDocType.BlockGroup) {
Read(reader);
} else if(reader.DocElement == MatroskaDocType.Timecode) {
timecode = (long)(ulong)reader.RetrieveValue();
} else return false;
return true;
}
protected override void Validate() { }
public override IEnumerator<KeyValuePair<string, object>> GetEnumerator() { yield break; }
public class Track {
private readonly TrackEntrySection? mkvTrack;
public int TrackNumber { get; private set; }
public double TimecodeScale { get; private set; }
public List<TrackTimecode> Timecodes { get; private set; }
public Track(int trackNumber, double timecodeScale, TrackEntrySection? mkvTrack) {
TrackNumber = trackNumber;
TimecodeScale = mkvTrack?.TrackTimecodeScale ?? 1d;
this.mkvTrack = mkvTrack;
Timecodes = new List<TrackTimecode>();
}
public TrackInfo TrackInfo => trackInfo ??= CalcTrackInfo();
private TrackInfo trackInfo;
private TrackInfo? CalcTrackInfo() {
try {
//Hack to get info from subtitles stored CodecPrivate
if(
Timecodes.Count == 0 && mkvTrack?.CodecPrivate != null &&
("S_TEXT/ASS".Equals(mkvTrack.CodecId) || "S_TEXT/SSA".Equals(mkvTrack.CodecId))
) {
ExtractSubtitleInfo();
}
Timecodes.Sort();
var rate = new double[3];
double? minSampleRate = null, maxSampleRate = null;
var oldTC = Timecodes.FirstOrDefault();
int pos = 0, prevPos = 0, prevprevPos;
double maxDiff;
int frames = oldTC.FrameCount;
long trackSize = (mkvTrack?.CodecPrivate?.Length ?? 0) + oldTC.Size;
var sampleRateHistogram = new Dictionary<double, int>();
var bitRateHistogram = new Dictionary<double, int>();
foreach(var timecode in Timecodes.Skip(1)) {
//fps[pos] = 1d / ((timecode.timeCode - oldTC.timeCode) / (double)oldTC.frames / 1000000000d);
rate[pos] = (1000000000d * oldTC.FrameCount) / (timecode.TimeCode - oldTC.TimeCode);
if(!double.IsInfinity(rate[pos]) && !double.IsNaN(rate[pos])) {
if(!sampleRateHistogram.ContainsKey(rate[pos])) sampleRateHistogram[rate[pos]] = 0;
sampleRateHistogram[rate[pos]]++;
}
var bitRate = timecode.Size * 8000000000d / ((uint)timecode.FrameCount * (timecode.TimeCode - oldTC.TimeCode));
if(!double.IsInfinity(bitRate) && !double.IsNaN(bitRate)) {
if(!bitRateHistogram.ContainsKey(bitRate)) bitRateHistogram[bitRate] = 0;
bitRateHistogram[bitRate] += timecode.FrameCount;
}
oldTC = timecode;
prevprevPos = prevPos;
prevPos = pos;
pos = (pos + 1) % 3;
trackSize += timecode.Size;
frames += timecode.FrameCount;
maxDiff = (rate[prevprevPos] + rate[pos] / 2) * 0.1;
if(Math.Abs(rate[prevPos] - rate[prevprevPos]) < maxDiff && Math.Abs(rate[prevPos] - rate[pos]) < maxDiff) {
if(!minSampleRate.HasValue || minSampleRate.Value > rate[prevPos]) minSampleRate = rate[prevPos];
if(!maxSampleRate.HasValue || maxSampleRate.Value < rate[prevPos]) maxSampleRate = rate[prevPos];
}
}
var trackLength = TimeSpan.FromMilliseconds((Timecodes.LastOrDefault().TimeCode - Timecodes.FirstOrDefault().TimeCode) / 1000000);
return new TrackInfo {
SampleRateHistogram = sampleRateHistogram.Select(kvp => new SampleRateCountPair(kvp.Key, kvp.Value)).ToList().AsReadOnly(),
AverageBitrate = (trackSize != 0 && trackLength.Ticks != 0) ? trackSize * 8 / trackLength.TotalSeconds : (double?)null,
AverageSampleRate = (frames != 0 && trackLength.Ticks != 0) ? frames / trackLength.TotalSeconds : (double?)null,
MinSampleRate = minSampleRate,
MaxSampleRate = maxSampleRate,
TrackLength = trackLength,
TrackSize = trackSize,
SampleCount = frames
};
} catch(Exception) { }
return null;
}
private void ExtractSubtitleInfo() {
var assOrSsaContent = Encoding.UTF8.GetString(mkvTrack?.CodecPrivate ?? Array.Empty<byte>());
var eventSectionStart = assOrSsaContent.InvIndexOf("[Events]");
if(eventSectionStart < 0) return;
var formatStart = assOrSsaContent.InvIndexOf("Format:", eventSectionStart);
if(formatStart < 0) return;
formatStart += 7;
var formatEnd = assOrSsaContent.InvIndexOf("\n", formatStart) - 1;
if(formatEnd < 0) return;
var columns = assOrSsaContent[formatStart..formatEnd].InvReplace(" ", "").Split(',');
var startIndex = Array.IndexOf(columns, "Start");
var endIndex = Array.IndexOf(columns, "End");
var lines = assOrSsaContent[(formatEnd + 1)..].Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Split(new[] { ',' }, columns.Length)).ToArray();
foreach(var line in lines) {
Timecodes.Add(new TrackTimecode((ulong)TimeSpan.ParseExact(line[startIndex], @"h\:mm\:ss\.ff", CultureInfo.InvariantCulture).TotalMilliseconds * 1000000, 1, 0));
}
}
}
public class TrackInfo {
public double? AverageBitrate { get; internal set; }
public double? AverageSampleRate { get; internal set; }
public double? MinSampleRate { get; internal set; }
public double? MaxSampleRate { get; internal set; }
public ReadOnlyCollection<SampleRateCountPair> SampleRateHistogram { get; internal set; }
public TimeSpan TrackLength { get; internal set; }
public long TrackSize { get; internal set; }
public int SampleCount { get; internal set; }
//public TrackInfo(ReadOnlyCollection<LaceRateCountPair> laceRateHistogram, double? averageBitrate, double? averageLaceRate, TimeSpan trackLength, long trackSize, int laceCount) {
// AverageBitrate = averageBitrate;
// AverageLaceRate = averageLaceRate;
// TrackLength = trackLength; TrackSize = trackSize; LaceCount = laceCount;
// LaceRateHistogram = laceRateHistogram;
//}
}
public class SampleRateCountPair {
public double SampleRate { get; private set; }
public long Count { get; private set; }
public SampleRateCountPair(double laceRate, long count) { SampleRate = laceRate; Count = count; }
}
public struct TrackTimecode : IComparable<TrackTimecode> {
public ulong TimeCode;
public byte FrameCountMinusOne;
public int Size;
public int FrameCount => FrameCountMinusOne + 1;
public TrackTimecode(ulong timeCode, byte frameCountMinusOne, int size) {
this.FrameCountMinusOne = frameCountMinusOne; this.Size = size; this.TimeCode = timeCode;
}
public int CompareTo(TrackTimecode other) {
return TimeCode.CompareTo(other.TimeCode);
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Content.Shared.Access;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using static Content.Shared.GameObjects.Components.Access.SharedIdCardConsoleComponent;
namespace Content.Client.GameObjects.Components.Access
{
public class IdCardConsoleWindow : SS14Window
{
private readonly Button _privilegedIdButton;
private readonly Button _targetIdButton;
private readonly Label _privilegedIdLabel;
private readonly Label _targetIdLabel;
private readonly Label _fullNameLabel;
private readonly LineEdit _fullNameLineEdit;
private readonly Label _jobTitleLabel;
private readonly LineEdit _jobTitleLineEdit;
private readonly Button _fullNameSaveButton;
private readonly Button _jobTitleSaveButton;
private readonly IdCardConsoleBoundUserInterface _owner;
private readonly Dictionary<string, Button> _accessButtons = new Dictionary<string, Button>();
private string _lastFullName;
private string _lastJobTitle;
protected override Vector2? CustomSize => (650, 270);
public IdCardConsoleWindow(IdCardConsoleBoundUserInterface owner, IPrototypeManager prototypeManager)
{
_owner = owner;
var vBox = new VBoxContainer();
vBox.AddChild(new GridContainer
{
Columns = 3,
Children =
{
new Label {Text = Loc.GetString("Privileged ID:")},
(_privilegedIdButton = new Button()),
(_privilegedIdLabel = new Label()),
new Label {Text = Loc.GetString("Target ID:")},
(_targetIdButton = new Button()),
(_targetIdLabel = new Label())
}
});
_privilegedIdButton.OnPressed += _ => _owner.ButtonPressed(UiButton.PrivilegedId);
_targetIdButton.OnPressed += _ => _owner.ButtonPressed(UiButton.TargetId);
// Separator
vBox.AddChild(new Control {CustomMinimumSize = (0, 8)});
// Name and job title line edits.
vBox.AddChild(new GridContainer
{
Columns = 3,
HSeparationOverride = 4,
Children =
{
// Name
(_fullNameLabel = new Label
{
Text = Loc.GetString("Full name:")
}),
(_fullNameLineEdit = new LineEdit
{
SizeFlagsHorizontal = SizeFlags.FillExpand,
}),
(_fullNameSaveButton = new Button
{
Text = Loc.GetString("Save"),
Disabled = true
}),
// Title
(_jobTitleLabel = new Label
{
Text = Loc.GetString("Job title:")
}),
(_jobTitleLineEdit = new LineEdit
{
SizeFlagsHorizontal = SizeFlags.FillExpand
}),
(_jobTitleSaveButton = new Button
{
Text = Loc.GetString("Save"),
Disabled = true
}),
},
});
_fullNameLineEdit.OnTextEntered += _ => SubmitData();
_fullNameLineEdit.OnTextChanged += _ =>
{
_fullNameSaveButton.Disabled = _fullNameSaveButton.Text == _lastFullName;
};
_fullNameSaveButton.OnPressed += _ => SubmitData();
_jobTitleLineEdit.OnTextEntered += _ => SubmitData();
_jobTitleLineEdit.OnTextChanged += _ =>
{
_jobTitleSaveButton.Disabled = _jobTitleLineEdit.Text == _lastJobTitle;
};
_jobTitleSaveButton.OnPressed += _ => SubmitData();
// Separator
vBox.AddChild(new Control {CustomMinimumSize = (0, 8)});
{
var grid = new GridContainer
{
Columns = 5,
SizeFlagsHorizontal = SizeFlags.ShrinkCenter
};
vBox.AddChild(grid);
foreach (var accessLevel in prototypeManager.EnumeratePrototypes<AccessLevelPrototype>())
{
var newButton = new Button
{
Text = accessLevel.Name,
ToggleMode = true,
};
grid.AddChild(newButton);
_accessButtons.Add(accessLevel.ID, newButton);
newButton.OnPressed += _ => SubmitData();
}
}
Contents.AddChild(vBox);
}
public void UpdateState(IdCardConsoleBoundUserInterfaceState state)
{
_privilegedIdButton.Text = state.IsPrivilegedIdPresent
? Loc.GetString("Eject")
: Loc.GetString("Insert");
_privilegedIdLabel.Text = state.PrivilegedIdName;
_targetIdButton.Text = state.IsTargetIdPresent
? Loc.GetString("Eject")
: Loc.GetString("Insert");
_targetIdLabel.Text = state.TargetIdName;
var interfaceEnabled =
state.IsPrivilegedIdPresent && state.IsPrivilegedIdAuthorized && state.IsTargetIdPresent;
var fullNameDirty = _lastFullName != null && _fullNameLineEdit.Text != state.TargetIdFullName;
var jobTitleDirty = _lastJobTitle != null && _jobTitleLineEdit.Text != state.TargetIdJobTitle;
_fullNameLabel.Modulate = interfaceEnabled ? Color.White : Color.Gray;
_fullNameLineEdit.Editable = interfaceEnabled;
if (!fullNameDirty)
{
_fullNameLineEdit.Text = state.TargetIdFullName;
}
_fullNameSaveButton.Disabled = !interfaceEnabled || !fullNameDirty;
_jobTitleLabel.Modulate = interfaceEnabled ? Color.White : Color.Gray;
_jobTitleLineEdit.Editable = interfaceEnabled;
if (!jobTitleDirty)
{
_jobTitleLineEdit.Text = state.TargetIdJobTitle;
}
_jobTitleSaveButton.Disabled = !interfaceEnabled || !jobTitleDirty;
foreach (var (accessName, button) in _accessButtons)
{
button.Disabled = !interfaceEnabled;
if (interfaceEnabled)
{
button.Pressed = state.TargetIdAccessList.Contains(accessName);
}
}
_lastFullName = state.TargetIdFullName;
_lastJobTitle = state.TargetIdJobTitle;
}
private void SubmitData()
{
_owner.SubmitData(
_fullNameLineEdit.Text,
_jobTitleLineEdit.Text,
// Iterate over the buttons dictionary, filter by `Pressed`, only get key from the key/value pair
_accessButtons.Where(x => x.Value.Pressed).Select(x => x.Key).ToList());
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.TimerJobs.Samples.ExpandJob
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*
*
*
* Changed (well hacked ...) by Christoph Kutza for Unity support.
*
*/
#if NET4
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using SharpNeat.Core;
namespace SharpNeat.DistanceMetrics
{
/// <summary>
/// Manhattan distance metric.
///
/// The Manhattan distance is simply the sum total of all of the distances in each dimension.
/// Also known as the taxicab distance, rectilinear distance, L1 distance or L1 norm.
///
/// Use the default constructor for classical Manhattan Distance.
/// Optionally the constructor can be provided with a two coefficients and a constant that can be used to modify/distort
/// distance measures. These are:
///
/// matchDistanceCoeff - When comparing two positions in the same dimension the distance between those two position is
/// multiplied by this coefficient.
///
/// mismatchDistanceCoeff, mismatchDistanceConstant - When comparing two coordinates where one describes a position in a given
/// dimenasion and the other does not then the second coordinate is assumed to be at position zero in that dimension. However,
/// the resulting distance is multiplied by this coefficient and mismatchDistanceConstant is added, therefore allowing matches and
/// mismatches to be weighted differently, e.g. more emphasis can be placed on mismatches (and therefore network topology).
/// If mismatchDistanceCoeff is zero and mismatchDistanceConstant is non-zero then the distance of mismatches is a fixed value.
///
/// The two coefficients and constant allow the following schemes:
///
/// 1) Classical Manhattan distance.
/// 2) Topology only distance metric (ignore connections weights).
/// 3) Equivalent of genome distance in Original NEAT (O-NEAT). This is actually a mix of (1) and (2).
/// </summary>
public class ManhattanDistanceMetric : IDistanceMetric
{
/// <summary>A coefficient to applied to the distance obtained from two coordinates that both
/// describe a position in a given dimension.</summary>
readonly double _matchDistanceCoeff;
/// <summary>A coefficient applied to the distance obtained from two coordinates where only one of the coordinates describes
/// a position in a given dimension. The other point is taken to be at position zero in that dimension.</summary>
readonly double _mismatchDistanceCoeff;
/// <summary>A constant that is added to the distance where only one of the coordinates describes a position in a given dimension.
/// This adds extra emphasis to distance when comparing coordinates that exist in different dimesions.</summary>
readonly double _mismatchDistanceConstant;
#region Constructors
/// <summary>
/// Constructs using default weightings for comparisons on matching and mismatching dimensions.
/// Classical Manhattan Distance.
/// </summary>
public ManhattanDistanceMetric() : this(1.0, 1.0, 0.0)
{
}
/// <summary>
/// Constructs using the provided weightings for comparisons on matching and mismatching dimensions.
/// </summary>
/// <param name="matchDistanceCoeff">A coefficient to applied to the distance obtained from two coordinates that both
/// describe a position in a given dimension.</param>
/// <param name="mismatchDistanceCoeff">A coefficient applied to the distance obtained from two coordinates where only one of the coordinates describes
/// a position in a given dimension. The other point is taken to be at position zero in that dimension.</param>
/// <param name="mismatchDistanceConstant">A constant that is added to the distance where only one of the coordinates describes a position in a given dimension.
/// This adds extra emphasis to distance when comparing coordinates that exist in different dimesions.</param>
public ManhattanDistanceMetric(double matchDistanceCoeff, double mismatchDistanceCoeff, double mismatchDistanceConstant)
{
_matchDistanceCoeff = matchDistanceCoeff;
_mismatchDistanceCoeff = mismatchDistanceCoeff;
_mismatchDistanceConstant = mismatchDistanceConstant;
}
#endregion
#region IDistanceMetric Members
/// <summary>
/// Tests if the distance between two positions is less than some threshold.
///
/// A simple way of implementing this method would be to calculate the distance between the
/// two coordinates and test if it is less than the threshold. However, that approach requires that all of the
/// elements in both CoordinateVectors be fully compared. We can improve performance in the general case
/// by testing if the threshold has been passed after each vector element comparison thus allowing an early exit
/// from the method for many calls. Further to this, we can begin comparing from the ends of the vectors where
/// differences are most likely to occur.
/// </summary>
public bool MeasureDistance(CoordinateVector p1, CoordinateVector p2, double threshold)
{
KeyValuePair<ulong,double>[] arr1 = p1.CoordArray;
KeyValuePair<ulong,double>[] arr2 = p2.CoordArray;
// Store these heavily used values locally.
int arr1Length = arr1.Length;
int arr2Length = arr2.Length;
//--- Test for special cases.
if(0 == arr1Length && 0 == arr2Length)
{ // Both arrays are empty. No disparities, therefore the distance is zero.
return 0.0 < threshold;
}
double distance = 0.0;
if(0 == arr1Length)
{ // All arr2 elements are mismatches.
// p1 doesn't specify a value in these dimensions therefore we take its position to be 0 in all of them.
for(int i=0; i<arr2Length; i++) {
distance += Math.Abs(arr2[i].Value);
}
distance = (_mismatchDistanceConstant * arr2Length) + (distance * _mismatchDistanceCoeff);
return distance < threshold;
}
if(0 == arr2Length)
{ // All arr1 elements are mismatches.
// p2 doesn't specify a value in these dimensions therefore we take it's position to be 0 in all of them.
for(int i=0; i<arr1Length; i++) {
distance += Math.Abs(arr1[i].Value);
}
distance = (_mismatchDistanceConstant * arr1Length) + (distance * _mismatchDistanceCoeff);
return distance < threshold;
}
//----- Both arrays contain elements. Compare the contents starting from the ends where the greatest discrepancies
// between coordinates are expected to occur. In the general case this should result in less element comparisons
// before the threshold is passed and we exit the method.
int arr1Idx = arr1Length - 1;
int arr2Idx = arr2Length - 1;
KeyValuePair<ulong,double> elem1 = arr1[arr1Idx];
KeyValuePair<ulong,double> elem2 = arr2[arr2Idx];
for(;;)
{
if(elem2.Key > elem1.Key)
{
// p1 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem2.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr2.
arr2Idx--;
}
else if(elem1.Key == elem2.Key)
{
// Matching elements.
distance += Math.Abs(elem1.Value - elem2.Value) * _matchDistanceCoeff;
// Move to the next element in both arrays.
arr1Idx--;
arr2Idx--;
}
else // elem1.Key > elem2.Key
{
// p2 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem1.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr1.
arr1Idx--;
}
// Test the threshold.
if(distance >= threshold) {
return false;
}
// Check if we have exhausted one or both of the arrays.
if(arr1Idx < 0)
{ // Any remaining arr2 elements are mismatches.
for(int i=arr2Idx; i >- 1; i--) {
distance += _mismatchDistanceConstant + (Math.Abs(arr2[i].Value) * _mismatchDistanceCoeff);
}
return distance < threshold;
}
if(arr2Idx < 0)
{ // All remaining arr1 elements are mismatches.
for(int i=arr1Idx; i > -1; i--) {
distance += _mismatchDistanceConstant + (Math.Abs(arr1[i].Value) * _mismatchDistanceCoeff);
}
return distance < threshold;
}
elem1 = arr1[arr1Idx];
elem2 = arr2[arr2Idx];
}
}
/// <summary>
/// Measures the distance between two positions.
/// </summary>
public double MeasureDistance(CoordinateVector p1, CoordinateVector p2)
{
KeyValuePair<ulong,double>[] arr1 = p1.CoordArray;
KeyValuePair<ulong,double>[] arr2 = p2.CoordArray;
// Store these heavily used values locally.
int arr1Length = arr1.Length;
int arr2Length = arr2.Length;
//--- Test for special cases.
if(0 == arr1Length && 0 == arr2Length)
{ // Both arrays are empty. No disparities, therefore the distance is zero.
return 0.0;
}
double distance = 0;
if(0 == arr1Length)
{ // All arr2 genes are mismatches.
for(int i=0; i<arr2Length; i++) {
distance += Math.Abs(arr2[i].Value);
}
return (_mismatchDistanceConstant * arr2Length) + (distance * _mismatchDistanceCoeff);
}
if(0 == arr2Length)
{ // All arr1 elements are mismatches.
for(int i=0; i<arr1Length; i++) {
distance += Math.Abs(arr1[i].Value);
}
return (_mismatchDistanceConstant * arr1Length) + (distance * _mismatchDistanceCoeff);
}
//----- Both arrays contain elements.
int arr1Idx = 0;
int arr2Idx = 0;
KeyValuePair<ulong,double> elem1 = arr1[arr1Idx];
KeyValuePair<ulong,double> elem2 = arr2[arr2Idx];
for(;;)
{
if(elem1.Key < elem2.Key)
{
// p2 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem1.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr1.
arr1Idx++;
}
else if(elem1.Key == elem2.Key)
{
// Matching elements.
distance += Math.Abs(elem1.Value - elem2.Value) * _matchDistanceCoeff;
// Move to the next element in both arrays.
arr1Idx++;
arr2Idx++;
}
else // elem2.Key < elem1.Key
{
// p1 doesn't specify a value in this dimension therefore we take it's position to be 0.
distance += _mismatchDistanceConstant + (Math.Abs(elem2.Value) * _mismatchDistanceCoeff);
// Move to the next element in arr2.
arr2Idx++;
}
// Check if we have exhausted one or both of the arrays.
if(arr1Idx == arr1Length)
{ // All remaining arr2 elements are mismatches.
for(int i=arr2Idx; i<arr2Length; i++) {
distance += _mismatchDistanceConstant + (Math.Abs(arr2[i].Value) * _mismatchDistanceCoeff);
}
return distance;
}
if(arr2Idx == arr2Length)
{ // All remaining arr1 elements are mismatches.
for(int i=arr1Idx; i<arr1.Length; i++) {
distance += _mismatchDistanceConstant + (Math.Abs(arr1[i].Value) * _mismatchDistanceCoeff);
}
return distance;
}
elem1 = arr1[arr1Idx];
elem2 = arr2[arr2Idx];
}
}
// TODO: Cleanup.
///// <summary>
///// Calculates the centroid for the given set of points.
///// This is perhaps most easy to consider as the center of mass of the set of points (of equal mass).
/////
///// The centroid calculation is dependent on the distance metric in use. E.g. for Euclidean distance
///// we take the average value on each axis for all the points and this minimizes the total distance from
///// points to centroid. For euclidean distance this has the side effect of also minimizing squared distance,
///// but this is not the goal when calculating a centroid.
/////
///// For manhattan distance the centroid is thus given by the calculating the median value for each axis, this
///// achieves the goal of minimizing total distance to the centroid but not squared distance. Other distance
///// metrics require their own centroid calculation accordingly.
/////
///// A centroid is used in k-means clustering to define the center of a cluster.
///// </summary>
///// <param name="coordList"></param>
///// <returns></returns>
//public CoordinateVector CalculateCentroid(IList<CoordinateVector> coordList)
//{
// // Each coordinate element has an ID. Here we keep a list of each value observed for each ID
// // so that we can calculate the median value.
// // Note. Where a coordinate does not specify a position on an axis that other coordinates in
// // the list do specify, that coordinate's position on that axis is taken to be zero. However
// // we do not record those zeroes at this stage. We save storage and time by not recording the
// // zeroes and taking them into account later.
// // Coord elements within a CoordinateVector must be sorted by ID, therefore we use a
// // SortedDictionary here to eliminate the need to sort elements later.
// // We use SortedDictionary and not SortedList for performance, SortedList is fastest for insertion
// // only if the inserts are in order (sorted). However this is generally not the case here because although
// // cordinate IDs are sorted with a given CoordinateVector, not all IDs exist within all genomes, thus a
// // low ID may be presented to coordElemArrays after a higher ID.
// SortedDictionary<ulong, List<double>> coordElemArrays = new SortedDictionary<ulong,List<double>>();
// // Loop over coords. Group together values by axis.
// int coordCount = coordList.Count;
// for(int i=0; i<coordCount; i++)
// {
// CoordinateVector coordVector = coordList[i];
// // Loop over each element within the current coord.
// foreach(KeyValuePair<ulong,double> coordElem in coordVector.CoordArray)
// {
// List<double> elemArray;
// if(!coordElemArrays.TryGetValue(coordElem.Key, out elemArray))
// {
// elemArray = new List<double>();
// coordElemArrays.Add(coordElem.Key, elemArray);
// }
// elemArray.Add(coordElem.Value);
// }
// }
// // We now now how many axes the centroid coordinate has. Allocate storage for the centroid coordinate elements.
// int centroidElemCount = coordElemArrays.Count;
// KeyValuePair<ulong,double>[] centroidElemArr = new KeyValuePair<ulong,double>[centroidElemCount];
// // Loop over each axis calculating the mean value for each. We also compensate here for all of the
// // instances where a coordinate didn't specify a position on a given axis and therefore has an
// // implied position of zero.
// // Create a temp array with enough capacity to hold an axis value for each coordinate.
// double[] tmpArr = new double[coordCount];
// int j=0;
// foreach(KeyValuePair<ulong,List<double>> coordElemItem in coordElemArrays)
// {
// List<double> valueList = coordElemItem.Value;
// // In total we expect coordCount values. Any missing values are form coordinates with an implied
// // position of zero on the current axis.
// int zeroCount = coordCount - valueList.Count;
// // Calculate median value.
// double median;
// // Test special case.
// if(zeroCount > valueList.Count)
// { // More than half the values are zero, therefore the median must be zero.
// median = 0.0;
// }
// else if(0 == zeroCount)
// {
// valueList.Sort();
// median = Utilities.CalculateMedian(valueList);
// }
// else
// {
// // ENHANCEMENT: We can stop and calculate the median once we reach halfway through the values.
// // Combine valueList with the required number of zeroes. Sort the list and calc the median.
// // We can save some effort by sorting valueList first and inserting the zeroes in-place afterwards.
// valueList.Sort();
// // Insert all values below zero.
// int valueListCount = valueList.Count;
// int valueListIdx = 0;
// int k=0;
// for(;k<valueListCount && valueList[valueListIdx] < 0.0; valueListIdx++, k++)
// {
// tmpArr[k] = valueList[valueListIdx];
// }
// // Insert zeroes.
// for(int l=0; l<zeroCount; l++, k++)
// {
// tmpArr[k] = 0.0;
// }
// // Insert all values zero or above.
// for(;valueListIdx<valueListCount; valueListIdx++, k++)
// {
// tmpArr[k] = valueList[valueListIdx];
// }
// median = Utilities.CalculateMedian(tmpArr);
// }
// // Store centroid coord element.
// centroidElemArr[j++] = new KeyValuePair<ulong,double>(coordElemItem.Key, median);
// }
// CoordinateVector tmp = CalculateCentroid_Euclidean(coordList);
// return new CoordinateVector(centroidElemArr);
//}
// TODO: Determine mathematically correct centroid. This method calculates the Euclidean distance centroid and
// is an approximation of the true centroid in L1 space (manhatten distance).
// Note. In practice this is possibly a near optimal centroid for all but small clusters.
/// <summary>
/// Calculates the centroid for the given set of points.
/// The centroid is a central position within a set of points that minimizes the sum of the squared distance
/// between each of those points and the centroid. As such it can also be thought of as being an exemplar
/// for a set of points.
///
/// The centroid calculation is dependent on the distance metric, hence this method is defined on IDistanceMetric.
/// For some distance metrics the centroid may not be a unique point, in those cases one of the possible centroids
/// is returned.
///
/// A centroid is used in k-means clustering to define the center of a cluster.
/// </summary>
public CoordinateVector CalculateCentroid(IList<CoordinateVector> coordList)
{
// Special case - one item in list, it *is* the centroid.
if(1 == coordList.Count) {
return coordList[0];
}
// Each coordinate element has an ID. Here we calculate the total for each ID across all CoordinateVectors,
// then divide the totals by the number of CoordinateVectors to get the average for each ID. That is, we
// calculate the component-wise mean.
//
// Coord elements within a CoordinateVector must be sorted by ID, therefore we use a SortedDictionary here
// when building the centroid coordinate to eliminate the need to sort elements later.
//
// We use SortedDictionary and not SortedList for performance. SortedList is fastest for insertion
// only if the inserts are in order (sorted). However, this is generally not the case here because although
// cordinate IDs are sorted within the source CoordinateVectors, not all IDs exist within all CoordinateVectors
// therefore a low ID may be presented to coordElemTotals after a higher ID.
SortedDictionary<ulong, double[]> coordElemTotals = new SortedDictionary<ulong,double[]>();
// Loop over coords.
foreach(CoordinateVector coord in coordList)
{
// Loop over each element within the current coord.
foreach(KeyValuePair<ulong,double> coordElem in coord.CoordArray)
{
// If the ID has previously been encountered then add the current element value to it, otherwise
// add a new double[1] tp hold the value.
// Note that we wrap the double value in an object so that we do not have to re-insert values
// to increment them. In tests this approach was about 40% faster (including GC overhead).
double[] doubleWrapper;
if(coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper)) {
doubleWrapper[0] += coordElem.Value;
}
else {
coordElemTotals.Add(coordElem.Key, new double[]{coordElem.Value});
}
}
}
// Put the unique coord elems from coordElemTotals into a list, dividing each element's value
// by the total number of coords as we go.
double coordCountReciprocol = 1.0 / (double)coordList.Count;
KeyValuePair<ulong,double>[] centroidElemArr = new KeyValuePair<ulong,double>[coordElemTotals.Count];
int i=0;
foreach(KeyValuePair<ulong,double[]> coordElem in coordElemTotals)
{ // For speed we multiply by reciprocol instead of dividing by coordCount.
centroidElemArr[i++] = new KeyValuePair<ulong,double>(coordElem.Key, coordElem.Value[0] * coordCountReciprocol);
}
// Use the new list of elements to construct a centroid CoordinateVector.
return new CoordinateVector(centroidElemArr);
}
/// <summary>
/// Parallelized version of CalculateCentroid().
/// </summary>
public CoordinateVector CalculateCentroidParallel(IList<CoordinateVector> coordList)
{
// Special case - one item in list, it *is* the centroid.
if (1 == coordList.Count)
{
return coordList[0];
}
// Each coordinate element has an ID. Here we calculate the total for each ID across all CoordinateVectors,
// then divide the totals by the number of CoordinateVectors to get the average for each ID. That is, we
// calculate the component-wise mean.
// ConcurrentDictionary provides a low-locking strategy that greatly improves performance here
// compared to using mutual exclusion locks or even ReadWriterLock(s).
ConcurrentDictionary<ulong,double[]> coordElemTotals = new ConcurrentDictionary<ulong, double[]>();
// Loop over coords.
Parallel.ForEach(coordList, delegate(CoordinateVector coord)
{
// Loop over each element within the current coord.
foreach (KeyValuePair<ulong, double> coordElem in coord.CoordArray)
{
// If the ID has previously been encountered then add the current element value to it, otherwise
// add a new double[1] to hold the value.
// Note that we wrap the double value in an object so that we do not have to re-insert values
// to increment them. In tests this approach was about 40% faster (including GC overhead).
// If position is zero then (A) skip doing any work, and (B) zero will break the following logic.
if (coordElem.Value == 0.0) {
continue;
}
double[] doubleWrapper;
if (coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
{ // By locking just the specific object that holds the value we are incrementing
// we greatly reduce the amount of lock contention.
lock(doubleWrapper)
{
doubleWrapper[0] += coordElem.Value;
}
}
else
{
doubleWrapper = new double[] { coordElem.Value };
if (!coordElemTotals.TryAdd(coordElem.Key, doubleWrapper))
{
if(coordElemTotals.TryGetValue(coordElem.Key, out doubleWrapper))
{
lock (doubleWrapper)
{
doubleWrapper[0] += coordElem.Value;
}
}
}
}
}
});
// Put the unique coord elems from coordElemTotals into a list, dividing each element's value
// by the total number of coords as we go.
double coordCountReciprocol = 1.0 / (double)coordList.Count;
KeyValuePair<ulong, double>[] centroidElemArr = new KeyValuePair<ulong, double>[coordElemTotals.Count];
int i = 0;
foreach (KeyValuePair<ulong, double[]> coordElem in coordElemTotals)
{ // For speed we multiply by reciprocol instead of dividing by coordCount.
centroidElemArr[i++] = new KeyValuePair<ulong, double>(coordElem.Key, coordElem.Value[0] * coordCountReciprocol);
}
// Coord elements within a CoordinateVector must be sorted by ID.
Array.Sort(centroidElemArr, delegate(KeyValuePair<ulong, double> x, KeyValuePair<ulong, double> y)
{
if (x.Key < y.Key) {
return -1;
}
if (x.Key > y.Key) {
return 1;
}
return 0;
});
// Use the new list of elements to construct a centroid CoordinateVector.
return new CoordinateVector(centroidElemArr);
}
#endregion
}
}
#endif
| |
using System.Text;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Converts numbers to english strings for testing.
/// @lucene.internal
/// </summary>
public sealed class English
{
private English() // no instance
{
}
public static string LongToEnglish(long i)
{
StringBuilder result = new StringBuilder();
LongToEnglish(i, result);
return result.ToString();
}
public static void LongToEnglish(long i, StringBuilder result)
{
if (i == 0)
{
result.Append("zero");
return;
}
if (i < 0)
{
result.Append("minus ");
i = -i;
}
if (i >= 1000000000000000000l) // quadrillion
{
LongToEnglish(i / 1000000000000000000l, result);
result.Append("quintillion, ");
i = i % 1000000000000000000l;
}
if (i >= 1000000000000000l) // quadrillion
{
LongToEnglish(i / 1000000000000000l, result);
result.Append("quadrillion, ");
i = i % 1000000000000000l;
}
if (i >= 1000000000000l) // trillions
{
LongToEnglish(i / 1000000000000l, result);
result.Append("trillion, ");
i = i % 1000000000000l;
}
if (i >= 1000000000) // billions
{
LongToEnglish(i / 1000000000, result);
result.Append("billion, ");
i = i % 1000000000;
}
if (i >= 1000000) // millions
{
LongToEnglish(i / 1000000, result);
result.Append("million, ");
i = i % 1000000;
}
if (i >= 1000) // thousands
{
LongToEnglish(i / 1000, result);
result.Append("thousand, ");
i = i % 1000;
}
if (i >= 100) // hundreds
{
LongToEnglish(i / 100, result);
result.Append("hundred ");
i = i % 100;
}
//we know we are smaller here so we can cast
if (i >= 20)
{
switch (((int)i) / 10)
{
case 9:
result.Append("ninety");
break;
case 8:
result.Append("eighty");
break;
case 7:
result.Append("seventy");
break;
case 6:
result.Append("sixty");
break;
case 5:
result.Append("fifty");
break;
case 4:
result.Append("forty");
break;
case 3:
result.Append("thirty");
break;
case 2:
result.Append("twenty");
break;
}
i = i % 10;
if (i == 0)
{
result.Append(" ");
}
else
{
result.Append("-");
}
}
switch ((int)i)
{
case 19:
result.Append("nineteen ");
break;
case 18:
result.Append("eighteen ");
break;
case 17:
result.Append("seventeen ");
break;
case 16:
result.Append("sixteen ");
break;
case 15:
result.Append("fifteen ");
break;
case 14:
result.Append("fourteen ");
break;
case 13:
result.Append("thirteen ");
break;
case 12:
result.Append("twelve ");
break;
case 11:
result.Append("eleven ");
break;
case 10:
result.Append("ten ");
break;
case 9:
result.Append("nine ");
break;
case 8:
result.Append("eight ");
break;
case 7:
result.Append("seven ");
break;
case 6:
result.Append("six ");
break;
case 5:
result.Append("five ");
break;
case 4:
result.Append("four ");
break;
case 3:
result.Append("three ");
break;
case 2:
result.Append("two ");
break;
case 1:
result.Append("one ");
break;
case 0:
result.Append("");
break;
}
}
public static string IntToEnglish(int i)
{
StringBuilder result = new StringBuilder();
LongToEnglish(i, result);
return result.ToString();
}
public static void IntToEnglish(int i, StringBuilder result)
{
LongToEnglish(i, result);
}
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERCLevel;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D12_CityRoad (editable child object).<br/>
/// This is a generated base class of <see cref="D12_CityRoad"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D11_CityRoadColl"/> collection.
/// </remarks>
[Serializable]
public partial class D12_CityRoad : BusinessBase<D12_CityRoad>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="CityRoad_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CityRoad_IDProperty = RegisterProperty<int>(p => p.CityRoad_ID, "CityRoads ID");
/// <summary>
/// Gets the CityRoads ID.
/// </summary>
/// <value>The CityRoads ID.</value>
public int CityRoad_ID
{
get { return GetProperty(CityRoad_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CityRoad_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> CityRoad_NameProperty = RegisterProperty<string>(p => p.CityRoad_Name, "CityRoads Name");
/// <summary>
/// Gets or sets the CityRoads Name.
/// </summary>
/// <value>The CityRoads Name.</value>
public string CityRoad_Name
{
get { return GetProperty(CityRoad_NameProperty); }
set { SetProperty(CityRoad_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D12_CityRoad"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D12_CityRoad"/> object.</returns>
internal static D12_CityRoad NewD12_CityRoad()
{
return DataPortal.CreateChild<D12_CityRoad>();
}
/// <summary>
/// Factory method. Loads a <see cref="D12_CityRoad"/> object from the given D12_CityRoadDto.
/// </summary>
/// <param name="data">The <see cref="D12_CityRoadDto"/>.</param>
/// <returns>A reference to the fetched <see cref="D12_CityRoad"/> object.</returns>
internal static D12_CityRoad GetD12_CityRoad(D12_CityRoadDto data)
{
D12_CityRoad obj = new D12_CityRoad();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D12_CityRoad"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D12_CityRoad()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D12_CityRoad"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(CityRoad_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D12_CityRoad"/> object from the given <see cref="D12_CityRoadDto"/>.
/// </summary>
/// <param name="data">The D12_CityRoadDto to use.</param>
private void Fetch(D12_CityRoadDto data)
{
// Value properties
LoadProperty(CityRoad_IDProperty, data.CityRoad_ID);
LoadProperty(CityRoad_NameProperty, data.CityRoad_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D12_CityRoad"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D10_City parent)
{
var dto = new D12_CityRoadDto();
dto.Parent_City_ID = parent.City_ID;
dto.CityRoad_Name = CityRoad_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<ID12_CityRoadDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(CityRoad_IDProperty, resultDto.CityRoad_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D12_CityRoad"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new D12_CityRoadDto();
dto.CityRoad_ID = CityRoad_ID;
dto.CityRoad_Name = CityRoad_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<ID12_CityRoadDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="D12_CityRoad"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<ID12_CityRoadDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(CityRoad_IDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace Hydra.Framework
{
/// <summary>
/// Represents a range of enumerable items
/// </summary>
/// <typeparam name="T">The type of range</typeparam>
public class Range<T>
: IEquatable<Range<T>>
{
#region Member Variables
/// <summary>
/// Comparer Implementation for Type T
/// </summary>
readonly IComparer<T> comparer;
/// <summary>
/// Is lower Binding included in the range
/// </summary>
readonly bool includeLowerBound;
/// <summary>
/// Is upper binding included in the range
/// </summary>
readonly bool includeUpperBound;
/// <summary>
/// Lower Bound object T
/// </summary>
readonly T lowerBound;
/// <summary>
/// Upper Bound object T
/// </summary>
readonly T upperBound;
#endregion
#region Constructors
/// <summary>
/// Initializes a new Range
/// </summary>
/// <param name="lowerBound">The lower bound.</param>
/// <param name="upperBound">The upper bound.</param>
/// <param name="includeLowerBound">If the lower bound should be included</param>
/// <param name="includeUpperBound">If the upper bound should be included</param>
public Range(T lowerBound, T upperBound, bool includeLowerBound, bool includeUpperBound)
: this(lowerBound, upperBound, includeLowerBound, includeUpperBound, Comparer<T>.Default)
{
}
/// <summary>
/// Initializes a new Range
/// </summary>
/// <param name="lowerBound">The lower bound.</param>
/// <param name="upperBound">The upper bound.</param>
/// <param name="includeLowerBound">If the lower bound should be included</param>
/// <param name="includeUpperBound">If the upper bound should be included</param>
/// <param name="comparer">The comparison to use for the range elements</param>
Range(T lowerBound, T upperBound, bool includeLowerBound, bool includeUpperBound, IComparer<T> comparer)
{
this.comparer = comparer;
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.includeLowerBound = includeLowerBound;
this.includeUpperBound = includeUpperBound;
}
#endregion
#region Properties
/// <summary>
/// The lower bound of the range
/// </summary>
/// <value>The lower bound.</value>
public T LowerBound
{
get
{
return lowerBound;
}
}
/// <summary>
/// The upper bound of the range
/// </summary>
public T UpperBound
{
get
{
return upperBound;
}
}
/// <summary>
/// The comparison used for the elements in the range
/// </summary>
/// <value>The comparer.</value>
public IComparer<T> Comparer
{
get
{
return comparer;
}
}
/// <summary>
/// If the lower bound is included in the range
/// </summary>
/// <value><c>true</c> if [include lower bound]; otherwise, <c>false</c>.</value>
public bool IncludeLowerBound
{
get
{
return includeLowerBound;
}
}
/// <summary>
/// If the upper bound is included in the range
/// </summary>
/// <value><c>true</c> if [include upper bound]; otherwise, <c>false</c>.</value>
public bool IncludeUpperBound
{
get
{
return includeUpperBound;
}
}
#endregion
#region Public Methods
/// <summary>
/// Determines if the value specified is contained within the range
/// </summary>
/// <param name="value">The value to check</param>
/// <returns>
/// Returns true if the value is contained within the range, otherwise false
/// </returns>
public bool Contains(T value)
{
int left = comparer.Compare(value, lowerBound);
if (comparer.Compare(value, lowerBound) < 0 || (left == 0 && !includeLowerBound))
return false;
int right = comparer.Compare(value, upperBound);
return right < 0 ||
(right == 0 && includeUpperBound);
}
/// <summary>
/// Returns a forward enumerator for the range
/// </summary>
/// <param name="step">A function used to step through the range</param>
/// <returns>An enumerator for the range</returns>
public RangeEnumerator<T> Forward(Func<T, T> step)
{
return new RangeEnumerator<T>(this, step);
}
#endregion
#region Equality Implementation
/// <summary>
/// Equalses the specified obj.
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public bool Equals(Range<T> obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
return obj.includeLowerBound.Equals(includeLowerBound) && obj.includeUpperBound.Equals(includeUpperBound) && Equals(obj.lowerBound, lowerBound) && Equals(obj.upperBound, upperBound);
}
/// <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)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(Range<T>))
return false;
return Equals((Range<T>)obj);
}
/// <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 provider.
/// </returns>
public override int GetHashCode()
{
unchecked
{
int result = includeLowerBound.GetHashCode();
result = (result * 397) ^ includeUpperBound.GetHashCode();
result = (result * 397) ^ lowerBound.GetHashCode();
result = (result * 397) ^ upperBound.GetHashCode();
return result;
}
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(Range<T> left, Range<T> right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(Range<T> left, Range<T> right)
{
return !Equals(left, right);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections; //IEnumerator
using System.Collections.Generic; //List<T>
namespace Microsoft.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// TestInput
//
////////////////////////////////////////////////////////////////
public class TestInput
{
//Data
private static TestProps s_pproperties;
private static String s_pinitstring;
private static String s_pcommandline;
//Constructor
public static TestProps Properties
{
get
{
if (s_pproperties == null)
{
s_pproperties = new TestProps(new TestProperties());
//CommandLine
String commandline = s_pcommandline;
s_pproperties["CommandLine"] = commandline;
//CommandLine Options
KeywordParser.Tokens tokens = new KeywordParser.Tokens();
tokens.Equal = " ";
tokens.Seperator = "/";
Dictionary<string, string> options = KeywordParser.ParseKeywords(commandline, tokens);
foreach (String key in options.Keys)
s_pproperties["CommandLine/" + key] = options[key];
}
return s_pproperties;
}
set
{
if (value != null)
{
//Clear between each run
s_pproperties = null;
//InitString keywords
String initstring = value["Alias/InitString"];
TestInput.Properties["Alias/InitString"] = initstring;
Dictionary<string, string> keywords = KeywordParser.ParseKeywords(initstring);
foreach (String key in keywords.Keys)
TestInput.Properties["Alias/InitString/" + key] = keywords[key] as String;
// Command line keywords (if any)
TestProp commandLineProp = value.Get("CommandLine");
if (commandLineProp != null)
{
string commandLine = value["CommandLine"];
TestInput.Properties["CommandLine"] = commandLine;
//CommandLine Options
KeywordParser.Tokens tokens = new KeywordParser.Tokens();
tokens.Equal = " ";
tokens.Seperator = "/";
Dictionary<string, string> options = KeywordParser.ParseKeywords(commandLine, tokens);
foreach (String key in options.Keys)
TestInput.Properties["CommandLine/" + key] = options[key];
}
}
}
}
public static bool IsTestCaseSelected(string testcasename)
{
bool ret = true;
string testcasefilter = Properties["CommandLine/testcase"];
if (testcasefilter != null
&& testcasefilter != "*"
&& testcasefilter != testcasename)
{
ret = false;
}
return ret;
}
public static bool IsVariationSelected(string variationname)
{
bool ret = true;
string variationfilter = s_pproperties["variation"];
if (variationfilter != null
&& variationfilter != "*"
&& variationfilter != variationname)
{
ret = false;
}
return ret;
}
internal static void Dispose()
{
//Reset the info.
//Since this is a static class, (to make it simplier to access from anywhere in your code)
//we need to reset this info every time a test is run - so if you don't select an alias
//the next time it doesn't use the previous alias setting - ie: ProviderInfo doesn't
//get called when no alias is selected...
s_pproperties = null;
s_pinitstring = null;
s_pcommandline = null;
}
public static string InitString
{
get
{
//Useful typed getter
if (s_pinitstring == null)
s_pinitstring = TestInput.Properties["Alias/InitString"];
return s_pinitstring;
}
}
public static string CommandLine
{
get
{
//Useful typed getter
if (s_pcommandline == null)
s_pcommandline = TestInput.Properties["CommandLine"];
return s_pcommandline;
}
set
{
s_pcommandline = value;
}
}
public static String Filter
{
get
{
if (TestInput.Properties != null)
return TestInput.Properties["CommandLine/Filter"];
return null;
}
}
public static String MaxPriority
{
get
{
if (TestInput.Properties != null)
return TestInput.Properties["CommandLine/MaxPriority"];
return null;
}
}
}
////////////////////////////////////////////////////////////////
// TestProps
//
////////////////////////////////////////////////////////////////
public class TestProps : ITestProperties, IEnumerable, IEnumerator
{
//Data
protected ITestProperties pinternal;
protected int penum = -1;
//Constructor
public TestProps(ITestProperties properties)
{
pinternal = properties;
}
//Accessors
public virtual ITestProperties Internal
{
get { return pinternal; }
}
public virtual int Count
{
get
{
if (pinternal != null)
return pinternal.Count;
return 0;
}
}
public virtual TestProp this[int index]
{
get
{
ITestProperty property = pinternal.GetItem(index);
if (property != null)
return new TestProp(property);
return null;
}
}
public virtual String this[String name]
{
get
{
ITestProperty property = pinternal.Get(name);
if (property != null)
return StringEx.ToString(property.Value);
return null;
}
set
{
this.Add(name).Value = value;
}
}
public virtual TestProp Get(String name)
{
ITestProperty property = pinternal.Get(name);
if (property != null)
return new TestProp(property);
return null;
}
public virtual TestProp Add(String name)
{
return new TestProp(pinternal.Add(name));
}
public virtual void Remove(String name)
{
pinternal.Remove(name);
}
public virtual IEnumerator GetEnumerator()
{
return this;
}
public virtual bool MoveNext()
{
if (penum + 1 >= this.Count)
return false;
penum++;
return true;
}
public virtual Object Current
{
get { return this[penum]; }
}
public virtual void Reset()
{
penum = -1;
}
public virtual void Clear()
{
if (pinternal != null)
pinternal.Clear();
}
ITestProperty ITestProperties.Add(String name)
{
return pinternal.Add(name);
}
ITestProperty ITestProperties.Get(String name)
{
return pinternal.Get(name);
}
ITestProperty ITestProperties.GetItem(int index)
{
return pinternal.GetItem(index);
}
}
////////////////////////////////////////////////////////////////
// TestProp
//
////////////////////////////////////////////////////////////////
public class TestProp : ITestProperty, IEnumerable
{
//Data
protected ITestProperty pinternal;
//Constructor
public TestProp(ITestProperty property)
{
pinternal = property;
}
//Accessors
public virtual ITestProperty Internal
{
get { return pinternal; }
}
public virtual String Name
{
get { return pinternal.Name; }
}
public virtual String Desc
{
get { return pinternal.Desc; }
}
public virtual TestPropertyFlags Flags
{
get { return pinternal.Flags; }
set { pinternal.Flags = value; }
}
public virtual Object Value
{
get { return pinternal.Value; }
set { pinternal.set_Value(ref value); }
}
public virtual TestProps Children
{
get { return new TestProps(pinternal.Children); }
}
public virtual IEnumerator GetEnumerator()
{
return this.Children;
}
void ITestProperty.set_Value(ref object value)
{
pinternal.set_Value(ref value);
}
ITestProperties ITestProperty.Children
{
get { return pinternal.Children; }
}
ITestProperties ITestProperty.Metadata
{
get { return pinternal.Metadata; }
}
}
////////////////////////////////////////////////////////////////
// TestProperty
//
////////////////////////////////////////////////////////////////
public class TestProperty : ITestProperty
{
//Data
protected String pname = null;
protected String pdesc = null;
protected Object pvalue = null;
protected TestPropertyFlags pflags = 0;
protected TestProperties pmetadata = null;
protected TestProperties pchildren = null;
//Constructor
public TestProperty(String name, Object value)
{
pname = name;
pvalue = value;
}
//Accessors
public string Name
{
get { return pname; }
set { pname = value; }
}
public string Desc
{
get { return pdesc; }
set { pdesc = value; }
}
public TestPropertyFlags Flags
{
get { return pflags; }
set { pflags = value; }
}
public object Value
{
get { return pvalue; }
set { pvalue = value; }
}
public void set_Value(ref object value)
{
pvalue = value;
}
public ITestProperties Metadata
{
get { return pmetadata; }
}
public ITestProperties Children
{
get { return pchildren; }
}
}
////////////////////////////////////////////////////////////////
// TestProperties
//
////////////////////////////////////////////////////////////////
public class TestProperties : ITestProperties, IEnumerable
{
//Data
protected List<TestProperty> plist = null;
//Constructor
public TestProperties()
{
plist = new List<TestProperty>();
}
//Methods
public virtual int Count
{
get { return plist.Count; }
}
public virtual TestProperty this[int index]
{
get { return plist[index]; }
}
public virtual Object this[String name]
{
get
{
ITestProperty property = this.Get(name);
if (property != null)
return property.Value;
return null;
}
set { this.Add(name).Value = value; }
}
public virtual int IndexOf(string name)
{
int count = plist.Count;
for (int i = 0; i < count; i++)
{
if (String.Compare(plist[i].Name, name) == 0)
return i;
}
return -1;
}
public virtual IEnumerator GetEnumerator()
{
return plist.GetEnumerator();
}
ITestProperty ITestProperties.GetItem(int index)
{
return this[index];
}
public virtual ITestProperty Get(String name)
{
int index = this.IndexOf(name);
if (index >= 0)
return plist[index];
return null;
}
ITestProperty ITestProperties.Add(String name)
{
return (TestProperty)Add(name);
}
public virtual TestProperty Add(String name)
{
//Exists
int index = this.IndexOf(name);
if (index >= 0)
return plist[index];
//Otherwise add
TestProperty property = new TestProperty(name, null);
plist.Add(property);
return property;
}
public virtual void Remove(String name)
{
int index = this.IndexOf(name);
if (index >= 0)
plist.RemoveAt(index);
}
public virtual void Clear()
{
plist.Clear();
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using Microsoft.Boogie;
using System.Collections.Generic;
using System.Diagnostics;
namespace Symbooglix
{
public abstract class Traverser
{
protected IExprVisitor Visitor;
public Traverser(IExprVisitor Visitor)
{
this.Visitor = Visitor;
}
public abstract Expr Traverse(Expr root);
protected Expr Visit(Expr e)
{
// Handle Expressions that are of different types
if (e is NAryExpr)
return HandleNAry(e as NAryExpr);
else if (e is LiteralExpr)
return Visitor.VisitLiteralExpr(e as LiteralExpr);
else if (e is IdentifierExpr)
return Visitor.VisitIdentifierExpr(e as IdentifierExpr);
else if (e is OldExpr)
return Visitor.VisitOldExpr(e as OldExpr);
else if (e is CodeExpr)
return Visitor.VisitCodeExpr(e as CodeExpr);
else if (e is BvExtractExpr)
return Visitor.VisitBvExtractExpr(e as BvExtractExpr);
else if (e is BvConcatExpr)
return Visitor.VisitBvConcatExpr(e as BvConcatExpr);
else if (e is ForallExpr)
return Visitor.VisitForallExpr(e as ForallExpr);
else if (e is ExistsExpr)
return Visitor.VisitExistExpr(e as ExistsExpr);
else if (e is LambdaExpr)
return Visitor.VisitLambdaExpr(e as LambdaExpr);
throw new NotImplementedException("Expr not supported!");
}
protected Expr HandleNAry(NAryExpr e)
{
if (e.Fun is FunctionCall)
{
var FC = (FunctionCall) e.Fun;
string bvbuiltin = QKeyValue.FindStringAttribute(FC.Func.Attributes, "bvbuiltin");
if (bvbuiltin != null)
{
return HandlerBvBuiltIns(e, bvbuiltin);
}
else
{
string builtin = QKeyValue.FindStringAttribute(FC.Func.Attributes, "builtin");
if (builtin != null)
return HandlerBuiltIns(e, builtin);
// Not a bvbuiltin so treat as generic function call.
return Visitor.VisitFunctionCall(e);
}
}
else if (e.Fun is UnaryOperator)
{
var U = (UnaryOperator) e.Fun;
switch (U.Op)
{
case UnaryOperator.Opcode.Neg:
return Visitor.VisitNeg(e);
case UnaryOperator.Opcode.Not:
return Visitor.VisitNot(e);
default:
throw new NotImplementedException("Unary operator not supported");
}
}
else if (e.Fun is BinaryOperator)
{
var B = (BinaryOperator) e.Fun;
switch (B.Op)
{
// Integer or Real number operators
case BinaryOperator.Opcode.Add:
return Visitor.VisitAdd(e);
case BinaryOperator.Opcode.Sub:
return Visitor.VisitSub(e);
case BinaryOperator.Opcode.Mul:
return Visitor.VisitMul(e);
case BinaryOperator.Opcode.Div:
return Visitor.VisitDiv(e);
case BinaryOperator.Opcode.Mod:
return Visitor.VisitMod(e);
case BinaryOperator.Opcode.RealDiv:
return Visitor.VisitRealDiv(e);
case BinaryOperator.Opcode.Pow:
return Visitor.VisitPow(e);
// Comparision operators
case BinaryOperator.Opcode.Eq:
return Visitor.VisitEq(e);
case BinaryOperator.Opcode.Neq:
return Visitor.VisitNeq(e);
case BinaryOperator.Opcode.Gt:
return Visitor.VisitGt(e);
case BinaryOperator.Opcode.Ge:
return Visitor.VisitGe(e);
case BinaryOperator.Opcode.Lt:
return Visitor.VisitLt(e);
case BinaryOperator.Opcode.Le:
return Visitor.VisitLe(e);
// Bool operators
case BinaryOperator.Opcode.And:
return Visitor.VisitAnd(e);
case BinaryOperator.Opcode.Or:
return Visitor.VisitOr(e);
case BinaryOperator.Opcode.Imp:
return Visitor.VisitImp(e);
case BinaryOperator.Opcode.Iff:
return Visitor.VisitIff(e);
case BinaryOperator.Opcode.Subtype:
return Visitor.VisitSubType(e);
default:
throw new NotImplementedException("Binary operator not supported!");
}
}
else if (e.Fun is MapStore)
{
return Visitor.VisitMapStore(e);
}
else if (e.Fun is MapSelect)
{
return Visitor.VisitMapSelect(e);
}
else if (e.Fun is IfThenElse)
{
return Visitor.VisitIfThenElse(e);
}
else if (e.Fun is TypeCoercion)
{
return Visitor.VisitTypeCoercion(e);
}
else if (e.Fun is ArithmeticCoercion)
{
return Visitor.VisitArithmeticCoercion(e);
}
else if (e.Fun is DistinctOperator)
{
return Visitor.VisitDistinct(e);
}
throw new NotImplementedException("NAry not handled!");
}
protected Expr HandlerBuiltIns(NAryExpr e, string builtin)
{
// We support very few builtins here. People shouldn't be using them
switch (builtin)
{
case "div":
return Visitor.VisitDiv(e);
case "mod":
return Visitor.VisitMod(e);
case "rem":
return Visitor.VisitRem(e);
default:
throw new NotImplementedException("Builtin \"" + builtin + "\" not supported");
}
}
protected Expr HandlerBvBuiltIns(NAryExpr e, string builtin)
{
Debug.Assert(builtin.Length > 0);
// We grab for first word because the bvbuiltin
// might be "zeroextend 16", we don't care about the number
string firstWord = builtin.Split(' ')[0];
Debug.Assert(firstWord.Length > 0);
switch (firstWord)
{
// arithmetic
case "bvadd":
return Visitor.Visit_bvadd(e);
case "bvsub":
return Visitor.Visit_bvsub(e);
case "bvmul":
return Visitor.Visit_bvmul(e);
case "bvudiv":
return Visitor.Visit_bvudiv(e);
case "bvurem":
return Visitor.Visit_bvurem(e);
case "bvsdiv":
return Visitor.Visit_bvsdiv(e);
case "bvsrem":
return Visitor.Visit_bvsrem(e);
case "bvsmod":
return Visitor.Visit_bvsmod(e);
case "sign_extend":
return Visitor.Visit_sign_extend(e);
case "zero_extend":
return Visitor.Visit_zero_extend(e);
// bitwise logical
case "bvneg":
return Visitor.Visit_bvneg(e);
case "bvand":
return Visitor.Visit_bvand(e);
case "bvor":
return Visitor.Visit_bvor(e);
case "bvnot":
return Visitor.Visit_bvnot(e);
case "bvxor":
return Visitor.Visit_bvxor(e);
// shift
case "bvshl":
return Visitor.Visit_bvshl(e);
case "bvlshr":
return Visitor.Visit_bvlshr(e);
case "bvashr":
return Visitor.Visit_bvashr(e);
// Comparison
case "bvult":
return Visitor.Visit_bvult(e);
case "bvule":
return Visitor.Visit_bvule(e);
case "bvugt":
return Visitor.Visit_bvugt(e);
case "bvuge":
return Visitor.Visit_bvuge(e);
case "bvslt":
return Visitor.Visit_bvslt(e);
case "bvsle":
return Visitor.Visit_bvsle(e);
case "bvsgt":
return Visitor.Visit_bvsgt(e);
case "bvsge":
return Visitor.Visit_bvsge(e);
default:
throw new NotImplementedException(firstWord + " bvbuiltin not supported!");
}
}
}
}
| |
namespace XenAdmin.Dialogs
{
partial class RoleSelectionDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RoleSelectionDialog));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelBlurb = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelDescription = new System.Windows.Forms.Label();
this.gridRoles = new System.Windows.Forms.DataGridView();
this.ColumnRolesCheckBox = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.pictureBoxSubjectType = new System.Windows.Forms.PictureBox();
this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.gridRoles)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxSubjectType)).BeginInit();
this.tableLayoutPanel2.SuspendLayout();
this.SuspendLayout();
//
// buttonSave
//
resources.ApplyResources(this.buttonSave, "buttonSave");
this.buttonSave.Name = "buttonSave";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.labelBlurb.Name = "labelBlurb";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.labelDescription, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.gridRoles, 0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// labelDescription
//
resources.ApplyResources(this.labelDescription, "labelDescription");
this.labelDescription.Name = "labelDescription";
//
// gridRoles
//
this.gridRoles.AllowUserToAddRows = false;
this.gridRoles.AllowUserToDeleteRows = false;
this.gridRoles.AllowUserToResizeColumns = false;
this.gridRoles.AllowUserToResizeRows = false;
this.gridRoles.BackgroundColor = System.Drawing.SystemColors.Window;
this.gridRoles.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.gridRoles.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.gridRoles.ColumnHeadersVisible = false;
this.gridRoles.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnRolesCheckBox,
this.dataGridViewTextBoxColumn1});
resources.ApplyResources(this.gridRoles, "gridRoles");
this.gridRoles.MultiSelect = false;
this.gridRoles.Name = "gridRoles";
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle2.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.gridRoles.RowHeadersDefaultCellStyle = dataGridViewCellStyle2;
this.gridRoles.RowHeadersVisible = false;
this.gridRoles.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
this.gridRoles.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.gridRoles.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.gridRoles_CellContentClick);
this.gridRoles.SelectionChanged += new System.EventHandler(this.gridRoles_SelectionChanged);
this.gridRoles.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.gridRoles_KeyPress);
//
// ColumnRolesCheckBox
//
this.ColumnRolesCheckBox.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
resources.ApplyResources(this.ColumnRolesCheckBox, "ColumnRolesCheckBox");
this.ColumnRolesCheckBox.Name = "ColumnRolesCheckBox";
this.ColumnRolesCheckBox.ReadOnly = true;
this.ColumnRolesCheckBox.Resizable = System.Windows.Forms.DataGridViewTriState.False;
//
// dataGridViewTextBoxColumn1
//
this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewTextBoxColumn1.DefaultCellStyle = dataGridViewCellStyle1;
resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1");
this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
this.dataGridViewTextBoxColumn1.ReadOnly = true;
this.dataGridViewTextBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridViewTextBoxColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// pictureBoxSubjectType
//
resources.ApplyResources(this.pictureBoxSubjectType, "pictureBoxSubjectType");
this.pictureBoxSubjectType.Name = "pictureBoxSubjectType";
this.pictureBoxSubjectType.TabStop = false;
//
// dataGridViewTextBoxColumn2
//
this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewTextBoxColumn2.DefaultCellStyle = dataGridViewCellStyle3;
resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2");
this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
this.dataGridViewTextBoxColumn2.ReadOnly = true;
this.dataGridViewTextBoxColumn2.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridViewTextBoxColumn2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// dataGridViewTextBoxColumn3
//
this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3");
this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
this.dataGridViewTextBoxColumn3.ReadOnly = true;
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.labelBlurb, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.pictureBoxSubjectType, 0, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// RoleSelectionDialog
//
this.AcceptButton = this.buttonSave;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.tableLayoutPanel2);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Name = "RoleSelectionDialog";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.gridRoles)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxSubjectType)).EndInit();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button buttonSave;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label labelBlurb;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.DataGridView gridRoles;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
private System.Windows.Forms.Label labelDescription;
private System.Windows.Forms.PictureBox pictureBoxSubjectType;
private System.Windows.Forms.DataGridViewCheckBoxColumn ColumnRolesCheckBox;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
}
}
| |
// 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;
/// <summary>
/// System.Collections.Generic.List.LastIndexOf(T item, Int32,Int32)
/// </summary>
public class ListLastIndexOf3
{
#region Public Methods
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;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int");
try
{
int[] iArray = new int[1000];
for (int i = 0; i < 1000; i++)
{
iArray[i] = i;
}
List<int> listObject = new List<int>(iArray);
int ob = this.GetInt32(0, 1000);
int result = listObject.LastIndexOf(ob, 999, 1000);
if (result != ob)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string");
try
{
string[] strArray = { "apple", "dog", "banana", "chocolate", "dog", "food" };
List<string> listObject = new List<string>(strArray);
int result = listObject.LastIndexOf("dog", 3, 3);
if (result != 1)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type");
try
{
MyClass myclass1 = new MyClass();
MyClass myclass2 = new MyClass();
MyClass myclass3 = new MyClass();
MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 };
List<MyClass> listObject = new List<MyClass>(mc);
int result = listObject.LastIndexOf(myclass3, 2, 1);
if (result != 2)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: There are many element in the list with the same value");
try
{
string[] strArray = { "apple", "banana", "chocolate", "banana", "banana", "dog", "banana", "food" };
List<string> listObject = new List<string>(strArray);
int result = listObject.LastIndexOf("banana", 2, 3);
if (result != 1)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Do not find the element ");
try
{
int[] iArray = { 1, 9, -8, 3, 6, -1, 8, 7, -11, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, 6, 4);
if (result != -1)
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The index is negative");
try
{
int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, -4, 3);
TestLibrary.TestFramework.LogError("101", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: index and count do not specify a valid section in the List");
try
{
int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, 6, 10);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The count is a negative number");
try
{
int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 };
List<int> listObject = new List<int>(iArray);
int result = listObject.LastIndexOf(-11, 1, -1);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ListLastIndexOf3 test = new ListLastIndexOf3();
TestLibrary.TestFramework.BeginTestCase("ListLastIndexOf3");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
public class MyClass
{
}
| |
//
// CTFrame.cs: Implements the managed CTFrame
//
// Authors: Mono Team
//
// Copyright 2010 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.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.CoreGraphics;
namespace MonoMac.CoreText {
[Since (3,2)]
[Flags]
public enum CTFrameProgression : uint {
TopToBottom = 0,
RightToLeft = 1
}
[Since (4,2)]
public enum CTFramePathFillRule {
EvenOdd,
WindingNumber
}
[Since (3,2)]
public static class CTFrameAttributeKey {
public static readonly NSString Progression;
[Since (4,2)]
public static readonly NSString PathFillRule;
[Since (4,2)]
public static readonly NSString PathWidth;
[Since (4,3)]
public static readonly NSString ClippingPaths;
[Since (4,3)]
public static readonly NSString PathClippingPath;
static CTFrameAttributeKey ()
{
var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0);
if (handle == IntPtr.Zero)
return;
try {
Progression = Dlfcn.GetStringConstant (handle, "kCTFrameProgressionAttributeName");
PathFillRule = Dlfcn.GetStringConstant (handle, "kCTFramePathFillRuleAttributeName");
PathWidth = Dlfcn.GetStringConstant (handle, "kCTFramePathWidthAttributeName");
ClippingPaths = Dlfcn.GetStringConstant (handle, "kCTFrameClippingPathsAttributeName");
PathClippingPath = Dlfcn.GetStringConstant (handle, "kCTFramePathClippingPathAttributeName");
}
finally {
Dlfcn.dlclose (handle);
}
}
}
[Since (3,2)]
public class CTFrameAttributes {
public CTFrameAttributes ()
: this (new NSMutableDictionary ())
{
}
public CTFrameAttributes (NSDictionary dictionary)
{
if (dictionary == null)
throw new ArgumentNullException ("dictionary");
Dictionary = dictionary;
}
public NSDictionary Dictionary {get; private set;}
public CTFrameProgression? Progression {
get {
var value = Adapter.GetUInt32Value (Dictionary, CTFrameAttributeKey.Progression);
return !value.HasValue ? null : (CTFrameProgression?) value.Value;
}
set {
Adapter.SetValue (Dictionary, CTFrameAttributeKey.Progression,
value.HasValue ? (uint?) value.Value : null);
}
}
}
[Since (3,2)]
public class CTFrame : INativeObject, IDisposable {
internal IntPtr handle;
internal CTFrame (IntPtr handle, bool owns)
{
if (handle == IntPtr.Zero)
throw ConstructorError.ArgumentNull (this, "handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
public IntPtr Handle {
get { return handle; }
}
~CTFrame ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
[DllImport (Constants.CoreTextLibrary)]
extern static NSRange CTFrameGetStringRange (IntPtr handle);
[DllImport (Constants.CoreTextLibrary)]
extern static NSRange CTFrameGetVisibleStringRange (IntPtr handle);
public NSRange GetStringRange ()
{
return CTFrameGetStringRange (handle);
}
public NSRange GetVisibleStringRange ()
{
return CTFrameGetVisibleStringRange (handle);
}
[DllImport (Constants.CoreTextLibrary)]
extern static IntPtr CTFrameGetPath (IntPtr handle);
public CGPath GetPath ()
{
IntPtr h = CTFrameGetPath (handle);
return h == IntPtr.Zero ? null : new CGPath (h, true);
}
[DllImport (Constants.CoreTextLibrary)]
extern static IntPtr CTFrameGetFrameAttributes (IntPtr handle);
public CTFrameAttributes GetFrameAttributes ()
{
var attrs = (NSDictionary) Runtime.GetNSObject (CTFrameGetFrameAttributes (handle));
return attrs == null ? null : new CTFrameAttributes (attrs);
}
[DllImport (Constants.CoreTextLibrary)]
extern static IntPtr CTFrameGetLines (IntPtr handle);
public CTLine [] GetLines ()
{
var cfArrayRef = CTFrameGetLines (handle);
if (cfArrayRef == IntPtr.Zero)
return new CTLine [0];
return NSArray.ArrayFromHandleFunc<CTLine> (cfArrayRef, (p) => {
// We need to take a ref, since we dispose it later.
return new CTLine (p, false);
});
}
[DllImport (Constants.CoreTextLibrary)]
extern static void CTFrameGetLineOrigins(IntPtr handle, NSRange range, [Out] PointF[] origins);
public void GetLineOrigins (NSRange range, PointF[] origins)
{
if (origins == null)
throw new ArgumentNullException ("origins");
if (range.Length != 0 && origins.Length < range.Length)
throw new ArgumentException ("origins must contain at least range.Length elements.", "origins");
else if (origins.Length < CFArray.GetCount (CTFrameGetLines (handle)))
throw new ArgumentException ("origins must contain at least GetLines().Length elements.", "origins");
CTFrameGetLineOrigins (handle, range, origins);
}
[DllImport (Constants.CoreTextLibrary)]
extern static void CTFrameDraw (IntPtr handle, IntPtr context);
public void Draw (CGContext ctx)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
CTFrameDraw (handle, ctx.Handle);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DictionaryOperations operations.
/// </summary>
internal partial class DictionaryOperations : IServiceOperations<AzureCompositeModelClient>, IDictionaryOperations
{
/// <summary>
/// Initializes a new instance of the DictionaryOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DictionaryOperations(AzureCompositeModelClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModelClient
/// </summary>
public AzureCompositeModelClient Client { get; private set; }
/// <summary>
/// Get complex types with dictionary property
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with dictionary property
/// </summary>
/// <param name='defaultProgram'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
DictionaryWrapper complexBody = new DictionaryWrapper();
if (defaultProgram != null)
{
complexBody.DefaultProgram = defaultProgram;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new 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>
/// Get complex types with dictionary property which is empty
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types with dictionary property which is empty
/// </summary>
/// <param name='defaultProgram'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> defaultProgram = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
DictionaryWrapper complexBody = new DictionaryWrapper();
if (defaultProgram != null)
{
complexBody.DefaultProgram = defaultProgram;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/empty").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new 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>
/// Get complex types with dictionary property which is null
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/null").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get complex types with dictionary property while server doesn't provide a
/// response payload
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/dictionary/typed/notprovided").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", 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 (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<DictionaryWrapper>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DictionaryWrapper>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace DoFactory.HeadFirst.Factory.Method.Pizza
{
class PizzaTestDrive
{
static void Main(string[] args)
{
PizzaStore nyStore = new NYPizzaStore();
PizzaStore chicagoStore = new ChicagoPizzaStore();
Pizza pizza = nyStore.OrderPizza("cheese");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");
pizza = chicagoStore.OrderPizza("cheese");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");
pizza = nyStore.OrderPizza("clam");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");
pizza = chicagoStore.OrderPizza("clam");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");
pizza = nyStore.OrderPizza("pepperoni");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");
pizza = chicagoStore.OrderPizza("pepperoni");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");
pizza = nyStore.OrderPizza("veggie");
Console.WriteLine("Ethan ordered a " + pizza.Name + "\n");
pizza = chicagoStore.OrderPizza("veggie");
Console.WriteLine("Joel ordered a " + pizza.Name + "\n");
// Wait for user
Console.ReadKey();
}
}
#region Pizza Stores
public abstract class PizzaStore
{
public abstract Pizza CreatePizza(string item);
public Pizza OrderPizza(string type)
{
Pizza pizza = CreatePizza(type);
Console.WriteLine("--- Making a " + pizza.Name + " ---");
pizza.Prepare();
pizza.Bake();
pizza.Cut();
pizza.Box();
return pizza;
}
}
public class NYPizzaStore : PizzaStore
{
public override Pizza CreatePizza(String item)
{
Pizza pizza = null;
switch (item)
{
case "cheese":
pizza = new NYStyleCheesePizza();
break;
case "veggie":
pizza = new NYStyleVeggiePizza();
break;
case "clam":
pizza = new NYStyleClamPizza();
break;
case "pepperoni":
pizza = new NYStylePepperoniPizza();
break;
}
return pizza;
}
}
public class ChicagoPizzaStore : PizzaStore
{
public override Pizza CreatePizza(String item)
{
Pizza pizza = null;
switch (item)
{
case "cheese":
pizza = new ChicagoStyleCheesePizza();
break;
case "veggie":
pizza = new ChicagoStyleVeggiePizza();
break;
case "clam":
pizza = new ChicagoStyleClamPizza();
break;
case "pepperoni":
pizza = new ChicagoStylePepperoniPizza();
break;
}
return pizza;
}
}
// Alternatively use this store
public class DependentPizzaStore
{
public Pizza CreatePizza(string style, string type)
{
Pizza pizza = null;
if (style == "NY")
{
switch (type)
{
case "cheese":
pizza = new NYStyleCheesePizza();
break;
case "veggie":
pizza = new NYStyleVeggiePizza();
break;
case "clam":
pizza = new NYStyleClamPizza();
break;
case "pepperoni":
pizza = new NYStylePepperoniPizza();
break;
}
}
else if (style == "Chicago")
{
switch (type)
{
case "cheese":
pizza = new ChicagoStyleCheesePizza();
break;
case "veggie":
pizza = new ChicagoStyleVeggiePizza();
break;
case "clam":
pizza = new ChicagoStyleClamPizza();
break;
case "pepperoni":
pizza = new ChicagoStylePepperoniPizza();
break;
}
}
else
{
Console.WriteLine("Error: invalid store");
return null;
}
pizza.Prepare();
pizza.Bake();
pizza.Cut();
pizza.Box();
return pizza;
}
}
#endregion
#region Pizzas
public abstract class Pizza
{
public Pizza()
{
Toppings = new List<string>();
}
public string Name { get; set; }
public string Dough { get; set; }
public string Sauce { get; set; }
public List<string> Toppings { get; set; }
public void Prepare()
{
Console.WriteLine("Preparing " + Name);
Console.WriteLine("Tossing dough...");
Console.WriteLine("Adding sauce...");
Console.WriteLine("Adding toppings: ");
foreach (string topping in Toppings)
{
Console.WriteLine(" " + topping);
}
}
public void Bake()
{
Console.WriteLine("Bake for 25 minutes at 350");
}
public virtual void Cut()
{
Console.WriteLine("Cutting the pizza into diagonal slices");
}
public void Box()
{
Console.WriteLine("Place pizza in official PizzaStore box");
}
public override string ToString()
{
StringBuilder display = new StringBuilder();
display.Append("---- " + Name + " ----\n");
display.Append(Dough + "\n");
display.Append(Sauce + "\n");
foreach (string topping in Toppings)
{
display.Append(topping.ToString() + "\n");
}
return display.ToString();
}
}
public class ChicagoStyleVeggiePizza : Pizza
{
public ChicagoStyleVeggiePizza()
{
Name = "Chicago Deep Dish Veggie Pizza";
Dough = "Extra Thick Crust Dough";
Sauce = "Plum Tomato Sauce";
Toppings.Add("Shredded Mozzarella Cheese");
Toppings.Add("Black Olives");
Toppings.Add("Spinach");
Toppings.Add("Eggplant");
}
public override void Cut()
{
Console.WriteLine("Cutting the pizza into square slices");
}
}
public class ChicagoStylePepperoniPizza : Pizza
{
public ChicagoStylePepperoniPizza()
{
Name = "Chicago Style Pepperoni Pizza";
Dough = "Extra Thick Crust Dough";
Sauce = "Plum Tomato Sauce";
Toppings.Add("Shredded Mozzarella Cheese");
Toppings.Add("Black Olives");
Toppings.Add("Spinach");
Toppings.Add("Eggplant");
Toppings.Add("Sliced Pepperoni");
}
public override void Cut()
{
Console.WriteLine("Cutting the pizza into square slices");
}
}
public class ChicagoStyleClamPizza : Pizza
{
public ChicagoStyleClamPizza()
{
Name = "Chicago Style Clam Pizza";
Dough = "Extra Thick Crust Dough";
Sauce = "Plum Tomato Sauce";
Toppings.Add("Shredded Mozzarella Cheese");
Toppings.Add("Frozen Clams from Chesapeake Bay");
}
public override void Cut()
{
Console.WriteLine("Cutting the pizza into square slices");
}
}
public class ChicagoStyleCheesePizza : Pizza
{
public ChicagoStyleCheesePizza()
{
Name = "Chicago Style Deep Dish Cheese Pizza";
Dough = "Extra Thick Crust Dough";
Sauce = "Plum Tomato Sauce";
Toppings.Add("Shredded Mozzarella Cheese");
}
public override void Cut()
{
Console.WriteLine("Cutting the pizza into square slices");
}
}
public class NYStyleVeggiePizza : Pizza
{
public NYStyleVeggiePizza()
{
Name = "NY Style Veggie Pizza";
Dough = "Thin Crust Dough";
Sauce = "Marinara Sauce";
Toppings.Add("Grated Reggiano Cheese");
Toppings.Add("Garlic");
Toppings.Add("Onion");
Toppings.Add("Mushrooms");
Toppings.Add("Red Pepper");
}
}
public class NYStylePepperoniPizza : Pizza
{
public NYStylePepperoniPizza()
{
Name = "NY Style Pepperoni Pizza";
Dough = "Thin Crust Dough";
Sauce = "Marinara Sauce";
Toppings.Add("Grated Reggiano Cheese");
Toppings.Add("Sliced Pepperoni");
Toppings.Add("Garlic");
Toppings.Add("Onion");
Toppings.Add("Mushrooms");
Toppings.Add("Red Pepper");
}
}
public class NYStyleClamPizza : Pizza
{
public NYStyleClamPizza()
{
Name = "NY Style Clam Pizza";
Dough = "Thin Crust Dough";
Sauce = "Marinara Sauce";
Toppings.Add("Grated Reggiano Cheese");
Toppings.Add("Fresh Clams from Long Island Sound");
}
}
public class NYStyleCheesePizza : Pizza
{
public NYStyleCheesePizza()
{
Name = "NY Style Sauce and Cheese Pizza";
Dough = "Thin Crust Dough";
Sauce = "Marinara Sauce";
Toppings.Add("Grated Reggiano Cheese");
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using Nop.Core.Domain.Common;
using Nop.Services.Localization;
namespace Nop.Services.Common
{
/// <summary>
/// Address attribute parser
/// </summary>
public partial class AddressAttributeParser : IAddressAttributeParser
{
private readonly IAddressAttributeService _addressAttributeService;
private readonly ILocalizationService _localizationService;
public AddressAttributeParser(IAddressAttributeService addressAttributeService,
ILocalizationService localizationService)
{
this._addressAttributeService = addressAttributeService;
this._localizationService = localizationService;
}
/// <summary>
/// Gets selected address attribute identifiers
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Selected address attribute identifiers</returns>
protected virtual IList<int> ParseAddressAttributeIds(string attributesXml)
{
var ids = new List<int>();
if (String.IsNullOrEmpty(attributesXml))
return ids;
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(attributesXml);
foreach (XmlNode node in xmlDoc.SelectNodes(@"//Attributes/AddressAttribute"))
{
if (node.Attributes != null && node.Attributes["ID"] != null)
{
string str1 = node.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
ids.Add(id);
}
}
}
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return ids;
}
/// <summary>
/// Gets selected address attributes
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Selected address attributes</returns>
public virtual IList<AddressAttribute> ParseAddressAttributes(string attributesXml)
{
var result = new List<AddressAttribute>();
if (String.IsNullOrEmpty(attributesXml))
return result;
var ids = ParseAddressAttributeIds(attributesXml);
foreach (int id in ids)
{
var attribute = _addressAttributeService.GetAddressAttributeById(id);
if (attribute != null)
{
result.Add(attribute);
}
}
return result;
}
/// <summary>
/// Get address attribute values
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Address attribute values</returns>
public virtual IList<AddressAttributeValue> ParseAddressAttributeValues(string attributesXml)
{
var values = new List<AddressAttributeValue>();
if (String.IsNullOrEmpty(attributesXml))
return values;
var attributes = ParseAddressAttributes(attributesXml);
foreach (var attribute in attributes)
{
if (!attribute.ShouldHaveValues())
continue;
var valuesStr = ParseValues(attributesXml, attribute.Id);
foreach (string valueStr in valuesStr)
{
if (!String.IsNullOrEmpty(valueStr))
{
int id;
if (int.TryParse(valueStr, out id))
{
var value = _addressAttributeService.GetAddressAttributeValueById(id);
if (value != null)
values.Add(value);
}
}
}
}
return values;
}
/// <summary>
/// Gets selected address attribute value
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="addressAttributeId">Address attribute identifier</param>
/// <returns>Address attribute value</returns>
public virtual IList<string> ParseValues(string attributesXml, int addressAttributeId)
{
var selectedAddressAttributeValues = new List<string>();
if (String.IsNullOrEmpty(attributesXml))
return selectedAddressAttributeValues;
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(attributesXml);
var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/AddressAttribute");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["ID"] != null)
{
string str1 = node1.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
if (id == addressAttributeId)
{
var nodeList2 = node1.SelectNodes(@"AddressAttributeValue/Value");
foreach (XmlNode node2 in nodeList2)
{
string value = node2.InnerText.Trim();
selectedAddressAttributeValues.Add(value);
}
}
}
}
}
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return selectedAddressAttributeValues;
}
/// <summary>
/// Adds an attribute
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="attribute">Address attribute</param>
/// <param name="value">Value</param>
/// <returns>Attributes</returns>
public virtual string AddAddressAttribute(string attributesXml, AddressAttribute attribute, string value)
{
string result = string.Empty;
try
{
var xmlDoc = new XmlDocument();
if (String.IsNullOrEmpty(attributesXml))
{
var element1 = xmlDoc.CreateElement("Attributes");
xmlDoc.AppendChild(element1);
}
else
{
xmlDoc.LoadXml(attributesXml);
}
var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes");
XmlElement attributeElement = null;
//find existing
var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/AddressAttribute");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["ID"] != null)
{
string str1 = node1.Attributes["ID"].InnerText.Trim();
int id;
if (int.TryParse(str1, out id))
{
if (id == attribute.Id)
{
attributeElement = (XmlElement)node1;
break;
}
}
}
}
//create new one if not found
if (attributeElement == null)
{
attributeElement = xmlDoc.CreateElement("AddressAttribute");
attributeElement.SetAttribute("ID", attribute.Id.ToString());
rootElement.AppendChild(attributeElement);
}
var attributeValueElement = xmlDoc.CreateElement("AddressAttributeValue");
attributeElement.AppendChild(attributeValueElement);
var attributeValueValueElement = xmlDoc.CreateElement("Value");
attributeValueValueElement.InnerText = value;
attributeValueElement.AppendChild(attributeValueValueElement);
result = xmlDoc.OuterXml;
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return result;
}
/// <summary>
/// Validates address attributes
/// </summary>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetAttributeWarnings(string attributesXml)
{
var warnings = new List<string>();
//ensure it's our attributes
var attributes1 = ParseAddressAttributes(attributesXml);
//validate required address attributes (whether they're chosen/selected/entered)
var attributes2 = _addressAttributeService.GetAllAddressAttributes();
foreach (var a2 in attributes2)
{
if (a2.IsRequired)
{
bool found = false;
//selected address attributes
foreach (var a1 in attributes1)
{
if (a1.Id == a2.Id)
{
var valuesStr = ParseValues(attributesXml, a1.Id);
foreach (string str1 in valuesStr)
{
if (!String.IsNullOrEmpty(str1.Trim()))
{
found = true;
break;
}
}
}
}
//if not found
if (!found)
{
var notFoundWarning = string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetLocalized(a => a.Name));
warnings.Add(notFoundWarning);
}
}
}
return warnings;
}
}
}
| |
// 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.ComponentModel;
using System.Globalization;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
namespace System.ServiceModel
{
public sealed class MessageSecurityOverTcp
{
internal const MessageCredentialType DefaultClientCredentialType = MessageCredentialType.Windows;
internal const string defaultServerIssuedTransitionTokenLifetimeString = "00:15:00";
internal static readonly TimeSpan defaultServerIssuedTransitionTokenLifetime = TimeSpan.Parse(defaultServerIssuedTransitionTokenLifetimeString, CultureInfo.InvariantCulture);
private MessageCredentialType _clientCredentialType;
SecurityAlgorithmSuite algorithmSuite;
bool wasAlgorithmSuiteSet;
public MessageSecurityOverTcp()
{
_clientCredentialType = DefaultClientCredentialType;
algorithmSuite = SecurityAlgorithmSuite.Default;
}
[DefaultValue(MessageSecurityOverTcp.DefaultClientCredentialType)]
public MessageCredentialType ClientCredentialType
{
get { return _clientCredentialType; }
set
{
if (!MessageCredentialTypeHelper.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
_clientCredentialType = value;
}
}
[DefaultValue(typeof(SecurityAlgorithmSuite))]
public SecurityAlgorithmSuite AlgorithmSuite
{
get { return this.algorithmSuite; }
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.algorithmSuite = value;
wasAlgorithmSuiteSet = true;
}
}
internal bool WasAlgorithmSuiteSet
{
get { return this.wasAlgorithmSuiteSet; }
}
// TODO: [MethodImpl(MethodImplOptions.NoInlining)]
internal SecurityBindingElement CreateSecurityBindingElement(bool isSecureTransportMode, bool isReliableSession, BindingElement transportBindingElement)
{
SecurityBindingElement result;
SecurityBindingElement oneShotSecurity;
if (isSecureTransportMode)
{
switch (this._clientCredentialType)
{
case MessageCredentialType.None:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ClientCredentialTypeMustBeSpecifiedForMixedMode));
case MessageCredentialType.UserName:
oneShotSecurity = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
break;
case MessageCredentialType.Certificate:
oneShotSecurity = SecurityBindingElement.CreateCertificateOverTransportBindingElement();
break;
case MessageCredentialType.Windows:
oneShotSecurity = SecurityBindingElement.CreateSspiNegotiationOverTransportBindingElement(true);
break;
case MessageCredentialType.IssuedToken:
oneShotSecurity = SecurityBindingElement.CreateIssuedTokenOverTransportBindingElement(IssuedSecurityTokenParameters.CreateInfoCardParameters(new SecurityStandardsManager(), this.algorithmSuite));
break;
default:
Fx.Assert("unknown ClientCredentialType");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
result = SecurityBindingElement.CreateSecureConversationBindingElement(oneShotSecurity);
}
else
{
switch (this._clientCredentialType)
{
case MessageCredentialType.None:
oneShotSecurity = SecurityBindingElement.CreateSslNegotiationBindingElement(false, true);
break;
case MessageCredentialType.UserName:
// require cancellation so that impersonation is possible
oneShotSecurity = SecurityBindingElement.CreateUserNameForSslBindingElement(true);
break;
case MessageCredentialType.Certificate:
oneShotSecurity = SecurityBindingElement.CreateSslNegotiationBindingElement(true, true);
break;
case MessageCredentialType.Windows:
// require cancellation so that impersonation is possible
oneShotSecurity = SecurityBindingElement.CreateSspiNegotiationBindingElement(true);
break;
case MessageCredentialType.IssuedToken:
oneShotSecurity = SecurityBindingElement.CreateIssuedTokenForSslBindingElement(IssuedSecurityTokenParameters.CreateInfoCardParameters(new SecurityStandardsManager(), this.algorithmSuite), true);
break;
default:
Fx.Assert("unknown ClientCredentialType");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
result = SecurityBindingElement.CreateSecureConversationBindingElement(oneShotSecurity, true);
}
// set the algorithm suite and issued token params if required
result.DefaultAlgorithmSuite = oneShotSecurity.DefaultAlgorithmSuite = this.AlgorithmSuite;
result.IncludeTimestamp = true;
if (!isReliableSession)
{
result.LocalServiceSettings.ReconnectTransportOnFailure = false;
result.LocalClientSettings.ReconnectTransportOnFailure = false;
}
else
{
result.LocalServiceSettings.ReconnectTransportOnFailure = true;
result.LocalClientSettings.ReconnectTransportOnFailure = true;
}
// since a session is always bootstrapped, configure the transition sct to live for a short time only
oneShotSecurity.LocalServiceSettings.IssuedCookieLifetime = defaultServerIssuedTransitionTokenLifetime;
result.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
oneShotSecurity.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;
return result;
}
internal static bool TryCreate(SecurityBindingElement sbe, bool isReliableSession, BindingElement transportBindingElement, out MessageSecurityOverTcp messageSecurity)
{
//throw new NotImplementedException();
messageSecurity = null;
if (sbe == null)
return false;
// do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
if (!sbe.IncludeTimestamp)
return false;
if (sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11
&& sbe.MessageSecurityVersion != MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10)
{
return false;
}
if (sbe.SecurityHeaderLayout != SecurityProtocolFactory.defaultSecurityHeaderLayout)
return false;
MessageCredentialType clientCredentialType;
SecurityBindingElement bootstrapSecurity;
if (!SecurityBindingElement.IsSecureConversationBinding(sbe, true, out bootstrapSecurity))
return false;
bool isSecureTransportMode = bootstrapSecurity is TransportSecurityBindingElement;
IssuedSecurityTokenParameters infocardParameters;
if (isSecureTransportMode)
{
if (SecurityBindingElement.IsUserNameOverTransportBinding(bootstrapSecurity))
clientCredentialType = MessageCredentialType.UserName;
else if (SecurityBindingElement.IsCertificateOverTransportBinding(bootstrapSecurity))
clientCredentialType = MessageCredentialType.Certificate;
else if (SecurityBindingElement.IsSspiNegotiationOverTransportBinding(bootstrapSecurity, true))
clientCredentialType = MessageCredentialType.Windows;
else if (SecurityBindingElement.IsIssuedTokenOverTransportBinding(bootstrapSecurity, out infocardParameters))
{
if (!IssuedSecurityTokenParameters.IsInfoCardParameters(
infocardParameters,
new SecurityStandardsManager(
bootstrapSecurity.MessageSecurityVersion,
new WSSecurityTokenSerializer(
bootstrapSecurity.MessageSecurityVersion.SecurityVersion,
bootstrapSecurity.MessageSecurityVersion.TrustVersion,
bootstrapSecurity.MessageSecurityVersion.SecureConversationVersion,
true,
null, null, null))))
return false;
clientCredentialType = MessageCredentialType.IssuedToken;
}
else
{
// the standard binding does not support None client credential type in mixed mode
return false;
}
}
else
{
if (SecurityBindingElement.IsUserNameForSslBinding(bootstrapSecurity, true))
clientCredentialType = MessageCredentialType.UserName;
else if (SecurityBindingElement.IsSslNegotiationBinding(bootstrapSecurity, true, true))
clientCredentialType = MessageCredentialType.Certificate;
else if (SecurityBindingElement.IsSspiNegotiationBinding(bootstrapSecurity, true))
clientCredentialType = MessageCredentialType.Windows;
else if (SecurityBindingElement.IsIssuedTokenForSslBinding(bootstrapSecurity, true, out infocardParameters))
{
if (!IssuedSecurityTokenParameters.IsInfoCardParameters(
infocardParameters,
new SecurityStandardsManager(
bootstrapSecurity.MessageSecurityVersion,
new WSSecurityTokenSerializer(
bootstrapSecurity.MessageSecurityVersion.SecurityVersion,
bootstrapSecurity.MessageSecurityVersion.TrustVersion,
bootstrapSecurity.MessageSecurityVersion.SecureConversationVersion,
true,
null, null, null))))
return false;
clientCredentialType = MessageCredentialType.IssuedToken;
}
else if (SecurityBindingElement.IsSslNegotiationBinding(bootstrapSecurity, false, true))
clientCredentialType = MessageCredentialType.None;
else
return false;
}
messageSecurity = new MessageSecurityOverTcp();
messageSecurity.ClientCredentialType = clientCredentialType;
// set the algorithm suite and issued token params if required
if (clientCredentialType != MessageCredentialType.IssuedToken)
{
messageSecurity.AlgorithmSuite = bootstrapSecurity.DefaultAlgorithmSuite;
}
return true;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 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.Globalization;
using NUnit.Framework.Constraints;
namespace NUnit.Framework.Internal
{
/// <summary>
/// TextMessageWriter writes constraint descriptions and messages
/// in displayable form as a text stream. It tailors the display
/// of individual message components to form the standard message
/// format of NUnit assertion failure messages.
/// </summary>
public class TextMessageWriter : MessageWriter
{
#region Message Formats and Constants
private static readonly int DEFAULT_LINE_LENGTH = 78;
// Prefixes used in all failure messages. All must be the same
// length, which is held in the PrefixLength field. Should not
// contain any tabs or newline characters.
/// <summary>
/// Prefix used for the expected value line of a message
/// </summary>
public static readonly string Pfx_Expected = " Expected: ";
/// <summary>
/// Prefix used for the actual value line of a message
/// </summary>
public static readonly string Pfx_Actual = " But was: ";
/// <summary>
/// Length of a message prefix
/// </summary>
public static readonly int PrefixLength = Pfx_Expected.Length;
#endregion
#region Instance Fields
private int maxLineLength = DEFAULT_LINE_LENGTH;
private bool _sameValDiffTypes = false;
private string _expectedType, _actualType;
#endregion
#region Constructors
/// <summary>
/// Construct a TextMessageWriter
/// </summary>
public TextMessageWriter() { }
/// <summary>
/// Construct a TextMessageWriter, specifying a user message
/// and optional formatting arguments.
/// </summary>
/// <param name="userMessage"></param>
/// <param name="args"></param>
public TextMessageWriter(string userMessage, params object[] args)
{
if ( userMessage != null && userMessage != string.Empty)
this.WriteMessageLine(userMessage, args);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the maximum line length for this writer
/// </summary>
public override int MaxLineLength
{
get { return maxLineLength; }
set { maxLineLength = value; }
}
#endregion
#region Public Methods - High Level
/// <summary>
/// Method to write single line message with optional args, usually
/// written to precede the general failure message, at a given
/// indentation level.
/// </summary>
/// <param name="level">The indentation level of the message</param>
/// <param name="message">The message to be written</param>
/// <param name="args">Any arguments used in formatting the message</param>
public override void WriteMessageLine(int level, string message, params object[] args)
{
if (message != null)
{
while (level-- >= 0) Write(" ");
if (args != null && args.Length > 0)
message = string.Format(message, args);
WriteLine(MsgUtils.EscapeNullCharacters(message));
}
}
/// <summary>
/// Display Expected and Actual lines for a constraint. This
/// is called by MessageWriter's default implementation of
/// WriteMessageTo and provides the generic two-line display.
/// </summary>
/// <param name="result">The result of the constraint that failed</param>
public override void DisplayDifferences(ConstraintResult result)
{
WriteExpectedLine(result);
WriteActualLine(result);
}
/// <summary>
/// Gets the unique type name between expected and actual.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
/// <param name="expectedType">Output of the unique type name for expected</param>
/// <param name="actualType">Output of the unique type name for actual</param>
private void ResolveTypeNameDifference(object expected, object actual, out string expectedType, out string actualType) {
string[] expectedOriginalType = expected.GetType().ToString().Split('.');
string[] actualOriginalType = actual.GetType().ToString().Split('.');
int actualStart = 0, expectStart = 0;
for (int expectLen = expectedOriginalType.Length - 1,actualLen = actualOriginalType.Length - 1;
expectLen >= 0 && actualLen >= 0;
expectLen--, actualLen--) {
if (expectedOriginalType[expectLen] != actualOriginalType[actualLen]) {
actualStart = actualLen;
expectStart = expectLen;
break;
}
}
expectedType = " ("+String.Join(".", expectedOriginalType, expectStart, expectedOriginalType.Length- expectStart)+")";
actualType = " (" + String.Join(".", actualOriginalType, actualStart, actualOriginalType.Length- actualStart) + ")";
}
/// <summary>
/// Display Expected and Actual lines for given _values. This
/// method may be called by constraints that need more control over
/// the display of actual and expected _values than is provided
/// by the default implementation.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
public override void DisplayDifferences(object expected, object actual)
{
DisplayDifferences(expected, actual,null);
}
/// <summary>
/// Display Expected and Actual lines for given _values, including
/// a tolerance value on the expected line.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value causing the failure</param>
/// <param name="tolerance">The tolerance within which the test was made</param>
public override void DisplayDifferences(object expected, object actual, Tolerance tolerance)
{
if (expected != null && actual != null && expected.GetType() != actual.GetType() && MsgUtils.FormatValue(expected) == MsgUtils.FormatValue(actual) )
{
_sameValDiffTypes = true;
ResolveTypeNameDifference(expected, actual, out _expectedType, out _actualType);
}
WriteExpectedLine(expected, tolerance);
WriteActualLine(actual);
}
/// <summary>
/// Display the expected and actual string _values on separate lines.
/// If the mismatch parameter is >=0, an additional line is displayed
/// line containing a caret that points to the mismatch point.
/// </summary>
/// <param name="expected">The expected string value</param>
/// <param name="actual">The actual string value</param>
/// <param name="mismatch">The point at which the strings don't match or -1</param>
/// <param name="ignoreCase">If true, case is ignored in string comparisons</param>
/// <param name="clipping">If true, clip the strings to fit the max line length</param>
public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping)
{
// Maximum string we can display without truncating
int maxDisplayLength = MaxLineLength
- PrefixLength // Allow for prefix
- 2; // 2 quotation marks
if ( clipping )
MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch);
expected = MsgUtils.EscapeControlChars(expected);
actual = MsgUtils.EscapeControlChars(actual);
// The mismatch position may have changed due to clipping or white space conversion
mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase);
Write( Pfx_Expected );
Write( MsgUtils.FormatValue(expected) );
if ( ignoreCase )
Write( ", ignoring case" );
WriteLine();
WriteActualLine( actual );
//DisplayDifferences(expected, actual);
if (mismatch >= 0)
WriteCaretLine(mismatch);
}
#endregion
#region Public Methods - Low Level
/// <summary>
/// Writes the text for an actual value.
/// </summary>
/// <param name="actual">The actual value.</param>
public override void WriteActualValue(object actual)
{
WriteValue(actual);
}
/// <summary>
/// Writes the text for a generalized value.
/// </summary>
/// <param name="val">The value.</param>
public override void WriteValue(object val)
{
Write(MsgUtils.FormatValue(val));
}
/// <summary>
/// Writes the text for a collection value,
/// starting at a particular point, to a max length
/// </summary>
/// <param name="collection">The collection containing elements to write.</param>
/// <param name="start">The starting point of the elements to write</param>
/// <param name="max">The maximum number of elements to write</param>
public override void WriteCollectionElements(IEnumerable collection, long start, int max)
{
Write(MsgUtils.FormatCollection(collection, start, max));
}
#endregion
#region Helper Methods
/// <summary>
/// Write the generic 'Expected' line for a constraint
/// </summary>
/// <param name="result">The constraint that failed</param>
private void WriteExpectedLine(ConstraintResult result)
{
Write(Pfx_Expected);
WriteLine(result.Description);
}
/// <summary>
/// Write the generic 'Expected' line for a given value
/// </summary>
/// <param name="expected">The expected value</param>
private void WriteExpectedLine(object expected)
{
WriteExpectedLine(expected, null);
}
/// <summary>
/// Write the generic 'Expected' line for a given value
/// and tolerance.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="tolerance">The tolerance within which the test was made</param>
private void WriteExpectedLine(object expected, Tolerance tolerance)
{
Write(Pfx_Expected);
Write(MsgUtils.FormatValue(expected));
if (_sameValDiffTypes) {
Write(_expectedType);
}
if (tolerance != null && !tolerance.IsUnsetOrDefault)
{
Write(" +/- ");
Write(MsgUtils.FormatValue(tolerance.Amount));
if (tolerance.Mode != ToleranceMode.Linear)
Write(" {0}", tolerance.Mode);
}
WriteLine();
}
/// <summary>
/// Write the generic 'Actual' line for a constraint
/// </summary>
/// <param name="result">The ConstraintResult for which the actual value is to be written</param>
private void WriteActualLine(ConstraintResult result)
{
Write(Pfx_Actual);
result.WriteActualValueTo(this);
WriteLine();
//WriteLine(MsgUtils.FormatValue(result.ActualValue));
}
/// <summary>
/// Write the generic 'Actual' line for a given value
/// </summary>
/// <param name="actual">The actual value causing a failure</param>
private void WriteActualLine(object actual)
{
Write(Pfx_Actual);
WriteActualValue(actual);
if (_sameValDiffTypes)
{
Write(_actualType);
}
WriteLine();
}
private void WriteCaretLine(int mismatch)
{
// We subtract 2 for the initial 2 blanks and add back 1 for the initial quote
WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
#if !NET_NATIVE
namespace System.Xml.Serialization
{
internal class SourceInfo
{
//a[ia]
//((global::System.Xml.Serialization.XmlSerializerNamespaces)p[0])
private static Regex s_regex = new Regex("([(][(](?<t>[^)]+)[)])?(?<a>[^[]+)[[](?<ia>.+)[]][)]?");
//((global::Microsoft.CFx.Test.Common.TypeLibrary.IXSType_9)o), @"IXSType_9", @"", true, true);
private static Regex s_regex2 = new Regex("[(][(](?<cast>[^)]+)[)](?<arg>[^)]+)[)]");
private static readonly Lazy<MethodInfo> s_iListGetItemMethod = new Lazy<MethodInfo>(
() =>
{
return typeof(IList).GetMethod(
"get_Item",
new Type[] { typeof(Int32) }
);
});
public string Source;
public readonly string Arg;
public readonly MemberInfo MemberInfo;
public readonly Type Type;
public readonly CodeGenerator ILG;
public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg)
{
this.Source = source;
this.Arg = arg ?? source;
this.MemberInfo = memberInfo;
this.Type = type;
this.ILG = ilg;
}
public SourceInfo CastTo(TypeDesc td)
{
return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type, ILG);
}
public void LoadAddress(Type elementType)
{
InternalLoad(elementType, asAddress: true);
}
public void Load(Type elementType)
{
InternalLoad(elementType);
}
private void InternalLoad(Type elementType, bool asAddress = false)
{
Match match = s_regex.Match(Arg);
if (match.Success)
{
object varA = ILG.GetVariable(match.Groups["a"].Value);
Type varType = ILG.GetVariableType(varA);
object varIA = ILG.GetVariable(match.Groups["ia"].Value);
if (varType.IsArray)
{
ILG.Load(varA);
ILG.Load(varIA);
Type eType = varType.GetElementType();
if (CodeGenerator.IsNullableGenericType(eType))
{
ILG.Ldelema(eType);
ConvertNullableValue(eType, elementType);
}
else
{
if (eType.IsValueType)
{
ILG.Ldelema(eType);
if (!asAddress)
{
ILG.Ldobj(eType);
}
}
else
ILG.Ldelem(eType);
if (elementType != null)
ILG.ConvertValue(eType, elementType);
}
}
else
{
ILG.Load(varA);
ILG.Load(varIA);
MethodInfo get_Item = varType.GetMethod(
"get_Item",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(Int32) }
);
if (get_Item == null && typeof(IList).IsAssignableFrom(varType))
{
get_Item = s_iListGetItemMethod.Value;
}
Debug.Assert(get_Item != null);
ILG.Call(get_Item);
Type eType = get_Item.ReturnType;
if (CodeGenerator.IsNullableGenericType(eType))
{
LocalBuilder localTmp = ILG.GetTempLocal(eType);
ILG.Stloc(localTmp);
ILG.Ldloca(localTmp);
ConvertNullableValue(eType, elementType);
}
else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType)))
{
throw new CodeGeneratorConversionException(eType, elementType, asAddress, "IsNotAssignableFrom");
}
else
{
Convert(eType, elementType, asAddress);
}
}
}
else if (Source == "null")
{
ILG.Load(null);
}
else
{
object var;
Type varType;
if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null)
{
var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg);
varType = ILG.GetVariableType(var);
if (varType.IsValueType)
ILG.LoadAddress(var);
else
ILG.Load(var);
}
else
{
var = ILG.GetVariable(Arg);
varType = ILG.GetVariableType(var);
if (CodeGenerator.IsNullableGenericType(varType) &&
varType.GetGenericArguments()[0] == elementType)
{
ILG.LoadAddress(var);
ConvertNullableValue(varType, elementType);
}
else
{
if (asAddress)
ILG.LoadAddress(var);
else
ILG.Load(var);
}
}
if (MemberInfo != null)
{
Type memberType = (MemberInfo is FieldInfo) ?
((FieldInfo)MemberInfo).FieldType : ((PropertyInfo)MemberInfo).PropertyType;
if (CodeGenerator.IsNullableGenericType(memberType))
{
ILG.LoadMemberAddress(MemberInfo);
ConvertNullableValue(memberType, elementType);
}
else
{
ILG.LoadMember(MemberInfo);
Convert(memberType, elementType, asAddress);
}
}
else
{
match = s_regex2.Match(Source);
if (match.Success)
{
Debug.Assert(match.Groups["arg"].Value == Arg);
Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type));
if (asAddress)
ILG.ConvertAddress(varType, Type);
else
ILG.ConvertValue(varType, Type);
varType = Type;
}
Convert(varType, elementType, asAddress);
}
}
}
private void Convert(Type sourceType, Type targetType, bool asAddress)
{
if (targetType != null)
{
if (asAddress)
ILG.ConvertAddress(sourceType, targetType);
else
ILG.ConvertValue(sourceType, targetType);
}
}
private void ConvertNullableValue(Type nullableType, Type targetType)
{
System.Diagnostics.Debug.Assert(targetType == nullableType || targetType.IsAssignableFrom(nullableType.GetGenericArguments()[0]));
if (targetType != nullableType)
{
MethodInfo Nullable_get_Value = nullableType.GetMethod(
"get_Value",
CodeGenerator.InstanceBindingFlags,
CodeGenerator.EmptyTypeArray
);
ILG.Call(Nullable_get_Value);
if (targetType != null)
{
ILG.ConvertValue(Nullable_get_Value.ReturnType, targetType);
}
}
}
public static implicit operator string (SourceInfo source)
{
return source.Source;
}
public static bool operator !=(SourceInfo a, SourceInfo b)
{
if ((object)a != null)
return !a.Equals(b);
return (object)b != null;
}
public static bool operator ==(SourceInfo a, SourceInfo b)
{
if ((object)a != null)
return a.Equals(b);
return (object)b == null;
}
public override bool Equals(object obj)
{
if (obj == null)
return Source == null;
SourceInfo info = obj as SourceInfo;
if (info != null)
return Source == info.Source;
return false;
}
public override int GetHashCode()
{
return (Source == null) ? 0 : Source.GetHashCode();
}
}
}
#endif
| |
//
// Copyright 2012 Hakan Kjellerstrand
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Google.OrTools.ConstraintSolver;
public class EinavPuzzle2
{
/**
*
* A programming puzzle from Einav.
*
* From
* "A programming puzzle from Einav"
* http://gcanyon.wordpress.com/2009/10/28/a-programming-puzzle-from-einav/
* """
* My friend Einav gave me this programming puzzle to work on. Given
* this array of positive and negative numbers:
* 33 30 -10 -6 18 7 -11 -23 6
* ...
* -25 4 16 30 33 -23 -4 4 -23
*
* You can flip the sign of entire rows and columns, as many of them
* as you like. The goal is to make all the rows and columns sum to positive
* numbers (or zero), and then to find the solution (there are more than one)
* that has the smallest overall sum. So for example, for this array:
* 33 30 -10
* -16 19 9
* -17 -12 -14
* You could flip the sign for the bottom row to get this array:
* 33 30 -10
* -16 19 9
* 17 12 14
* Now all the rows and columns have positive sums, and the overall total is
* 108.
* But you could instead flip the second and third columns, and the second
* row, to get this array:
* 33 -30 10
* 16 19 9
* -17 12 14
* All the rows and columns still total positive, and the overall sum is just
* 66. So this solution is better (I don't know if it's the best)
* A pure brute force solution would have to try over 30 billion solutions.
* I wrote code to solve this in J. I'll post that separately.
* """
*
* Note:
* This is a port of Larent Perrons's Python version of my own
* einav_puzzle.py. He removed some of the decision variables and made it more
* efficient. Thanks!
*
* Also see http://www.hakank.org/or-tools/einav_puzzle2.py
*
*/
private static void Solve()
{
Solver solver = new Solver("EinavPuzzle2");
//
// Data
//
// Small problem
// int rows = 3;
// int cols = 3;
// int[,] data = {
// { 33, 30, -10},
// {-16, 19, 9},
// {-17, -12, -14}
// };
// Full problem
int rows = 27;
int cols = 9;
int[,] data = { { 33, 30, 10, -6, 18, -7, -11, 23, -6 }, { 16, -19, 9, -26, -8, -19, -8, -21, -14 },
{ 17, 12, -14, 31, -30, 13, -13, 19, 16 }, { -6, -11, 1, 17, -12, -4, -7, 14, -21 },
{ 18, -31, 34, -22, 17, -19, 20, 24, 6 }, { 33, -18, 17, -15, 31, -5, 3, 27, -3 },
{ -18, -20, -18, 31, 6, 4, -2, -12, 24 }, { 27, 14, 4, -29, -3, 5, -29, 8, -12 },
{ -15, -7, -23, 23, -9, -8, 6, 8, -12 }, { 33, -23, -19, -4, -8, -7, 11, -12, 31 },
{ -20, 19, -15, -30, 11, 32, 7, 14, -5 }, { -23, 18, -32, -2, -31, -7, 8, 24, 16 },
{ 32, -4, -10, -14, -6, -1, 0, 23, 23 }, { 25, 0, -23, 22, 12, 28, -27, 15, 4 },
{ -30, -13, -16, -3, -3, -32, -3, 27, -31 }, { 22, 1, 26, 4, -2, -13, 26, 17, 14 },
{ -9, -18, 3, -20, -27, -32, -11, 27, 13 }, { -17, 33, -7, 19, -32, 13, -31, -2, -24 },
{ -31, 27, -31, -29, 15, 2, 29, -15, 33 }, { -18, -23, 15, 28, 0, 30, -4, 12, -32 },
{ -3, 34, 27, -25, -18, 26, 1, 34, 26 }, { -21, -31, -10, -13, -30, -17, -12, -26, 31 },
{ 23, -31, -19, 21, -17, -10, 2, -23, 23 }, { -3, 6, 0, -3, -32, 0, -10, -25, 14 },
{ -19, 9, 14, -27, 20, 15, -5, -27, 18 }, { 11, -6, 24, 7, -17, 26, 20, -31, -25 },
{ -25, 4, -16, 30, 33, 23, -4, -4, 23 } };
IEnumerable<int> ROWS = Enumerable.Range(0, rows);
IEnumerable<int> COLS = Enumerable.Range(0, cols);
//
// Decision variables
//
IntVar[,] x = solver.MakeIntVarMatrix(rows, cols, -100, 100, "x");
IntVar[] x_flat = x.Flatten();
int[] signs_domain = { -1, 1 };
// This don't work at the moment...
IntVar[] row_signs = solver.MakeIntVarArray(rows, signs_domain, "row_signs");
IntVar[] col_signs = solver.MakeIntVarArray(cols, signs_domain, "col_signs");
// To optimize
IntVar total_sum = x_flat.Sum().VarWithName("total_sum");
//
// Constraints
//
foreach (int i in ROWS)
{
foreach (int j in COLS)
{
solver.Add(x[i, j] == data[i, j] * row_signs[i] * col_signs[j]);
}
}
// row sums
IntVar[] row_sums = (from i in ROWS select(from j in COLS select x[i, j]).ToArray().Sum().Var()).ToArray();
foreach (int i in ROWS)
{
row_sums[i].SetMin(0);
}
// col sums
IntVar[] col_sums = (from j in COLS select(from i in ROWS select x[i, j]).ToArray().Sum().Var()).ToArray();
foreach (int j in COLS)
{
col_sums[j].SetMin(0);
}
//
// Objective
//
OptimizeVar obj = total_sum.Minimize(1);
//
// Search
//
DecisionBuilder db = solver.MakePhase(col_signs.Concat(row_signs).ToArray(), Solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
Solver.ASSIGN_MAX_VALUE);
solver.NewSearch(db, obj);
while (solver.NextSolution())
{
Console.WriteLine("Sum: {0}", total_sum.Value());
Console.Write("row_sums: ");
foreach (int i in ROWS)
{
Console.Write(row_sums[i].Value() + " ");
}
Console.Write("\nrow_signs: ");
foreach (int i in ROWS)
{
Console.Write(row_signs[i].Value() + " ");
}
Console.Write("\ncol_sums: ");
foreach (int j in COLS)
{
Console.Write(col_sums[j].Value() + " ");
}
Console.Write("\ncol_signs: ");
foreach (int j in COLS)
{
Console.Write(col_signs[j].Value() + " ");
}
Console.WriteLine("\n");
foreach (int i in ROWS)
{
foreach (int j in COLS)
{
Console.Write("{0,3} ", x[i, j].Value());
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine("\nSolutions: {0}", solver.Solutions());
Console.WriteLine("WallTime: {0}ms", solver.WallTime());
Console.WriteLine("Failures: {0}", solver.Failures());
Console.WriteLine("Branches: {0} ", solver.Branches());
solver.EndSearch();
}
public static void Main(String[] args)
{
Solve();
}
}
| |
using CheckpointAndLevelEndDemo.DataTypes;
using FlatRedBall.TileGraphics;
using System;
using System.Collections.Generic;
using System.Linq;
using CheckpointAndLevelEndDemo.Performance;
using FlatRedBall.Graphics;
using System.Reflection;
using TMXGlueLib.DataTypes;
using System.Collections;
using FlatRedBall.Math.Geometry;
namespace FlatRedBall.TileEntities
{
public class InstantiationRestrictions
{
public AxisAlignedRectangle Bounds = null;
public List<string> InclusiveList = null;
}
public static class TileEntityInstantiator
{
public class Settings
{
public bool RemoveTileObjectsAfterEntityCreation = true;
}
public static Settings CurrentSettings { get; set; } = new Settings();
/// <summary>
/// A dictionary that stores all available values for a given type.
/// </summary>
/// <remarks>
/// The structure of this class is a dictionary, where each entry in the dictionary is a list of dictionaries. This mgiht
/// seem confusing so let's look at an example.
/// This was originally created to cache values from CSVs. Let's say there's a type called PlatformerValues.
/// The class PlatformerValues would be the key in the dictionary.
/// Of course, platformer values can be defined in multiple entities (if multiple entities are platformers).
/// Each CSV in each entity becomes 1 dictionary, but since there can be multiple CSVs, there is a list. Therefore, the struture
/// might look like this:
/// * PlatformerValues
/// * List from Entity 1
/// * OnGround
/// * InAir
/// * List from Entity 2
/// * OnGround
/// * In Air
/// // and so on...
/// </remarks>
static Dictionary<string, List<IDictionary>> allDictionaries = new Dictionary<string, List<IDictionary>>();
/// <summary>
/// Creates entities from a single layer for any tile with the EntityToCreate property.
/// </summary>
/// <param name="mapLayer">The layer to create entities from.</param>
/// <param name="layeredTileMap">The map which contains the mapLayer instance.</param>
public static void CreateEntitiesFrom(MapDrawableBatch mapLayer, LayeredTileMap layeredTileMap)
{
var entitiesToRemove = new List<string>();
CreateEntitiesFrom(entitiesToRemove, mapLayer, layeredTileMap.TileProperties, layeredTileMap.WidthPerTile ?? 16);
if(CurrentSettings.RemoveTileObjectsAfterEntityCreation)
{
foreach (var entityToRemove in entitiesToRemove)
{
string remove = entityToRemove;
mapLayer.RemoveTiles(t => t.Any(item => (item.Name == "EntityToCreate" || item.Name == "Type") && item.Value as string == remove), layeredTileMap.TileProperties);
}
}
}
public static void CreateEntitiesFrom(LayeredTileMap layeredTileMap, InstantiationRestrictions restrictions = null)
{
if(layeredTileMap != null)
{
var entitiesToRemove = new List<string>();
foreach (var layer in layeredTileMap.MapLayers)
{
CreateEntitiesFrom(entitiesToRemove, layer, layeredTileMap.TileProperties, layeredTileMap.WidthPerTile ?? 16, restrictions);
}
if(CurrentSettings.RemoveTileObjectsAfterEntityCreation)
{
foreach (var entityToRemove in entitiesToRemove)
{
string remove = entityToRemove;
layeredTileMap.RemoveTiles(t => t.Any(item => (item.Name == "EntityToCreate" || item.Name == "Type") && item.Value as string == remove), layeredTileMap.TileProperties);
}
}
foreach (var shapeCollection in layeredTileMap.ShapeCollections)
{
CreateEntitiesFromCircles(layeredTileMap, shapeCollection, restrictions);
CreateEntitiesFromRectangles(layeredTileMap, shapeCollection, restrictions);
CreateEntitiesFromPolygons(layeredTileMap, shapeCollection, restrictions);
}
}
}
private static void CreateEntitiesFromCircles(LayeredTileMap layeredTileMap, ShapeCollection shapeCollection, InstantiationRestrictions restrictions)
{
var circles = shapeCollection.Circles;
for (int i = circles.Count - 1; i > -1; i--)
{
var circle = circles[i];
if (!string.IsNullOrEmpty(circle.Name) && layeredTileMap.ShapeProperties.ContainsKey(circle.Name))
{
var properties = layeredTileMap.ShapeProperties[circle.Name];
var entityAddingProperty = properties.FirstOrDefault(item => item.Name == "EntityToCreate" || item.Name == "Type");
var entityType = entityAddingProperty.Value as string;
var shouldCreate = !string.IsNullOrEmpty(entityType);
if (restrictions?.InclusiveList != null)
{
shouldCreate = restrictions.InclusiveList.Contains(entityType);
}
if(shouldCreate)
{
IEntityFactory factory = GetFactory(entityType);
if(factory != null)
{
var entity = factory.CreateNew(null) as PositionedObject;
entity.Name = circle.Name;
ApplyPropertiesTo(entity, properties, circle.Position);
if(CurrentSettings.RemoveTileObjectsAfterEntityCreation)
{
shapeCollection.Circles.Remove(circle);
}
if (entity is Math.Geometry.ICollidable)
{
var entityCollision = (entity as Math.Geometry.ICollidable).Collision;
entityCollision.Circles.Add(circle);
circle.AttachTo(entity, false);
}
}
}
}
}
}
private static void CreateEntitiesFromRectangles(LayeredTileMap layeredTileMap, ShapeCollection shapeCollection, InstantiationRestrictions restrictions)
{
var rectangles = shapeCollection.AxisAlignedRectangles;
for (int i = rectangles.Count - 1; i > -1; i--)
{
var rectangle = rectangles[i];
if (!string.IsNullOrEmpty(rectangle.Name) && layeredTileMap.ShapeProperties.ContainsKey(rectangle.Name))
{
var properties = layeredTileMap.ShapeProperties[rectangle.Name];
var entityAddingProperty = properties.FirstOrDefault(item => item.Name == "EntityToCreate" || item.Name == "Type");
var entityType = entityAddingProperty.Value as string;
var shouldCreate = !string.IsNullOrEmpty(entityType);
if (restrictions?.InclusiveList != null)
{
shouldCreate = restrictions.InclusiveList.Contains(entityType);
}
if (shouldCreate)
{
IEntityFactory factory = GetFactory(entityType);
if(factory != null)
{
var entity = factory.CreateNew(null) as PositionedObject;
entity.Name = rectangle.Name;
ApplyPropertiesTo(entity, properties, rectangle.Position);
if(CurrentSettings.RemoveTileObjectsAfterEntityCreation)
{
shapeCollection.AxisAlignedRectangles.Remove(rectangle);
}
if (entity is Math.Geometry.ICollidable)
{
var entityCollision = (entity as Math.Geometry.ICollidable).Collision;
entityCollision.AxisAlignedRectangles.Add(rectangle);
rectangle.AttachTo(entity, false);
}
}
}
}
}
}
private static void CreateEntitiesFromPolygons(LayeredTileMap layeredTileMap, Math.Geometry.ShapeCollection shapeCollection, InstantiationRestrictions restrictions)
{
var polygons = shapeCollection.Polygons;
for (int i = polygons.Count - 1; i > -1; i--)
{
var polygon = polygons[i];
if (!string.IsNullOrEmpty(polygon.Name) && layeredTileMap.ShapeProperties.ContainsKey(polygon.Name))
{
var properties = layeredTileMap.ShapeProperties[polygon.Name];
var entityAddingProperty = properties.FirstOrDefault(item => item.Name == "EntityToCreate" || item.Name == "Type");
var entityType = entityAddingProperty.Value as string;
var shouldCreate = !string.IsNullOrEmpty(entityType);
if (restrictions?.InclusiveList != null)
{
shouldCreate = restrictions.InclusiveList.Contains(entityType);
}
if (shouldCreate)
{
IEntityFactory factory = GetFactory(entityType);
if(factory != null)
{
var entity = factory.CreateNew(null) as PositionedObject;
entity.Name = polygon.Name;
ApplyPropertiesTo(entity, properties, polygon.Position);
if (CurrentSettings.RemoveTileObjectsAfterEntityCreation)
{
shapeCollection.Polygons.Remove(polygon);
}
if (entity is Math.Geometry.ICollidable)
{
var entityCollision = (entity as Math.Geometry.ICollidable).Collision;
entityCollision.Polygons.Add(polygon);
polygon.AttachTo(entity, false);
}
}
}
}
}
}
private static void CreateEntitiesFrom(List<string> entitiesToRemove, MapDrawableBatch layer, Dictionary<string, List<NamedValue>> propertiesDictionary,
float tileSize,
InstantiationRestrictions restrictions = null)
{
var flatRedBallLayer = SpriteManager.Layers.FirstOrDefault(item => item.Batches.Contains(layer));
var dictionary = layer.NamedTileOrderedIndexes;
// layer needs its position updated:
layer.ForceUpdateDependencies();
foreach (var propertyList in propertiesDictionary.Values)
{
var property =
propertyList.FirstOrDefault(item2 => item2.Name == "EntityToCreate" || item2.Name == "Type");
if (!string.IsNullOrEmpty(property.Name))
{
var tileName = propertyList.FirstOrDefault(item => item.Name.ToLowerInvariant() == "name").Value as string;
var entityType = property.Value as string;
var shouldCreateEntityType =
!string.IsNullOrEmpty(entityType) && dictionary.ContainsKey(tileName);
if (shouldCreateEntityType && restrictions?.InclusiveList != null)
{
shouldCreateEntityType = restrictions.InclusiveList.Contains(entityType);
}
if (shouldCreateEntityType)
{
IEntityFactory factory = GetFactory(entityType);
if (factory == null)
{
bool isEntity = typesInThisAssembly.Any(item => item.Name.Contains($".Entities.") && item.Name.EndsWith(entityType));
if (isEntity)
{
string message =
$"The factory for entity {entityType} could not be found. To create instances of this entity, " +
"set its 'CreatedByOtherEntities' property to true in Glue.";
throw new Exception(message);
}
}
else
{
entitiesToRemove.Add(entityType);
var indexList = dictionary[tileName];
foreach (var tileIndex in indexList)
{
var shouldCreate = true;
var bounds = restrictions?.Bounds;
if (bounds != null)
{
layer.GetBottomLeftWorldCoordinateForOrderedTile(tileIndex, out float x, out float y);
x += tileSize / 2.0f;
y += tileSize / 2.0f;
shouldCreate = bounds.IsPointInside(x, y);
}
if(shouldCreate)
{
var entity = factory.CreateNew(flatRedBallLayer) as PositionedObject;
ApplyPropertiesTo(entity, layer, tileIndex, propertyList);
}
}
}
}
}
}
}
private static void ApplyPropertiesTo(PositionedObject entity, MapDrawableBatch layer, int tileIndex, List<NamedValue> propertiesToAssign)
{
int vertexIndex = tileIndex * 4;
var dimension =
(layer.Vertices[vertexIndex + 1].Position - layer.Vertices[vertexIndex].Position).Length();
float dimensionHalf = dimension / 2.0f;
float left;
float bottom;
layer.GetBottomLeftWorldCoordinateForOrderedTile(tileIndex, out left, out bottom);
Microsoft.Xna.Framework.Vector3 position = new Microsoft.Xna.Framework.Vector3(left, bottom, 0);
var bottomRight = layer.Vertices[tileIndex * 4 + 1].Position;
float xDifference = bottomRight.X - left;
float yDifference = bottomRight.Y - bottom;
if (yDifference != 0 || xDifference < 0)
{
float angle = (float)System.Math.Atan2(yDifference, xDifference);
entity.RotationZ = angle;
}
position += entity.RotationMatrix.Right * dimensionHalf;
position += entity.RotationMatrix.Up * dimensionHalf;
position += layer.Position;
ApplyPropertiesTo(entity, propertiesToAssign, position);
}
private static void ApplyPropertiesTo(PositionedObject entity, List<NamedValue> propertiesToAssign, Microsoft.Xna.Framework.Vector3 position)
{
if (entity != null)
{
entity.Position = position;
}
var entityType = entity.GetType();
var lateBinder = Instructions.Reflection.LateBinder.GetInstance(entityType);
foreach (var property in propertiesToAssign)
{
// If name is EntityToCreate, skip it:
string propertyName = property.Name;
bool shouldSet = propertyName != "EntityToCreate" &&
propertyName != "Type";
if (shouldSet)
{
if (propertyName == "name")
{
propertyName = "Name";
}
var valueToSet = property.Value;
var propertyType = property.Type;
if (string.IsNullOrEmpty(propertyType))
{
propertyType = TryGetPropertyType(entityType, propertyName);
}
valueToSet = ConvertValueAccordingToType(valueToSet, propertyName, propertyType, entityType);
try
{
switch(propertyName)
{
case "X":
if(valueToSet is float)
{
entity.X += (float)valueToSet;
}
else if(valueToSet is int)
{
entity.X += (int)valueToSet;
}
break;
case "Y":
if (valueToSet is float)
{
entity.Y += (float)valueToSet;
}
else if (valueToSet is int)
{
entity.Y += (int)valueToSet;
}
break;
default:
lateBinder.SetValue(entity, propertyName, valueToSet);
break;
}
}
catch (InvalidCastException e)
{
string assignedType = valueToSet.GetType().ToString() ?? "unknown type";
assignedType = GetFriendlyNameForType(assignedType);
string expectedType = "unknown type";
object outValue;
if (lateBinder.TryGetValue(entity, propertyName, out outValue) && outValue != null)
{
expectedType = outValue.GetType().ToString();
expectedType = GetFriendlyNameForType(expectedType);
}
// This means that the property exists but is of a different type.
string message = $"Attempted to assign the property {propertyName} " +
$"to a value of type {assignedType} but expected {expectedType}. " +
$"Check the property type in your TMX and make sure it matches the type on the entity.";
throw new Exception(message, e);
}
catch (Exception e)
{
// Since this code indiscriminately tries to set properties, it may set properties which don't
// actually exist. Therefore, we tolerate failures.
}
}
}
}
private static string TryGetPropertyType(Type entityType, string propertyName)
{
// todo - cache for perf
var property = entityType.GetProperty(propertyName);
if (property != null)
{
return property?.PropertyType.FullName;
}
else
{
var field = entityType.GetField(propertyName);
return field?.FieldType.FullName;
}
}
public static void RegisterDictionary<T>(Dictionary<string, T> data)
{
#if DEBUG
if(data == null)
{
throw new ArgumentNullException("The argument data is null - do you need to call LoadStaticContent on the type containing this dictionary?");
}
#endif
var type = typeof(T).FullName;
if (allDictionaries.ContainsKey(type) == false)
{
allDictionaries.Add(type, new List<IDictionary>());
}
if (allDictionaries[type].Contains(data) == false)
{
allDictionaries[type].Add(data);
}
}
private static string GetFriendlyNameForType(string type)
{
switch (type)
{
case "System.String": return "string";
case "System.Single": return "float";
}
return type;
}
private static object ConvertValueAccordingToType(object valueToSet, string valueName, string valueType, Type entityType)
{
if (valueType == "bool")
{
bool boolValue = false;
if (bool.TryParse((string)valueToSet, out boolValue))
{
valueToSet = boolValue;
}
}
else if (valueType == "float")
{
float floatValue;
if (float.TryParse((string)valueToSet, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out floatValue))
{
valueToSet = floatValue;
}
}
else if (valueType == "int")
{
int intValue;
if (int.TryParse((string)valueToSet, out intValue))
{
valueToSet = intValue;
}
}
else if (valueName == "CurrentState")
{
// Since it's part of the class, it uses the "+" separator
var enumTypeName = entityType.FullName + "+VariableState";
var enumType = typesInThisAssembly.FirstOrDefault(item => item.FullName == enumTypeName);
valueToSet = Enum.Parse(enumType, (string)valueToSet);
}
else if (valueType != null && allDictionaries.ContainsKey(valueType))
{
var list = allDictionaries[valueType];
foreach (var dictionary in list)
{
if (dictionary.Contains(valueToSet))
{
valueToSet = dictionary[valueToSet];
break;
}
}
}
// todo - could add support for more file types here like textures, etc...
else if (valueType == "FlatRedBall.Graphics.Animation.AnimationChainList")
{
var method = entityType.GetMethod("GetFile");
valueToSet = method.Invoke(null, new object[] { valueToSet });
}
// If this has a + in it, then that might mean it's a state. We should try to get the type, and if we find it, stuff
// it in allDictionaries to make future calls faster
else if (valueType != null && valueType.Contains("+"))
{
var stateType = typesInThisAssembly.FirstOrDefault(item => item.FullName == valueType);
if (stateType != null)
{
Dictionary<string, object> allValues = new Dictionary<string, object>();
var fields = stateType.GetFields(BindingFlags.Static | BindingFlags.Public);
foreach (var field in fields)
{
allValues[field.Name] = field.GetValue(null);
}
// The list has all the dictioanries that contain values. But for states there is only one set of values, so
// we create a list
List<IDictionary> list = new List<IDictionary>();
list.Add(allValues);
allDictionaries[valueType] = list;
if (allValues.ContainsKey((string)valueToSet))
{
valueToSet = allValues[(string)valueToSet];
}
}
}
else if (valueType?.Contains(".") == true)
{
var type = typeof(TileEntityInstantiator).Assembly.GetType(valueType);
if (type != null && type.IsEnum)
{
valueToSet = Enum.Parse(type, (string)valueToSet);
}
}
return valueToSet;
}
private static void AssignCustomPropertyTo(PositionedObject entity, NamedValue property)
{
throw new NotImplementedException();
}
static Type[] typesInThisAssembly;
public static IEntityFactory GetFactory(string entityType)
{
if (typesInThisAssembly == null)
{
#if WINDOWS_8 || UWP
var assembly = typeof(TileEntityInstantiator).GetTypeInfo().Assembly;
typesInThisAssembly = assembly.DefinedTypes.Select(item=>item.AsType()).ToArray();
#else
var assembly = Assembly.GetExecutingAssembly();
typesInThisAssembly = assembly.GetTypes();
#endif
}
#if WINDOWS_8 || UWP
var filteredTypes =
typesInThisAssembly.Where(t => t.GetInterfaces().Contains(typeof(IEntityFactory))
&& t.GetConstructors().Any(c=>c.GetParameters().Count() == 0));
#else
var filteredTypes =
typesInThisAssembly.Where(t => t.GetInterfaces().Contains(typeof(IEntityFactory))
&& t.GetConstructor(Type.EmptyTypes) != null);
#endif
var factories = filteredTypes
.Select(
t =>
{
#if WINDOWS_8 || UWP
var propertyInfo = t.GetProperty("Self");
#else
var propertyInfo = t.GetProperty("Self");
#endif
var value = propertyInfo.GetValue(null, null);
return value as IEntityFactory;
}).ToList();
var factory = factories.FirstOrDefault(item =>
{
var type = item.GetType();
var methodInfo = type.GetMethod("CreateNew", new[] { typeof(Layer), typeof(float), typeof(float) });
var returntypeString = methodInfo.ReturnType.Name;
return entityType == returntypeString ||
entityType.EndsWith("\\" + returntypeString) ||
entityType.EndsWith("/" + returntypeString);
});
return factory;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using Xunit;
using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources;
using System.Reflection;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class WinMdTests : ExpressionCompilerTestBase
{
/// <summary>
/// Handle runtime assemblies rather than Windows.winmd
/// (compile-time assembly) since those are the assemblies
/// loaded in the debuggee.
/// </summary>
[WorkItem(981104)]
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs);
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections");
Assert.True(runtimeAssemblies.Length >= 2);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
SymReaderFactory.CreateReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("(p == null) ? f : null", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}");
}
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies_ExternAlias()
{
var source =
@"extern alias X;
class C
{
static void M(X::Windows.Storage.StorageFolder f)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r));
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage");
Assert.True(runtimeAssemblies.Length >= 1);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
SymReaderFactory.CreateReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}");
}
[Fact]
public void Win8OnWin8()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[Fact]
public void Win8OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[WorkItem(1108135)]
[Fact]
public void Win10OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows");
}
private void CompileTimeAndRuntimeAssemblies(
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences,
string storageAssemblyName)
{
var source =
@"class C
{
static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f)
{
}
}";
var runtime = CreateRuntime(source, compileReferences, runtimeReferences);
var context = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}");
testData = new CompilationTestData();
var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData);
Assert.Null(error);
var methodData = testData.GetMethodData("<>x.<>m0");
methodData.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
// Check return type is from runtime assembly.
var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference();
var compilation = CSharpCompilation.Create(
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference)));
var assembly = ImmutableArray.CreateRange(result.Assembly);
using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly)))
{
var reader = metadata.MetadataReader;
var typeDef = reader.GetTypeDef("<>x");
var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0");
var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule;
var metadataDecoder = new MetadataDecoder(module);
SignatureHeader signatureHeader;
BadImageFormatException metadataException;
var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException);
Assert.Equal(parameters.Length, 5);
var actualReturnType = parameters[0].Type;
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error
var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder");
Assert.Equal(expectedReturnType, actualReturnType);
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name);
}
}
/// <summary>
/// Assembly-qualified name containing "ContentType=WindowsRuntime",
/// and referencing runtime assembly.
/// </summary>
[WorkItem(1116143)]
[ConditionalFact(typeof(OSVersionWin8))]
public void AssemblyQualifiedName()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")));
var context = CreateMethodContext(
runtime,
"C.M");
var aliases = ImmutableArray.Create(
VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"));
string error;
var testData = new CompilationTestData();
context.CompileExpression(
"(object)s.Attributes ?? d.UniversalTime",
DkmEvaluationFlags.TreatAsExpression,
aliases,
out error,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime""
IL_0031: box ""long""
IL_0036: ret
}");
}
[WorkItem(1117084)]
[Fact]
public void OtherFrameworkAssembly()
{
var source =
@"class C
{
static void M(Windows.UI.Xaml.FrameworkElement f)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")));
var context = CreateMethodContext(runtime, "C.M");
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
var result = context.CompileExpression(
"f.RenderSize",
DkmEvaluationFlags.TreatAsExpression,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity();
Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single());
}
[WorkItem(1154988)]
[ConditionalFact(typeof(OSVersionWin8))]
public void WinMdAssemblyReferenceRequiresRedirect()
{
var source =
@"class C : Windows.UI.Xaml.Controls.UserControl
{
static void M(C c)
{
}
}";
var runtime = CreateRuntime(source,
ImmutableArray.Create(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml")));
string errorMessage;
var testData = new CompilationTestData();
ExpressionCompilerTestHelpers.CompileExpressionWithRetry(
runtime.Modules.SelectAsArray(m => m.MetadataBlock),
"c.Dispatcher",
ImmutableArray<Alias>.Empty,
(metadataBlocks, _) =>
{
return CreateMethodContext(runtime, "C.M");
},
(AssemblyIdentity assembly, out uint size) =>
{
// Compilation should succeed without retry if we redirect assembly refs correctly.
// Throwing so that we don't loop forever (as we did before fix)...
throw ExceptionUtilities.Unreachable;
},
out errorMessage,
out testData);
Assert.Null(errorMessage);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get""
IL_0006: ret
}");
}
private RuntimeInstance CreateRuntime(
string source,
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences)
{
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: compileReferences);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
return CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
runtimeReferences.AddIntrinsicAssembly(),
exeBytes,
SymReaderFactory.CreateReader(pdbBytes));
}
private static byte[] ToVersion1_3(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_3(bytes);
}
private static byte[] ToVersion1_4(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_4(bytes);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class MembershipChangeEventDecoder
{
public const ushort BLOCK_LENGTH = 40;
public const ushort TEMPLATE_ID = 25;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private MembershipChangeEventDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public MembershipChangeEventDecoder()
{
_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 MembershipChangeEventDecoder 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 LeadershipTermIdId()
{
return 1;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(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 LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int LogPositionId()
{
return 2;
}
public static int LogPositionSinceVersion()
{
return 0;
}
public static int LogPositionEncodingOffset()
{
return 8;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static string LogPositionMetaAttribute(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 LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public long LogPosition()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int TimestampId()
{
return 3;
}
public static int TimestampSinceVersion()
{
return 0;
}
public static int TimestampEncodingOffset()
{
return 16;
}
public static int TimestampEncodingLength()
{
return 8;
}
public static string TimestampMetaAttribute(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 TimestampNullValue()
{
return -9223372036854775808L;
}
public static long TimestampMinValue()
{
return -9223372036854775807L;
}
public static long TimestampMaxValue()
{
return 9223372036854775807L;
}
public long Timestamp()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public static int LeaderMemberIdId()
{
return 4;
}
public static int LeaderMemberIdSinceVersion()
{
return 0;
}
public static int LeaderMemberIdEncodingOffset()
{
return 24;
}
public static int LeaderMemberIdEncodingLength()
{
return 4;
}
public static string LeaderMemberIdMetaAttribute(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 LeaderMemberIdNullValue()
{
return -2147483648;
}
public static int LeaderMemberIdMinValue()
{
return -2147483647;
}
public static int LeaderMemberIdMaxValue()
{
return 2147483647;
}
public int LeaderMemberId()
{
return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian);
}
public static int ClusterSizeId()
{
return 5;
}
public static int ClusterSizeSinceVersion()
{
return 0;
}
public static int ClusterSizeEncodingOffset()
{
return 28;
}
public static int ClusterSizeEncodingLength()
{
return 4;
}
public static string ClusterSizeMetaAttribute(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 ClusterSizeNullValue()
{
return -2147483648;
}
public static int ClusterSizeMinValue()
{
return -2147483647;
}
public static int ClusterSizeMaxValue()
{
return 2147483647;
}
public int ClusterSize()
{
return _buffer.GetInt(_offset + 28, ByteOrder.LittleEndian);
}
public static int ChangeTypeId()
{
return 6;
}
public static int ChangeTypeSinceVersion()
{
return 0;
}
public static int ChangeTypeEncodingOffset()
{
return 32;
}
public static int ChangeTypeEncodingLength()
{
return 4;
}
public static string ChangeTypeMetaAttribute(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 ChangeType ChangeType()
{
return (ChangeType)_buffer.GetInt(_offset + 32, ByteOrder.LittleEndian);
}
public static int MemberIdId()
{
return 7;
}
public static int MemberIdSinceVersion()
{
return 0;
}
public static int MemberIdEncodingOffset()
{
return 36;
}
public static int MemberIdEncodingLength()
{
return 4;
}
public static string MemberIdMetaAttribute(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 MemberIdNullValue()
{
return -2147483648;
}
public static int MemberIdMinValue()
{
return -2147483647;
}
public static int MemberIdMaxValue()
{
return 2147483647;
}
public int MemberId()
{
return _buffer.GetInt(_offset + 36, ByteOrder.LittleEndian);
}
public static int ClusterMembersId()
{
return 8;
}
public static int ClusterMembersSinceVersion()
{
return 0;
}
public static string ClusterMembersCharacterEncoding()
{
return "US-ASCII";
}
public static string ClusterMembersMetaAttribute(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 ClusterMembersHeaderLength()
{
return 4;
}
public int ClusterMembersLength()
{
int limit = _parentMessage.Limit();
return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian));
}
public int GetClusterMembers(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 GetClusterMembers(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 ClusterMembers()
{
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("[MembershipChangeEvent](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='leadershipTermId', 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("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='logPosition', 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("LogPosition=");
builder.Append(LogPosition());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timestamp', 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='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, 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("Timestamp=");
builder.Append(Timestamp());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='leaderMemberId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, 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=24, 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("LeaderMemberId=");
builder.Append(LeaderMemberId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='clusterSize', referencedName='null', description='null', id=5, version=0, deprecated=0, encodedLength=0, offset=28, 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=28, 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("ClusterSize=");
builder.Append(ClusterSize());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='changeType', referencedName='null', description='null', id=6, version=0, deprecated=0, encodedLength=0, offset=32, 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'}}
//Token{signal=BEGIN_ENUM, name='ChangeType', referencedName='null', description='Type of Cluster Change Event.', id=-1, version=0, deprecated=0, encodedLength=4, offset=32, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("ChangeType=");
builder.Append(ChangeType());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='memberId', referencedName='null', description='null', id=7, version=0, deprecated=0, encodedLength=0, offset=36, 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=36, 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("MemberId=");
builder.Append(MemberId());
builder.Append('|');
//Token{signal=BEGIN_VAR_DATA, name='clusterMembers', referencedName='null', description='null', id=8, version=0, deprecated=0, encodedLength=0, offset=40, 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("ClusterMembers=");
builder.Append(ClusterMembers());
Limit(originalLimit);
return builder;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.CoreModules.World.Wind;
namespace OpenSim.Region.CoreModules.World.Wind.Plugins
{
[Extension(Path = "/OpenSim/WindModule", NodeName = "WindModel", Id = "ConfigurableWind")]
class ConfigurableWind : Mono.Addins.TypeExtensionNode, IWindModelPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Vector2[] m_windSpeeds = new Vector2[16 * 16];
//private Random m_rndnums = new Random(Environment.TickCount);
private float m_avgStrength = 5.0f; // Average magnitude of the wind vector
private float m_avgDirection = 0.0f; // Average direction of the wind in degrees
private float m_varStrength = 5.0f; // Max Strength Variance
private float m_varDirection = 30.0f;// Max Direction Variance
private float m_rateChange = 1.0f; //
private Vector2 m_curPredominateWind = new Vector2();
#region IPlugin Members
public string Version
{
get { return "1.0.0.0"; }
}
public string Name
{
get { return "ConfigurableWind"; }
}
public void Initialise()
{
}
#endregion
#region IDisposable Members
public void Dispose()
{
m_windSpeeds = null;
}
#endregion
#region IWindModelPlugin Members
public void WindConfig(OpenSim.Region.Framework.Scenes.Scene scene, Nini.Config.IConfig windConfig)
{
if (windConfig != null)
{
// Uses strength value if avg_strength not specified
m_avgStrength = windConfig.GetFloat("strength", 5.0F);
m_avgStrength = windConfig.GetFloat("avg_strength", 5.0F);
m_avgDirection = windConfig.GetFloat("avg_direction", 0.0F);
m_varStrength = windConfig.GetFloat("var_strength", 5.0F);
m_varDirection = windConfig.GetFloat("var_direction", 30.0F);
m_rateChange = windConfig.GetFloat("rate_change", 1.0F);
LogSettings();
}
}
public void WindUpdate(uint frame)
{
double avgAng = m_avgDirection * (Math.PI/180.0f);
double varDir = m_varDirection * (Math.PI/180.0f);
// Prevailing wind algorithm
// Inspired by Kanker Greenacre
// TODO:
// * This should probably be based on in-world time.
// * should probably move all these local variables to class members and constants
double time = DateTime.Now.TimeOfDay.Seconds / 86400.0f;
double theta = time * (2 * Math.PI) * m_rateChange;
double offset = Math.Sin(theta) * Math.Sin(theta*2) * Math.Sin(theta*9) * Math.Cos(theta*4);
double windDir = avgAng + (varDir * offset);
offset = Math.Sin(theta) * Math.Sin(theta*4) + (Math.Sin(theta*13) / 3);
double windSpeed = m_avgStrength + (m_varStrength * offset);
if (windSpeed<0)
windSpeed=0;
m_curPredominateWind.X = (float)Math.Cos(windDir);
m_curPredominateWind.Y = (float)Math.Sin(windDir);
m_curPredominateWind.Normalize();
m_curPredominateWind.X *= (float)windSpeed;
m_curPredominateWind.Y *= (float)windSpeed;
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x++)
{
m_windSpeeds[y * 16 + x] = m_curPredominateWind;
}
}
}
public Vector3 WindSpeed(float fX, float fY, float fZ)
{
return new Vector3(m_curPredominateWind, 0.0f);
}
public Vector2[] WindLLClientArray()
{
return m_windSpeeds;
}
public string Description
{
get
{
return "Provides a predominate wind direction that can change within configured variances for direction and speed.";
}
}
public System.Collections.Generic.Dictionary<string, string> WindParams()
{
Dictionary<string, string> Params = new Dictionary<string, string>();
Params.Add("avgStrength", "average wind strength");
Params.Add("avgDirection", "average wind direction in degrees");
Params.Add("varStrength", "allowable variance in wind strength");
Params.Add("varDirection", "allowable variance in wind direction in +/- degrees");
Params.Add("rateChange", "rate of change");
return Params;
}
public void WindParamSet(string param, float value)
{
switch (param)
{
case "avgStrength":
m_avgStrength = value;
break;
case "avgDirection":
m_avgDirection = value;
break;
case "varStrength":
m_varStrength = value;
break;
case "varDirection":
m_varDirection = value;
break;
case "rateChange":
m_rateChange = value;
break;
}
}
public float WindParamGet(string param)
{
switch (param)
{
case "avgStrength":
return m_avgStrength;
case "avgDirection":
return m_avgDirection;
case "varStrength":
return m_varStrength;
case "varDirection":
return m_varDirection;
case "rateChange":
return m_rateChange;
default:
throw new Exception(String.Format("Unknown {0} parameter {1}", this.Name, param));
}
}
#endregion
private void LogSettings()
{
m_log.InfoFormat("[ConfigurableWind] Average Strength : {0}", m_avgStrength);
m_log.InfoFormat("[ConfigurableWind] Average Direction : {0}", m_avgDirection);
m_log.InfoFormat("[ConfigurableWind] Varience Strength : {0}", m_varStrength);
m_log.InfoFormat("[ConfigurableWind] Varience Direction : {0}", m_varDirection);
m_log.InfoFormat("[ConfigurableWind] Rate Change : {0}", m_rateChange);
}
#region IWindModelPlugin Members
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Asn1
{
abstract public class Asn1Set
: Asn1Object, IEnumerable
{
private readonly IList _set;
/**
* return an ASN1Set from the given object.
*
* @param obj the object we want converted.
* @exception ArgumentException if the object cannot be converted.
*/
public static Asn1Set GetInstance(
object obj)
{
if (obj == null || obj is Asn1Set)
{
return (Asn1Set)obj;
}
else if (obj is Asn1SetParser)
{
return Asn1Set.GetInstance(((Asn1SetParser)obj).ToAsn1Object());
}
else if (obj is byte[])
{
try
{
return Asn1Set.GetInstance(FromByteArray((byte[])obj));
}
catch (IOException e)
{
throw new ArgumentException("failed to construct set from byte[]: " + e.Message);
}
}
else if (obj is Asn1Encodable)
{
Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object();
if (primitive is Asn1Set)
{
return (Asn1Set)primitive;
}
}
throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
}
/**
* Return an ASN1 set from a tagged object. There is a special
* case here, if an object appears to have been explicitly tagged on
* reading but we were expecting it to be implicitly tagged in the
* normal course of events it indicates that we lost the surrounding
* set - so we need to add it back (this will happen if the tagged
* object is a sequence that contains other sequences). If you are
* dealing with implicitly tagged sets you really <b>should</b>
* be using this method.
*
* @param obj the tagged object.
* @param explicitly true if the object is meant to be explicitly tagged
* false otherwise.
* @exception ArgumentException if the tagged object cannot
* be converted.
*/
public static Asn1Set GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
Asn1Object inner = obj.GetObject();
if (explicitly)
{
if (!obj.IsExplicit())
throw new ArgumentException("object implicit - explicit expected.");
return (Asn1Set) inner;
}
//
// constructed object which appears to be explicitly tagged
// and it's really implicit means we have to add the
// surrounding sequence.
//
if (obj.IsExplicit())
{
return new DerSet(inner);
}
if (inner is Asn1Set)
{
return (Asn1Set) inner;
}
//
// in this case the parser returns a sequence, convert it
// into a set.
//
if (inner is Asn1Sequence)
{
Asn1EncodableVector v = new Asn1EncodableVector();
Asn1Sequence s = (Asn1Sequence) inner;
foreach (Asn1Encodable ae in s)
{
v.Add(ae);
}
// TODO Should be able to construct set directly from sequence?
return new DerSet(v, false);
}
throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj");
}
protected internal Asn1Set(
int capacity)
{
_set = Platform.CreateArrayList(capacity);
}
public virtual IEnumerator GetEnumerator()
{
return _set.GetEnumerator();
}
[Obsolete("Use GetEnumerator() instead")]
public IEnumerator GetObjects()
{
return GetEnumerator();
}
/**
* return the object at the set position indicated by index.
*
* @param index the set number (starting at zero) of the object
* @return the object at the set position indicated by index.
*/
public virtual Asn1Encodable this[int index]
{
get { return (Asn1Encodable) _set[index]; }
}
[Obsolete("Use 'object[index]' syntax instead")]
public Asn1Encodable GetObjectAt(
int index)
{
return this[index];
}
[Obsolete("Use 'Count' property instead")]
public int Size
{
get { return Count; }
}
public virtual int Count
{
get { return _set.Count; }
}
public virtual Asn1Encodable[] ToArray()
{
Asn1Encodable[] values = new Asn1Encodable[this.Count];
for (int i = 0; i < this.Count; ++i)
{
values[i] = this[i];
}
return values;
}
private class Asn1SetParserImpl
: Asn1SetParser
{
private readonly Asn1Set outer;
private readonly int max;
private int index;
public Asn1SetParserImpl(
Asn1Set outer)
{
this.outer = outer;
this.max = outer.Count;
}
public IAsn1Convertible ReadObject()
{
if (index == max)
return null;
Asn1Encodable obj = outer[index++];
if (obj is Asn1Sequence)
return ((Asn1Sequence)obj).Parser;
if (obj is Asn1Set)
return ((Asn1Set)obj).Parser;
// NB: Asn1OctetString implements Asn1OctetStringParser directly
// if (obj is Asn1OctetString)
// return ((Asn1OctetString)obj).Parser;
return obj;
}
public virtual Asn1Object ToAsn1Object()
{
return outer;
}
}
public Asn1SetParser Parser
{
get { return new Asn1SetParserImpl(this); }
}
protected override int Asn1GetHashCode()
{
int hc = Count;
foreach (object o in this)
{
hc *= 17;
if (o == null)
{
hc ^= DerNull.Instance.GetHashCode();
}
else
{
hc ^= o.GetHashCode();
}
}
return hc;
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
Asn1Set other = asn1Object as Asn1Set;
if (other == null)
return false;
if (Count != other.Count)
{
return false;
}
IEnumerator s1 = GetEnumerator();
IEnumerator s2 = other.GetEnumerator();
while (s1.MoveNext() && s2.MoveNext())
{
Asn1Object o1 = GetCurrent(s1).ToAsn1Object();
Asn1Object o2 = GetCurrent(s2).ToAsn1Object();
if (!o1.Equals(o2))
return false;
}
return true;
}
private Asn1Encodable GetCurrent(IEnumerator e)
{
Asn1Encodable encObj = (Asn1Encodable)e.Current;
// unfortunately null was allowed as a substitute for DER null
if (encObj == null)
return DerNull.Instance;
return encObj;
}
/*protected internal void Sort()
{
if (_set.Count < 2)
return;
Asn1Encodable[] items = new Asn1Encodable[_set.Count];
byte[][] keys = new byte[_set.Count][];
for (int i = 0; i < _set.Count; ++i)
{
Asn1Encodable item = (Asn1Encodable)_set[i];
items[i] = item;
keys[i] = item.GetEncoded(Asn1Encodable.Der);
}
Array.Sort(keys, items, new DerComparer());
for (int i = 0; i < _set.Count; ++i)
{
_set[i] = items[i];
}
}*/
/**
* return true if a <= b (arrays are assumed padded with zeros).
*/
private bool LessThanOrEqual(
byte[] a,
byte[] b)
{
int len = System.Math.Min(a.Length, b.Length);
for (int i = 0; i != len; ++i)
{
if (a[i] != b[i])
{
return a[i] < b[i];
}
}
return len == a.Length;
}
protected internal void Sort()
{
if (_set.Count > 1)
{
bool swapped = true;
int lastSwap = _set.Count - 1;
while (swapped)
{
int index = 0;
int swapIndex = 0;
byte[] a = ((Asn1Encodable)_set[0]).GetEncoded();
swapped = false;
while (index != lastSwap)
{
byte[] b = ((Asn1Encodable)_set[index + 1]).GetEncoded();
if (LessThanOrEqual(a, b))
{
a = b;
}
else
{
object o = _set[index];
_set[index] = _set[index + 1];
_set[index + 1] = o;
swapped = true;
swapIndex = index;
}
index++;
}
lastSwap = swapIndex;
}
}
}
protected internal void AddObject(Asn1Encodable obj)
{
_set.Add(obj);
}
public override string ToString()
{
return CollectionUtilities.ToString(_set);
}
}
}
#endif
| |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using WPFDemo.Presentation.Controls.Adorner;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Input;
using WPFDemo.Presentation.EventManagers;
namespace WPFDemo.Presentation.Behaviors
{
public static class AdornerExtensions
{
#region Static Properties
private static readonly DependencyProperty AdornerLayerCacheProperty = DependencyProperty.RegisterAttached(
"AdornerLayerCache", typeof(AdornerLayer), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None)
);
private static readonly object AdornerLayerCacheLock = new object();
public static readonly DependencyProperty ShowMouseOverAdornerProperty = DependencyProperty.RegisterAttached(
"ShowMouseOverAdorner", typeof(bool), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender, ShowMouseOverAdorner_PropertyChanged)
);
public static readonly DependencyProperty MouseOverAdornerBrushProperty = DependencyProperty.RegisterAttached(
"MouseOverAdornerBrush", typeof(Brush), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, MouseOverAdornerBrush_PropertyChanged)
);
public static readonly DependencyProperty MouseOverAdornerPenProperty = DependencyProperty.RegisterAttached(
"MouseOverAdornerPen", typeof(Pen), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, MouseOverAdornerPen_PropertyChanged)
);
private static readonly DependencyProperty MouseOverAdornerProperty = DependencyProperty.RegisterAttached(
"MouseOverAdorner", typeof(RectangleAdorner), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)
);
public static readonly DependencyProperty ShowContentAdornerProperty = DependencyProperty.RegisterAttached(
"ShowContentAdorner", typeof(bool), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender, ShowContentAdorner_PropertyChanged)
);
public static readonly DependencyProperty ContentAdornerStyleProperty = DependencyProperty.RegisterAttached(
"ContentAdornerStyle", typeof(Style), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, ContentAdornerStyle_PropertyChanged)
);
private static readonly DependencyProperty ContentAdornerProperty = DependencyProperty.RegisterAttached(
"ContentAdorner", typeof(ContentAdorner), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)
);
private static readonly DependencyProperty ContentAdornerDataContextWeakEventListenerProperty = DependencyProperty.RegisterAttached(
"ContentAdornerDataContextWeakEventListener", typeof(IWeakEventListener), typeof(AdornerExtensions),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)
);
#endregion
#region Static Methods
private static AdornerLayer GetAdornerLayerCache(Visual visual)
{
return (AdornerLayer)visual.GetValue(AdornerLayerCacheProperty);
//return AdornerLayer.GetAdornerLayer(visual);
}
private static void SetAdornerLayerCache(Visual visual, AdornerLayer value)
{
visual.SetValue(AdornerLayerCacheProperty, value);
}
private static AdornerLayer InitializeAdornerLayerCache(Visual visual)
{
var Layer = GetAdornerLayerCache(visual);
if (Layer == null)
{
lock (AdornerLayerCacheLock)
{
Layer = GetAdornerLayerCache(visual);
if (Layer == null)
{
Layer = AdornerLayer.GetAdornerLayer(visual);
if (Layer == null)
throw new ArgumentException("No adorner layer.", "layer");
SetAdornerLayerCache(visual, Layer);
}
}
}
return Layer;
}
public static bool GetShowMouseOverAdorner(FrameworkElement element)
{
return (bool)element.GetValue(ShowMouseOverAdornerProperty);
}
public static void SetShowMouseOverAdorner(FrameworkElement element, bool value)
{
element.SetValue(ShowMouseOverAdornerProperty, value);
}
public static Brush GetMouseOverAdornerBrush(FrameworkElement element)
{
return (Brush)element.GetValue(MouseOverAdornerBrushProperty);
}
public static void SetMouseOverAdornerBrush(FrameworkElement element, Brush value)
{
element.SetValue(MouseOverAdornerBrushProperty, value);
}
public static Pen GetMouseOverAdornerPen(FrameworkElement element)
{
return (Pen)element.GetValue(MouseOverAdornerPenProperty);
}
public static void SetMouseOverAdornerPen(FrameworkElement element, Pen value)
{
element.SetValue(MouseOverAdornerPenProperty, value);
}
private static RectangleAdorner GetMouseOverAdorner(FrameworkElement element)
{
return (RectangleAdorner)element.GetValue(MouseOverAdornerProperty);
}
private static void SetMouseOverAdorner(FrameworkElement element, RectangleAdorner value)
{
element.SetValue(MouseOverAdornerProperty, value);
}
private static void ShowMouseOverAdorner_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var Element = o as FrameworkElement;
if (Element == null)
return;
Element.PreviewMouseMove -= ShowMouseOverAdorner_Element_PreviewMouseMove;
Element.MouseLeave -= ShowMouseOverAdorner_Element_MouseLeave;
if ((bool)e.NewValue)
{
Element.MouseEnter += ShowMouseOverAdorner_Element_PreviewMouseMove;
Element.MouseLeave += ShowMouseOverAdorner_Element_MouseLeave;
}
else
{
RemoveMouseOverAdorner(Element);
}
}
private static void MouseOverAdornerBrush_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var Element = o as FrameworkElement;
if (Element == null)
return;
var Adorner = GetMouseOverAdorner(Element) as RectangleAdorner;
if (Adorner == null)
return;
Adorner.Brush = e.NewValue as Brush;
}
private static void MouseOverAdornerPen_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var Element = o as FrameworkElement;
if (Element == null)
return;
var Adorner = GetMouseOverAdorner(Element) as RectangleAdorner;
if (Adorner == null)
return;
Adorner.Pen = e.NewValue as Pen;
}
private static void ShowMouseOverAdorner_Element_PreviewMouseMove(object sender, MouseEventArgs e)
{
var Element = sender as FrameworkElement;
if (Element == null)
return;
var AdornerLayer = InitializeAdornerLayerCache(Element);
if (AdornerLayer == null)
return;
var Adorner = GetMouseOverAdorner(Element);
if (Adorner == null)
{
Adorner = new RectangleAdorner(Element)
{
IsHitTestVisible = false,
Brush = GetMouseOverAdornerBrush(Element),
Pen = GetMouseOverAdornerPen(Element)
};
SetMouseOverAdorner(Element, Adorner);
}
if (Adorner.Parent != AdornerLayer)
AdornerLayer.Add(Adorner);
}
private static void ShowMouseOverAdorner_Element_MouseLeave(object sender, MouseEventArgs e)
{
var Element = sender as FrameworkElement;
if (Element == null)
return;
RemoveMouseOverAdorner(Element);
}
private static void RemoveMouseOverAdorner(FrameworkElement element)
{
if (element == null)
throw new ArgumentNullException("element");
var AdornerLayer = InitializeAdornerLayerCache(element);
if (AdornerLayer == null)
return;
var Adorner = GetMouseOverAdorner(element);
if (Adorner == null)
return;
AdornerLayer.Remove(Adorner);
SetMouseOverAdorner(element, null);
}
public static bool GetShowContentAdorner(FrameworkElement element)
{
return (bool)element.GetValue(ShowContentAdornerProperty);
}
public static void SetShowContentAdorner(FrameworkElement element, bool value)
{
element.SetValue(ShowContentAdornerProperty, value);
}
public static Style GetContentAdornerStyle(FrameworkElement element)
{
return (Style)element.GetValue(ContentAdornerStyleProperty);
}
public static void SetContentAdornerStyle(FrameworkElement element, Style value)
{
element.SetValue(ContentAdornerStyleProperty, value);
}
internal static ContentAdorner GetContentAdorner(FrameworkElement element)
{
return (ContentAdorner)element.GetValue(ContentAdornerProperty);
}
internal static void SetContentAdorner(FrameworkElement element, ContentAdorner value)
{
element.SetValue(ContentAdornerProperty, value);
}
private static IWeakEventListener GetContentAdornerDataContextWeakEventListener(FrameworkElement element)
{
return (IWeakEventListener)element.GetValue(ContentAdornerDataContextWeakEventListenerProperty);
}
private static void SetContentAdornerDataContextWeakEventListener(FrameworkElement element, IWeakEventListener value)
{
element.SetValue(ContentAdornerDataContextWeakEventListenerProperty, value);
}
private static void ShowContentAdorner_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var Element = o as FrameworkElement;
if (Element == null)
return;
var Listener = GetContentAdornerDataContextWeakEventListener(Element);
if ((bool)e.NewValue)
{
var AdornerLayer = InitializeAdornerLayerCache(Element);
if (AdornerLayer == null)
return;
var ContentAdorner = GetContentAdorner(Element);
if (ContentAdorner == null)
{
ContentAdorner = new ContentAdorner(Element);
ContentAdorner.Style = GetContentAdornerStyle(Element);
SetContentAdorner(Element, ContentAdorner);
}
if (ContentAdorner.Parent != AdornerLayer)
AdornerLayer.Add(ContentAdorner);
ContentAdorner.DataContext = Element.DataContext;
if (Listener == null)
Listener = new ContentAdornerDataContextWeakEventListener();
SetContentAdornerDataContextWeakEventListener(Element, Listener);
DataContextChangedEventManager.AddListener(Element, Listener);
}
else
{
if (Listener != null)
{
DataContextChangedEventManager.RemoveListener(Element, Listener);
SetContentAdornerDataContextWeakEventListener(Element, null);
}
RemoveContentAdorner(Element);
}
}
private static void ContentAdornerStyle_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var Element = o as FrameworkElement;
if (Element == null)
return;
var Adorner = GetContentAdorner(Element);
if (Adorner == null)
return;
Adorner.ContentControl.Style = (Style)e.NewValue;
}
private static void RemoveContentAdorner(FrameworkElement element)
{
if (element == null)
throw new ArgumentNullException("element");
var AdornerLayer = InitializeAdornerLayerCache(element);
if (AdornerLayer == null)
return;
var Adorner = GetContentAdorner(element);
if (Adorner == null)
return;
AdornerLayer.Remove(Adorner);
SetContentAdorner(element, null);
}
#endregion
}
internal class ContentAdornerDataContextWeakEventListener : IWeakEventListener
{
#region IWeakEventListener Members
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType != typeof(DataContextChangedEventManager))
return false;
var Element = sender as FrameworkElement;
if (Element == null)
return true;
var ContentAdorner = AdornerExtensions.GetContentAdorner(Element);
if (ContentAdorner == null)
return true;
ContentAdorner.DataContext = Element.DataContext;
return true;
}
#endregion
}
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.TestingHost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Streams.Core;
using TestExtensions;
using Xunit;
using UnitTests.GrainInterfaces;
using Orleans.TestingHost.Utils;
using UnitTests.Grains.ProgrammaticSubscribe;
namespace Tester.StreamingTests
{
public abstract class ProgrammaticSubcribeTestsRunner
{
private readonly BaseTestClusterFixture fixture;
public const string StreamProviderName = "StreamProvider1";
public const string StreamProviderName2 = "StreamProvider2";
public ProgrammaticSubcribeTestsRunner(BaseTestClusterFixture fixture)
{
this.fixture = fixture;
}
[SkippableFact]
public async Task Programmatic_Subscribe_Provider_WithExplicitPubsub_TryGetStreamSubscrptionManager()
{
var subGrain = this.fixture.HostedCluster.GrainFactory.GetGrain<ISubscribeGrain>(Guid.NewGuid());
Assert.True(await subGrain.CanGetSubscriptionManager(StreamProviderName));
}
[SkippableFact]
public async Task Programmatic_Subscribe_CanUseNullNamespace()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), null, StreamProviderName);
await subscriptionManager.AddSubscription<IPassive_ConsumerGrain>(streamId,
Guid.NewGuid());
var subscriptions = await subscriptionManager.GetSubscriptions(streamId);
await subscriptionManager.RemoveSubscription(streamId, subscriptions.First().SubscriptionId);
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_Subscribe()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for 10 consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 10);
var consumers = subscriptions.Select(sub => this.fixture.HostedCluster.GrainFactory.GetGrain<IPassive_ConsumerGrain>(sub.GrainId.PrimaryKey)).ToList();
var producer = this.fixture.HostedCluster.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
await producer.StopPeriodicProducing();
var tasks = new List<Task>();
foreach (var consumer in consumers)
{
tasks.Add(TestingUtils.WaitUntilAsync(lastTry => CheckCounters(new List<ITypedProducerGrain> { producer },
consumer, lastTry, this.fixture.Logger), _timeout));
}
await Task.WhenAll(tasks);
//clean up test
tasks.Clear();
tasks = consumers.Select(consumer => consumer.StopConsuming()).ToList();
await Task.WhenAll(tasks);
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_UnSubscribe()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 2);
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
//the subscription to remove
var subscription = subscriptions[0];
// remove subscription
await subscriptionManager.RemoveSubscription(streamId, subscription.SubscriptionId);
var numProducedWhenUnSub = await producer.GetNumberProduced();
var consumerUnSub = this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(subscription.GrainId.PrimaryKey);
var consumerNormal = this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(subscriptions[1].GrainId.PrimaryKey);
//assert consumer grain's onAdd func got called.
Assert.True((await consumerUnSub.GetCountOfOnAddFuncCalled()) > 0);
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProducedWhenUnSub, producer, lastTry), _timeout);
await producer.StopPeriodicProducing();
//wait for consumers to finish consuming
await Task.Delay(TimeSpan.FromMilliseconds(2000));
//assert normal consumer consumed equal to produced
await TestingUtils.WaitUntilAsync(
lastTry =>CheckCounters(new List<ITypedProducerGrain> { producer }, consumerNormal, lastTry, this.fixture.Logger), _timeout);
//asert unsubscribed consumer consumed less than produced
numProduced = await producer.GetNumberProduced();
var numConsumed = await consumerUnSub.GetNumberConsumed();
Assert.True(numConsumed <= numProducedWhenUnSub);
Assert.True(numConsumed < numProduced);
// clean up test
await consumerNormal.StopConsuming();
await consumerUnSub.StopConsuming();
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_GetSubscriptions()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscriptions
var expectedSubscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 2);
var expectedSubscriptionIds = expectedSubscriptions.Select(sub => sub.SubscriptionId).ToSet();
var subscriptions = await subscriptionManager.GetSubscriptions(streamId);
var subscriptionIds = subscriptions.Select(sub => sub.SubscriptionId).ToSet();
Assert.True(expectedSubscriptionIds.SetEquals(subscriptionIds));
//remove one subscription
await subscriptionManager.RemoveSubscription(streamId, expectedSubscriptions[0].SubscriptionId);
expectedSubscriptions = expectedSubscriptions.GetRange(1, 1);
subscriptions = await subscriptionManager.GetSubscriptions(streamId);
expectedSubscriptionIds = expectedSubscriptions.Select(sub => sub.SubscriptionId).ToSet();
subscriptionIds = subscriptions.Select(sub => sub.SubscriptionId).ToSet();
Assert.True(expectedSubscriptionIds.SetEquals(subscriptionIds));
// clean up tests
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_ConsumerUnsubscribeOnAdd()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscriptions
await subscriptionManager.SetupStreamingSubscriptionForStream<IJerk_ConsumerGrain>(streamId, 10);
//producer start producing
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingInt>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
await producer.StopPeriodicProducing();
//wait for consumers to react
await Task.Delay(TimeSpan.FromMilliseconds(1000));
//get subscription count now, should be all removed/unsubscribed
var subscriptions = await subscriptionManager.GetSubscriptions(streamId);
Assert.True( subscriptions.Count<Orleans.Streams.Core.StreamSubscription>()== 0);
// clean up tests
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_SubscribeToTwoStream_MessageWithPolymorphism()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for 10 consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 10);
var consumers = subscriptions.Select(sub => this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(sub.GrainId.PrimaryKey)).ToList();
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
// set up the new stream to subscribe, which produce strings
var streamId2 = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace2", StreamProviderName);
var producer2 = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer2.BecomeProducer(streamId2.Guid, streamId2.Namespace, streamId2.ProviderName);
//register the consumer grain to second stream
var tasks = consumers.Select(consumer => subscriptionManager.AddSubscription<IPassive_ConsumerGrain>(streamId2, consumer.GetPrimaryKey())).ToList();
await Task.WhenAll(tasks);
await producer2.StartPeriodicProducing();
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer2, lastTry), _timeout);
await producer.StopPeriodicProducing();
await producer2.StopPeriodicProducing();
var tasks2 = new List<Task>();
foreach (var consumer in consumers)
{
tasks2.Add(TestingUtils.WaitUntilAsync(lastTry => CheckCounters(new List<ITypedProducerGrain> { producer, producer2 },
consumer, lastTry, this.fixture.Logger), _timeout));
}
await Task.WhenAll(tasks);
//clean up test
tasks2.Clear();
tasks2 = consumers.Select(consumer => consumer.StopConsuming()).ToList();
await Task.WhenAll(tasks2);
}
[SkippableFact]
public async Task StreamingTests_Consumer_Producer_SubscribeToStreamsHandledByDifferentStreamProvider()
{
var subscriptionManager = new SubscriptionManager(this.fixture.HostedCluster);
var streamId = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace", StreamProviderName);
//set up subscription for 10 consumer grains
var subscriptions = await subscriptionManager.SetupStreamingSubscriptionForStream<IPassive_ConsumerGrain>(streamId, 10);
var consumers = subscriptions.Select(sub => this.fixture.GrainFactory.GetGrain<IPassive_ConsumerGrain>(sub.GrainId.PrimaryKey)).ToList();
var producer = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer.BecomeProducer(streamId.Guid, streamId.Namespace, streamId.ProviderName);
await producer.StartPeriodicProducing();
int numProduced = 0;
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer, lastTry), _timeout);
// set up the new stream to subscribe, which produce strings
var streamId2 = new FullStreamIdentity(Guid.NewGuid(), "EmptySpace2", StreamProviderName2);
var producer2 = this.fixture.GrainFactory.GetGrain<ITypedProducerGrainProducingApple>(Guid.NewGuid());
await producer2.BecomeProducer(streamId2.Guid, streamId2.Namespace, streamId2.ProviderName);
//register the consumer grain to second stream
var tasks = consumers.Select(consumer => subscriptionManager.AddSubscription<IPassive_ConsumerGrain>(streamId2, consumer.GetPrimaryKey())).ToList();
await Task.WhenAll(tasks);
await producer2.StartPeriodicProducing();
await TestingUtils.WaitUntilAsync(lastTry => ProducerHasProducedSinceLastCheck(numProduced, producer2, lastTry), _timeout);
await producer.StopPeriodicProducing();
await producer2.StopPeriodicProducing();
var tasks2 = new List<Task>();
foreach (var consumer in consumers)
{
tasks2.Add(TestingUtils.WaitUntilAsync(lastTry => CheckCounters(new List<ITypedProducerGrain> { producer, producer2 },
consumer, lastTry, this.fixture.Logger), _timeout));
}
await Task.WhenAll(tasks);
//clean up test
tasks2.Clear();
tasks2 = consumers.Select(consumer => consumer.StopConsuming()).ToList();
await Task.WhenAll(tasks2);
}
//test utilities and statics
private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(30);
public static async Task<bool> ProducerHasProducedSinceLastCheck(int numProducedLastTime, ITypedProducerGrain producer, bool assertIsTrue)
{
var numProduced = await producer.GetNumberProduced();
if (assertIsTrue)
{
throw new OrleansException($"Producer has not produced since last check");
}
else
{
return numProduced > numProducedLastTime;
}
}
public static async Task<bool> CheckCounters(List<ITypedProducerGrain> producers, IPassive_ConsumerGrain consumer, bool assertIsTrue, ILogger logger)
{
int numProduced = 0;
foreach (var p in producers)
{
numProduced += await p.GetNumberProduced();
}
var numConsumed = await consumer.GetNumberConsumed();
logger.Info("CheckCounters: numProduced = {0}, numConsumed = {1}", numProduced, numConsumed);
if (assertIsTrue)
{
Assert.Equal(numProduced, numConsumed);
return true;
}
else
{
return numProduced == numConsumed;
}
}
}
public class SubscriptionManager
{
private IGrainFactory grainFactory;
private IServiceProvider serviceProvider;
private IStreamSubscriptionManager subManager;
public SubscriptionManager(TestCluster cluster)
{
this.grainFactory = cluster.GrainFactory;
this.serviceProvider = cluster.ServiceProvider;
this.subManager = serviceProvider.GetService<IStreamSubscriptionManagerAdmin>().GetStreamSubscriptionManager(StreamSubscriptionManagerType.ExplicitSubscribeOnly);
}
public async Task<List<StreamSubscription>> SetupStreamingSubscriptionForStream<TGrainInterface>(FullStreamIdentity streamIdentity, int grainCount)
where TGrainInterface : IGrainWithGuidKey
{
var subscriptions = new List<StreamSubscription>();
while (grainCount > 0)
{
var grainId = Guid.NewGuid();
var grainRef = this.grainFactory.GetGrain<TGrainInterface>(grainId) as GrainReference;
subscriptions.Add(await subManager.AddSubscription(streamIdentity.ProviderName, streamIdentity, grainRef));
grainCount--;
}
return subscriptions;
}
public async Task<StreamSubscription> AddSubscription<TGrainInterface>(FullStreamIdentity streamId, Guid grainId)
where TGrainInterface : IGrainWithGuidKey
{
var grainRef = this.grainFactory.GetGrain<TGrainInterface>(grainId) as GrainReference;
var sub = await this.subManager
.AddSubscription(streamId.ProviderName, streamId, grainRef);
return sub;
}
public Task<IEnumerable<StreamSubscription>> GetSubscriptions(FullStreamIdentity streamIdentity)
{
return subManager.GetSubscriptions(streamIdentity.ProviderName, streamIdentity);
}
public async Task RemoveSubscription(FullStreamIdentity streamId, Guid subscriptionId)
{
await subManager.RemoveSubscription(streamId.ProviderName, streamId, subscriptionId);
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.DeviceDriver.ISA;
using Mosa.DeviceSystem;
using Mosa.DeviceSystem.PCI;
using System.Collections.Generic;
namespace Mosa.CoolWorld.x86
{
/// <summary>
/// Setup for the Device Driver System.
/// </summary>
public static class Setup
{
static private DeviceDriverRegistry deviceDriverRegistry;
static private IDeviceManager deviceManager;
static private IResourceManager resourceManager;
static private PCIControllerManager pciControllerManager;
/// <summary>
/// Gets the device driver library
/// </summary>
/// <value>The device driver library.</value>
static public DeviceDriverRegistry DeviceDriverRegistry { get { return deviceDriverRegistry; } }
/// <summary>
/// Gets the device manager.
/// </summary>
/// <value>The device manager.</value>
static public IDeviceManager DeviceManager { get { return deviceManager; } }
/// <summary>
/// Gets the resource manager.
/// </summary>
/// <value>The resource manager.</value>
static public IResourceManager ResourceManager { get { return resourceManager; } }
/// <summary>
/// Gets the PCI Controller Manager
/// </summary>
static public PCIControllerManager PCIControllerManager { get { return pciControllerManager; } }
static public StandardKeyboard Keyboard = null;
static public CMOS CMOS = null;
/// <summary>
/// Initializes the Device Driver System.
/// </summary>
static public void Initialize()
{
// Create Resource Manager
resourceManager = new ResourceManager();
// Create Device Manager
deviceManager = new DeviceManager();
// Create the Device Driver Manager
deviceDriverRegistry = new DeviceDriverRegistry(PlatformArchitecture.X86);
// Create the PCI Controller Manager
pciControllerManager = new PCIControllerManager(deviceManager);
// Setup hardware abstraction interface
IHardwareAbstraction hardwareAbstraction = new Mosa.CoolWorld.x86.HAL.HardwareAbstraction();
// Set device driver system to the hardware HAL
Mosa.DeviceSystem.HAL.SetHardwareAbstraction(hardwareAbstraction);
// Set the interrupt handler
Mosa.DeviceSystem.HAL.SetInterruptHandler(ResourceManager.InterruptManager.ProcessInterrupt);
}
/// <summary>
/// Start the Device Driver System.
/// </summary>
static public void Start()
{
// Find all drivers
Boot.Console.Write("Finding Drivers...");
deviceDriverRegistry.RegisterBuiltInDeviceDrivers();
var count = deviceDriverRegistry.GetPCIDeviceDrivers().Count + deviceDriverRegistry.GetISADeviceDrivers().Count;
Boot.Console.WriteLine("[Completed: " + count.ToString() + " found]");
// Start drivers for ISA devices
StartISADevices();
// Start drivers for PCI devices
StartPCIDevices();
// Get CMOS, StandardKeyboard, and PIC driver instances
CMOS = (CMOS)deviceManager.GetDevices(new FindDevice.WithName("CMOS")).First.Value;
Keyboard = (StandardKeyboard)deviceManager.GetDevices(new FindDevice.WithName("StandardKeyboard")).First.Value;
}
/// <summary>
/// Starts the PCI devices.
/// </summary>
static public void StartPCIDevices()
{
Boot.Console.Write("Probing PCI devices...");
PCIControllerManager.CreatePCIDevices();
Boot.Console.WriteLine("[Completed]");
Boot.Console.Write("Starting PCI devices... ");
var devices = deviceManager.GetDevices(new FindDevice.IsPCIDevice(), new FindDevice.IsAvailable());
Boot.Console.Write(devices.Count.ToString());
Boot.Console.WriteLine(" Devices");
foreach (IDevice device in devices)
{
var pciDevice = device as IPCIDevice;
Mosa.CoolWorld.x86.Boot.BulletPoint();
Boot.Console.WriteLine(device.Name + ": " + pciDevice.VendorID.ToString("x") + "." + pciDevice.DeviceID.ToString("x") + "." + pciDevice.Function.ToString("x") + "." + pciDevice.ClassCode.ToString("x"));
StartDevice(pciDevice);
}
}
/// <summary>
/// Starts the device.
/// </summary>
/// <param name="pciDevice">The pci device.</param>
static public void StartDevice(IPCIDevice pciDevice)
{
var deviceDriver = deviceDriverRegistry.FindDriver(pciDevice);
if (deviceDriver == null)
{
pciDevice.SetNoDriverFound();
return;
}
var hardwareDevice = System.Activator.CreateInstance(deviceDriver.DriverType);
StartDevice(pciDevice, deviceDriver, hardwareDevice as IHardwareDevice);
if (pciDevice.VendorID == 0x15AD && pciDevice.DeviceID == 0x0405)
{
var display = hardwareDevice as IPixelGraphicsDevice;
var color = new Color(255, 0, 0);
display.WritePixel(color, 100, 100);
}
}
private static void StartDevice(IPCIDevice pciDevice, Mosa.DeviceSystem.DeviceDriver deviceDriver, IHardwareDevice hardwareDevice)
{
var ioPortRegions = new LinkedList<IIOPortRegion>();
var memoryRegions = new LinkedList<IMemoryRegion>();
foreach (var pciBaseAddress in pciDevice.BaseAddresses)
{
switch (pciBaseAddress.Region)
{
case AddressType.IO: ioPortRegions.AddLast(new IOPortRegion((ushort)pciBaseAddress.Address, (ushort)pciBaseAddress.Size)); break;
case AddressType.Memory: memoryRegions.AddLast(new MemoryRegion(pciBaseAddress.Address, pciBaseAddress.Size)); break;
default: break;
}
}
foreach (var memoryAttribute in deviceDriver.MemoryAttributes)
{
if (memoryAttribute.MemorySize > 0)
{
var memory = Mosa.DeviceSystem.HAL.AllocateMemory(memoryAttribute.MemorySize, memoryAttribute.MemoryAlignment);
memoryRegions.AddLast(new MemoryRegion(memory.Address, memory.Size));
}
}
var hardwareResources = new HardwareResources(resourceManager, ioPortRegions.ToArray(), memoryRegions.ToArray(), new InterruptHandler(resourceManager.InterruptManager, pciDevice.IRQ, hardwareDevice), pciDevice as IDeviceResource);
if (resourceManager.ClaimResources(hardwareResources))
{
hardwareResources.EnableIRQ();
hardwareDevice.Setup(hardwareResources);
if (hardwareDevice.Start() == DeviceDriverStartStatus.Started)
{
pciDevice.SetDeviceOnline();
}
else
{
hardwareResources.DisableIRQ();
resourceManager.ReleaseResources(hardwareResources);
}
}
}
/// <summary>
/// Starts the ISA devices.
/// </summary>
static public void StartISADevices()
{
var deviceDrivers = deviceDriverRegistry.GetISADeviceDrivers();
foreach (var deviceDriver in deviceDrivers)
StartDevice(deviceDriver);
}
/// <summary>
/// Starts the device.
/// </summary>
/// <param name="deviceDriver">The device driver.</param>
static public void StartDevice(Mosa.DeviceSystem.DeviceDriver deviceDriver)
{
var driverAtttribute = deviceDriver.Attribute as ISADeviceDriverAttribute;
// Don't load the VGAText and PIC drivers
if (driverAtttribute.BasePort == 0x03B0 || driverAtttribute.BasePort == 0x20)
return;
if (driverAtttribute.AutoLoad)
{
var hardwareDevice = System.Activator.CreateInstance(deviceDriver.DriverType) as IHardwareDevice;
var ioPortRegions = new LinkedList<IIOPortRegion>();
var memoryRegions = new LinkedList<IMemoryRegion>();
ioPortRegions.AddLast(new IOPortRegion(driverAtttribute.BasePort, driverAtttribute.PortRange));
if (driverAtttribute.AltBasePort != 0x00)
ioPortRegions.AddLast(new IOPortRegion(driverAtttribute.AltBasePort, driverAtttribute.AltPortRange));
if (driverAtttribute.BaseAddress != 0x00)
memoryRegions.AddLast(new MemoryRegion(driverAtttribute.BaseAddress, driverAtttribute.AddressRange));
foreach (var memoryAttribute in deviceDriver.MemoryAttributes)
if (memoryAttribute.MemorySize > 0)
{
IMemory memory = Mosa.DeviceSystem.HAL.AllocateMemory(memoryAttribute.MemorySize, memoryAttribute.MemoryAlignment);
memoryRegions.AddLast(new MemoryRegion(memory.Address, memory.Size));
}
var hardwareResources = new HardwareResources(resourceManager, ioPortRegions.ToArray(), memoryRegions.ToArray(), new InterruptHandler(resourceManager.InterruptManager, driverAtttribute.IRQ, hardwareDevice));
hardwareDevice.Setup(hardwareResources);
Mosa.CoolWorld.x86.Boot.BulletPoint();
Boot.Console.Write("Adding device ");
Boot.InBrackets(hardwareDevice.Name, Mosa.Kernel.x86.Colors.White, Mosa.Kernel.x86.Colors.LightGreen);
Boot.Console.WriteLine();
if (resourceManager.ClaimResources(hardwareResources))
{
hardwareResources.EnableIRQ();
if (hardwareDevice.Start() == DeviceDriverStartStatus.Started)
{
deviceManager.Add(hardwareDevice);
}
else
{
hardwareResources.DisableIRQ();
resourceManager.ReleaseResources(hardwareResources);
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.