context stringlengths 2.52k 185k | gt stringclasses 1 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 Microsoft.CodeAnalysis.Collections;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class CustomTypeInfo
{
internal static readonly Guid PayloadTypeId = new Guid("108766CE-DF68-46EE-B761-0DCB7AC805F1");
internal static DkmClrCustomTypeInfo Create(
ReadOnlyCollection<byte> dynamicFlags,
ReadOnlyCollection<string> tupleElementNames)
{
var payload = Encode(dynamicFlags, tupleElementNames);
return (payload == null) ? null : DkmClrCustomTypeInfo.Create(PayloadTypeId, payload);
}
/// <summary>
/// Return a copy of the custom type info without tuple element names.
/// </summary>
internal static DkmClrCustomTypeInfo WithNoTupleElementNames(this DkmClrCustomTypeInfo typeInfo)
{
if ((typeInfo == null) || (typeInfo.Payload == null) || typeInfo.PayloadTypeId != PayloadTypeId)
{
return typeInfo;
}
var payload = typeInfo.Payload;
int length = payload[0] + 1;
if (length == payload.Count)
{
return typeInfo;
}
return DkmClrCustomTypeInfo.Create(PayloadTypeId, new ReadOnlyCollection<byte>(CopyBytes(payload, 0, length)));
}
/// <summary>
/// Return a copy of the custom type info with the leading dynamic flag removed.
/// There are no changes to tuple element names since this is used for walking
/// into an array element type only which does not affect tuple element names.
/// </summary>
internal static DkmClrCustomTypeInfo SkipOne(DkmClrCustomTypeInfo customInfo)
{
if (customInfo == null)
{
return customInfo;
}
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(
customInfo.PayloadTypeId,
customInfo.Payload,
out dynamicFlags,
out tupleElementNames);
if (dynamicFlags == null)
{
return customInfo;
}
return Create(DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlags), tupleElementNames);
}
internal static string GetTupleElementNameIfAny(ReadOnlyCollection<string> tupleElementNames, int index)
{
return tupleElementNames != null && index < tupleElementNames.Count ?
tupleElementNames[index] :
null;
}
// Encode in payload as a sequence of bytes {count}{dynamicFlags}{tupleNames}
// where {count} is a byte of the number of bytes in {dynamicFlags} (max: 8*256 bits)
// and {tupleNames} is a UTF8 encoded string of the names each preceded by '|'.
internal static ReadOnlyCollection<byte> Encode(
ReadOnlyCollection<byte> dynamicFlags,
ReadOnlyCollection<string> tupleElementNames)
{
if ((dynamicFlags == null) && (tupleElementNames == null))
{
return null;
}
var builder = ArrayBuilder<byte>.GetInstance();
if (dynamicFlags == null)
{
builder.Add(0);
}
else
{
int length = dynamicFlags.Count;
if (length > byte.MaxValue)
{
// Length exceeds capacity of byte.
builder.Free();
return null;
}
builder.Add((byte)length);
builder.AddRange(dynamicFlags);
}
if (tupleElementNames != null)
{
var bytes = EncodeNames(tupleElementNames);
builder.AddRange(bytes);
}
return new ReadOnlyCollection<byte>(builder.ToArrayAndFree());
}
internal static void Decode(
Guid payloadTypeId,
ReadOnlyCollection<byte> payload,
out ReadOnlyCollection<byte> dynamicFlags,
out ReadOnlyCollection<string> tupleElementNames)
{
dynamicFlags = null;
tupleElementNames = null;
if ((payload == null) || (payloadTypeId != PayloadTypeId))
{
return;
}
int length = payload[0];
if (length > 0)
{
dynamicFlags = new ReadOnlyCollection<byte>(CopyBytes(payload, 1, length));
}
int start = length + 1;
if (start < payload.Count)
{
tupleElementNames = DecodeNames(payload, start);
}
}
private const char NameSeparator = '|';
private static ReadOnlyCollection<byte> EncodeNames(ReadOnlyCollection<string> names)
{
var str = JoinNames(names);
return new ReadOnlyCollection<byte>(Encoding.UTF8.GetBytes(str));
}
private static ReadOnlyCollection<string> DecodeNames(ReadOnlyCollection<byte> bytes, int start)
{
int length = bytes.Count - start;
var array = CopyBytes(bytes, start, length);
var str = Encoding.UTF8.GetString(array, 0, length);
return SplitNames(str);
}
private static string JoinNames(ReadOnlyCollection<string> names)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
foreach (var name in names)
{
builder.Append(NameSeparator);
if (name != null)
{
builder.Append(name);
}
}
return pooledBuilder.ToStringAndFree();
}
private static ReadOnlyCollection<string> SplitNames(string str)
{
Debug.Assert(str != null);
Debug.Assert(str.Length > 0);
Debug.Assert(str[0] == NameSeparator);
var builder = ArrayBuilder<string>.GetInstance();
int offset = 1;
int n = str.Length;
while (true)
{
int next = str.IndexOf(NameSeparator, offset);
var name = (next < 0) ? str.Substring(offset) : str.Substring(offset, next - offset);
builder.Add((name.Length == 0) ? null : name);
if (next < 0)
{
break;
}
offset = next + 1;
}
return new ReadOnlyCollection<string>(builder.ToArrayAndFree());
}
private static byte[] CopyBytes(ReadOnlyCollection<byte> bytes, int start, int length)
{
var array = new byte[length];
for (int i = 0; i < length; i++)
{
array[i] = bytes[start + i];
}
return array;
}
}
}
| |
// 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.Linq;
namespace System.Reflection.Metadata.Tests
{
public class DiffUtil
{
private enum EditKind
{
/// <summary>
/// No change.
/// </summary>
None = 0,
/// <summary>
/// Node value was updated.
/// </summary>
Update = 1,
/// <summary>
/// Node was inserted.
/// </summary>
Insert = 2,
/// <summary>
/// Node was deleted.
/// </summary>
Delete = 3,
}
private class LCS<T> : LongestCommonSubsequence<IList<T>>
{
public static readonly LCS<T> Default = new LCS<T>(EqualityComparer<T>.Default);
private readonly IEqualityComparer<T> _comparer;
public LCS(IEqualityComparer<T> comparer)
{
_comparer = comparer;
}
protected override bool ItemsEqual(IList<T> sequenceA, int indexA, IList<T> sequenceB, int indexB)
{
return _comparer.Equals(sequenceA[indexA], sequenceB[indexB]);
}
public IEnumerable<string> CalculateDiff(IList<T> sequenceA, IList<T> sequenceB, Func<T, string> toString)
{
foreach (var edit in base.GetEdits(sequenceA, sequenceA.Count, sequenceB, sequenceB.Count).Reverse())
{
switch (edit.Kind)
{
case EditKind.Delete:
yield return "--> " + toString(sequenceA[edit.IndexA]);
break;
case EditKind.Insert:
yield return "++> " + toString(sequenceB[edit.IndexB]);
break;
case EditKind.Update:
yield return " " + toString(sequenceB[edit.IndexB]);
break;
}
}
}
}
public static string DiffReport<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer, Func<T, string> toString, string separator)
{
var lcs = (comparer != null) ? new LCS<T>(comparer) : LCS<T>.Default;
toString = toString ?? new Func<T, string>(obj => obj.ToString());
IList<T> expectedList = expected as IList<T> ?? new List<T>(expected);
IList<T> actualList = actual as IList<T> ?? new List<T>(actual);
return string.Join(separator, lcs.CalculateDiff(expectedList, actualList, toString));
}
private static readonly char[] s_LineSplitChars = new[] { '\r', '\n' };
public static string[] Lines(string s)
{
return s.Split(s_LineSplitChars, StringSplitOptions.RemoveEmptyEntries);
}
public static string DiffReport(string expected, string actual)
{
var exlines = Lines(expected);
var aclines = Lines(actual);
return DiffReport(exlines, aclines, null, null, Environment.NewLine);
}
/// <summary>
/// Calculates Longest Common Subsequence.
/// </summary>
private abstract class LongestCommonSubsequence<TSequence>
{
protected struct Edit
{
public readonly EditKind Kind;
public readonly int IndexA;
public readonly int IndexB;
internal Edit(EditKind kind, int indexA, int indexB)
{
this.Kind = kind;
this.IndexA = indexA;
this.IndexB = indexB;
}
}
private const int DeleteCost = 1;
private const int InsertCost = 1;
private const int UpdateCost = 2;
protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB);
protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
}
else
{
i--;
j--;
yield return new KeyValuePair<int, int>(i, j);
}
}
}
protected IEnumerable<Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
else
{
i--;
j--;
yield return new Edit(EditKind.Update, i, j);
}
}
while (i > 0)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
while (j > 0)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
}
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
Debug.Assert(lengthA >= 0 && lengthB >= 0);
if (lengthA == 0 || lengthB == 0)
{
return (lengthA == lengthB) ? 0.0 : 1.0;
}
int lcsLength = 0;
foreach (var pair in GetMatchingPairs(sequenceA, lengthA, sequenceB, lengthB))
{
lcsLength++;
}
int max = Math.Max(lengthA, lengthB);
Debug.Assert(lcsLength <= max);
return 1.0 - (double)lcsLength / (double)max;
}
/// <summary>
/// Calculates costs of all paths in an edit graph starting from vertex (0,0) and ending in vertex (lengthA, lengthB).
/// </summary>
/// <remarks>
/// The edit graph for A and B has a vertex at each point in the grid (i,j), i in [0, lengthA] and j in [0, lengthB].
///
/// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph.
/// Horizontal edges connect each vertex to its right neighbor.
/// Vertical edges connect each vertex to the neighbor below it.
/// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true.
///
/// Editing starts with S = [].
/// Move along horizontal edge (i-1,j)-(i,j) represents the fact that sequenceA[i-1] is not added to S.
/// Move along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1] to S.
/// Move along diagonal edge (i-1,j-1)-(i,j) represents an addition of sequenceB[j-1] to S via an acceptable
/// change of sequenceA[i-1] to sequenceB[j-1].
///
/// In every vertex the cheapest outgoing edge is selected.
/// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common subsequence.
/// </remarks>
private int[,] ComputeCostMatrix(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
var la = lengthA + 1;
var lb = lengthB + 1;
// TODO: Optimization possible: O(ND) time, O(N) space
// EUGENE W. MYERS: An O(ND) Difference Algorithm and Its Variations
var d = new int[la, lb];
d[0, 0] = 0;
for (int i = 1; i <= lengthA; i++)
{
d[i, 0] = d[i - 1, 0] + DeleteCost;
}
for (int j = 1; j <= lengthB; j++)
{
d[0, j] = d[0, j - 1] + InsertCost;
}
for (int i = 1; i <= lengthA; i++)
{
for (int j = 1; j <= lengthB; j++)
{
int m1 = d[i - 1, j - 1] + (ItemsEqual(sequenceA, i - 1, sequenceB, j - 1) ? 0 : UpdateCost);
int m2 = d[i - 1, j] + DeleteCost;
int m3 = d[i, j - 1] + InsertCost;
d[i, j] = Math.Min(Math.Min(m1, m2), m3);
}
}
return d;
}
}
}
}
| |
using System.ComponentModel;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Automation.Peers;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
using Avalonia.Automation;
namespace Avalonia.Controls
{
/// <summary>
/// A tab control that displays a tab strip along with the content of the selected tab.
/// </summary>
public class TabControl : SelectingItemsControl, IContentPresenterHost
{
/// <summary>
/// Defines the <see cref="TabStripPlacement"/> property.
/// </summary>
public static readonly StyledProperty<Dock> TabStripPlacementProperty =
AvaloniaProperty.Register<TabControl, Dock>(nameof(TabStripPlacement), defaultValue: Dock.Top);
/// <summary>
/// Defines the <see cref="HorizontalContentAlignment"/> property.
/// </summary>
public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
ContentControl.HorizontalContentAlignmentProperty.AddOwner<TabControl>();
/// <summary>
/// Defines the <see cref="VerticalContentAlignment"/> property.
/// </summary>
public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
ContentControl.VerticalContentAlignmentProperty.AddOwner<TabControl>();
/// <summary>
/// Defines the <see cref="ContentTemplate"/> property.
/// </summary>
public static readonly StyledProperty<IDataTemplate?> ContentTemplateProperty =
ContentControl.ContentTemplateProperty.AddOwner<TabControl>();
/// <summary>
/// The selected content property
/// </summary>
public static readonly StyledProperty<object?> SelectedContentProperty =
AvaloniaProperty.Register<TabControl, object?>(nameof(SelectedContent));
/// <summary>
/// The selected content template property
/// </summary>
public static readonly StyledProperty<IDataTemplate?> SelectedContentTemplateProperty =
AvaloniaProperty.Register<TabControl, IDataTemplate?>(nameof(SelectedContentTemplate));
/// <summary>
/// The default value for the <see cref="ItemsControl.ItemsPanel"/> property.
/// </summary>
private static readonly FuncTemplate<IPanel> DefaultPanel =
new FuncTemplate<IPanel>(() => new WrapPanel());
/// <summary>
/// Initializes static members of the <see cref="TabControl"/> class.
/// </summary>
static TabControl()
{
SelectionModeProperty.OverrideDefaultValue<TabControl>(SelectionMode.AlwaysSelected);
ItemsPanelProperty.OverrideDefaultValue<TabControl>(DefaultPanel);
AffectsMeasure<TabControl>(TabStripPlacementProperty);
SelectedItemProperty.Changed.AddClassHandler<TabControl>((x, e) => x.UpdateSelectedContent());
AutomationProperties.ControlTypeOverrideProperty.OverrideDefaultValue<TabControl>(AutomationControlType.Tab);
}
/// <summary>
/// Gets or sets the horizontal alignment of the content within the control.
/// </summary>
public HorizontalAlignment HorizontalContentAlignment
{
get { return GetValue(HorizontalContentAlignmentProperty); }
set { SetValue(HorizontalContentAlignmentProperty, value); }
}
/// <summary>
/// Gets or sets the vertical alignment of the content within the control.
/// </summary>
public VerticalAlignment VerticalContentAlignment
{
get { return GetValue(VerticalContentAlignmentProperty); }
set { SetValue(VerticalContentAlignmentProperty, value); }
}
/// <summary>
/// Gets or sets the tabstrip placement of the TabControl.
/// </summary>
public Dock TabStripPlacement
{
get { return GetValue(TabStripPlacementProperty); }
set { SetValue(TabStripPlacementProperty, value); }
}
/// <summary>
/// Gets or sets the default data template used to display the content of the selected tab.
/// </summary>
public IDataTemplate? ContentTemplate
{
get { return GetValue(ContentTemplateProperty); }
set { SetValue(ContentTemplateProperty, value); }
}
/// <summary>
/// Gets or sets the content of the selected tab.
/// </summary>
/// <value>
/// The content of the selected tab.
/// </value>
public object? SelectedContent
{
get { return GetValue(SelectedContentProperty); }
internal set { SetValue(SelectedContentProperty, value); }
}
/// <summary>
/// Gets or sets the content template for the selected tab.
/// </summary>
/// <value>
/// The content template of the selected tab.
/// </value>
public IDataTemplate? SelectedContentTemplate
{
get { return GetValue(SelectedContentTemplateProperty); }
internal set { SetValue(SelectedContentTemplateProperty, value); }
}
internal ItemsPresenter? ItemsPresenterPart { get; private set; }
internal IContentPresenter? ContentPart { get; private set; }
/// <inheritdoc/>
IAvaloniaList<ILogical> IContentPresenterHost.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
bool IContentPresenterHost.RegisterContentPresenter(IContentPresenter presenter)
{
return RegisterContentPresenter(presenter);
}
protected override void OnContainersMaterialized(ItemContainerEventArgs e)
{
base.OnContainersMaterialized(e);
UpdateSelectedContent();
}
protected override void OnContainersRecycled(ItemContainerEventArgs e)
{
base.OnContainersRecycled(e);
UpdateSelectedContent();
}
private void UpdateSelectedContent()
{
if (SelectedIndex == -1)
{
SelectedContent = SelectedContentTemplate = null;
}
else
{
var container = SelectedItem as IContentControl ??
ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as IContentControl;
SelectedContentTemplate = container?.ContentTemplate;
SelectedContent = container?.Content;
}
}
/// <summary>
/// Called when an <see cref="IContentPresenter"/> is registered with the control.
/// </summary>
/// <param name="presenter">The presenter.</param>
protected virtual bool RegisterContentPresenter(IContentPresenter presenter)
{
if (presenter.Name == "PART_SelectedContentHost")
{
ContentPart = presenter;
return true;
}
return false;
}
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
return new TabItemContainerGenerator(this);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
ItemsPresenterPart = e.NameScope.Get<ItemsPresenter>("PART_ItemsPresenter");
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
if (e.NavigationMethod == NavigationMethod.Directional)
{
e.Handled = UpdateSelectionFromEventSource(e.Source);
}
}
/// <inheritdoc/>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed && e.Pointer.Type == PointerType.Mouse)
{
e.Handled = UpdateSelectionFromEventSource(e.Source);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (e.InitialPressMouseButton == MouseButton.Left && e.Pointer.Type != PointerType.Mouse)
{
var container = GetContainerFromEventSource(e.Source);
if (container != null
&& container.GetVisualsAt(e.GetPosition(container))
.Any(c => container == c || container.IsVisualAncestorOf(c)))
{
e.Handled = UpdateSelectionFromEventSource(e.Source);
}
}
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google 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:
//
// * 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 System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
using NUnit.Framework;
namespace Grpc.Core.Tests
{
public class ClientServerTest
{
const string Host = "localhost";
const string ServiceName = "/tests.Test";
static readonly Method<string, string> EchoMethod = new Method<string, string>(
MethodType.Unary,
"/tests.Test/Echo",
Marshallers.StringMarshaller,
Marshallers.StringMarshaller);
static readonly Method<string, string> ConcatAndEchoMethod = new Method<string, string>(
MethodType.ClientStreaming,
"/tests.Test/ConcatAndEcho",
Marshallers.StringMarshaller,
Marshallers.StringMarshaller);
static readonly Method<string, string> NonexistentMethod = new Method<string, string>(
MethodType.Unary,
"/tests.Test/NonexistentMethod",
Marshallers.StringMarshaller,
Marshallers.StringMarshaller);
static readonly ServerServiceDefinition ServiceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName)
.AddMethod(EchoMethod, EchoHandler)
.AddMethod(ConcatAndEchoMethod, ConcatAndEchoHandler)
.Build();
Server server;
Channel channel;
[TestFixtureSetUp]
public void InitClass()
{
GrpcEnvironment.Initialize();
}
[SetUp]
public void Init()
{
server = new Server();
server.AddServiceDefinition(ServiceDefinition);
int port = server.AddListeningPort(Host, Server.PickUnusedPort);
server.Start();
channel = new Channel(Host + ":" + port);
}
[TearDown]
public void Cleanup()
{
channel.Dispose();
server.ShutdownAsync().Wait();
}
[TestFixtureTearDown]
public void CleanupClass()
{
GrpcEnvironment.Shutdown();
}
[Test]
public void UnaryCall()
{
var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty);
Assert.AreEqual("ABC", Calls.BlockingUnaryCall(call, "ABC", CancellationToken.None));
}
[Test]
public void UnaryCall_ServerHandlerThrows()
{
var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty);
try
{
Calls.BlockingUnaryCall(call, "THROW", CancellationToken.None);
Assert.Fail();
}
catch (RpcException e)
{
Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
}
}
[Test]
public void AsyncUnaryCall()
{
var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty);
var result = Calls.AsyncUnaryCall(call, "ABC", CancellationToken.None).Result;
Assert.AreEqual("ABC", result);
}
[Test]
public void AsyncUnaryCall_ServerHandlerThrows()
{
Task.Run(async () =>
{
var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty);
try
{
await Calls.AsyncUnaryCall(call, "THROW", CancellationToken.None);
Assert.Fail();
}
catch (RpcException e)
{
Assert.AreEqual(StatusCode.Unknown, e.Status.StatusCode);
}
}).Wait();
}
[Test]
public void ClientStreamingCall()
{
Task.Run(async () =>
{
var call = new Call<string, string>(ServiceName, ConcatAndEchoMethod, channel, Metadata.Empty);
var callResult = Calls.AsyncClientStreamingCall(call, CancellationToken.None);
await callResult.RequestStream.WriteAll(new string[] { "A", "B", "C" });
Assert.AreEqual("ABC", await callResult.Result);
}).Wait();
}
[Test]
public void ClientStreamingCall_CancelAfterBegin()
{
Task.Run(async () =>
{
var call = new Call<string, string>(ServiceName, ConcatAndEchoMethod, channel, Metadata.Empty);
var cts = new CancellationTokenSource();
var callResult = Calls.AsyncClientStreamingCall(call, cts.Token);
// TODO(jtattermusch): we need this to ensure call has been initiated once we cancel it.
await Task.Delay(1000);
cts.Cancel();
try
{
await callResult.Result;
}
catch (RpcException e)
{
Assert.AreEqual(StatusCode.Cancelled, e.Status.StatusCode);
}
}).Wait();
}
[Test]
public void UnaryCall_DisposedChannel()
{
channel.Dispose();
var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty);
Assert.Throws(typeof(ObjectDisposedException), () => Calls.BlockingUnaryCall(call, "ABC", CancellationToken.None));
}
[Test]
public void UnaryCallPerformance()
{
var call = new Call<string, string>(ServiceName, EchoMethod, channel, Metadata.Empty);
BenchmarkUtil.RunBenchmark(100, 100,
() => { Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken)); });
}
[Test]
public void UnknownMethodHandler()
{
var call = new Call<string, string>(ServiceName, NonexistentMethod, channel, Metadata.Empty);
try
{
Calls.BlockingUnaryCall(call, "ABC", default(CancellationToken));
Assert.Fail();
}
catch (RpcException e)
{
Assert.AreEqual(StatusCode.Unimplemented, e.Status.StatusCode);
}
}
private static async Task<string> EchoHandler(ServerCallContext context, string request)
{
if (request == "THROW")
{
throw new Exception("This was thrown on purpose by a test");
}
return request;
}
private static async Task<string> ConcatAndEchoHandler(ServerCallContext context, IAsyncStreamReader<string> requestStream)
{
string result = "";
await requestStream.ForEach(async (request) =>
{
if (request == "THROW")
{
throw new Exception("This was thrown on purpose by a test");
}
result += request;
});
// simulate processing takes some time.
await Task.Delay(250);
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Threading;
/// <devdoc>
/// Animates one or more images that have time-based frames.
/// See the ImageInfo.cs file for the helper nested ImageInfo class.
///
/// A common pattern for using this class is as follows (See PictureBox control):
/// 1. The winform app (user's code) calls ImageAnimator.Animate() from the main thread.
/// 2. Animate() spawns the animating (worker) thread in the background, which will update the image
/// frames and raise the OnFrameChanged event, which handler will be executed in the main thred.
/// 3. The main thread triggers a paint event (Invalidate()) from the OnFrameChanged handler.
/// 4. From the OnPaint event, the main thread calls ImageAnimator.UpdateFrames() and then paints the
/// image (updated frame).
/// 5. The main thread calls ImageAnimator.StopAnimate() when needed. This does not kill the worker thread.
///
/// Comment on locking the image ref:
/// We need to synchronize access to sections of code that modify the image(s), but we don't want to block
/// animation of one image when modifying a different one; for this, we use the image ref for locking the
/// critical section (lock(image)).
///
/// This class is safe for multi-threading but Image is not; multithreaded applications must use a critical
/// section lock using the image ref the image access is not from the same thread that executes ImageAnimator
/// code. If the user code locks on the image ref forever a deadlock will happen preventing the animiation
/// from occurring.
/// </devdoc>
public sealed partial class ImageAnimator
{
/// <devdoc>
/// A list of images to be animated.
/// </devdoc>
private static List<ImageInfo> s_imageInfoList;
/// <devdoc>
/// A variable to flag when an image or images need to be updated due to the selection of a new frame
/// in an image. We don't need to synchronize access to this variable, in the case it is true we don't
/// do anything, otherwise the worse case is where a thread attempts to update the image's frame after
/// another one did which is harmless.
/// </devdoc>
private static bool s_anyFrameDirty;
/// <devdoc>
/// The thread used for animating the images.
/// </devdoc>
private static Thread s_animationThread;
/// <devdoc>
/// Lock that allows either concurrent read-access to the images list for multiple threads, or write-
/// access to it for a single thread. Observe that synchronization access to image objects are done
/// with critical sections (lock).
/// </devdoc>
private static ReaderWriterLock s_rwImgListLock = new ReaderWriterLock();
/// <devdoc>
/// Flag to avoid a deadlock when waiting on a write-lock and a an attemp to acquire a read-lock is
/// made in the same thread. If RWLock is currently owned by another thread, the current thread is going to wait on an
/// event using CoWaitForMultipleHandles while pumps message.
/// The comment above refers to the COM STA message pump, not to be confused with the UI message pump.
/// However, the effect is the same, the COM message pump will pump messages and dispatch them to the
/// window while waiting on the writer lock; this has the potential of creating a re-entrancy situation
// that if during the message processing a wait on a reader lock is originated the thread will be block
// on itself.
/// While processing STA message, the thread may call back into managed code. We do this because
/// we can not block finalizer thread. Finalizer thread may need to release STA objects on this thread. If
/// the current thread does not pump message, finalizer thread is blocked, and AD unload is blocked while
/// waiting for finalizer thread. RWLock is a fair lock. If a thread waits for a writer lock, then it needs
/// a reader lock while pumping message, the thread is blocked forever.
/// This TLS variable is used to flag the above situation and avoid the deadlock, it is ThreadStatic so each
/// thread calling into ImageAnimator is garded against this problem.
/// </devdoc>
[ThreadStatic]
private static int t_threadWriterLockWaitCount;
/// <devdoc>
/// Prevent instantiation of this class.
/// </devdoc>
private ImageAnimator()
{
}
/// <devdoc>
/// Advances the frame in the specified image. The new frame is drawn the next time the image is rendered.
/// </devdoc>
public static void UpdateFrames(Image image)
{
if (!s_anyFrameDirty || image == null || s_imageInfoList == null)
{
return;
}
if (t_threadWriterLockWaitCount > 0)
{
// Cannot acquire reader lock - frame update will be missed.
return;
}
// If the current thread already has the writer lock, no reader lock is acquired. Instead, the lock count on
// the writer lock is incremented. It it already has a reader lock, the locks ref count will be incremented
// w/o placing the request at the end of the reader queue.
s_rwImgListLock.AcquireReaderLock(Timeout.Infinite);
try
{
bool foundDirty = false;
bool foundImage = false;
foreach (ImageInfo imageInfo in s_imageInfoList)
{
if (imageInfo.Image == image)
{
if (imageInfo.FrameDirty)
{
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (imageInfo.Image)
{
#pragma warning restore CA2002
imageInfo.UpdateFrame();
}
}
foundImage = true;
}
if (imageInfo.FrameDirty)
{
foundDirty = true;
}
if (foundDirty && foundImage)
{
break;
}
}
s_anyFrameDirty = foundDirty;
}
finally
{
s_rwImgListLock.ReleaseReaderLock();
}
}
/// <devdoc>
/// Advances the frame in all images currently being animated. The new frame is drawn the next time the image is rendered.
/// </devdoc>
public static void UpdateFrames()
{
if (!s_anyFrameDirty || s_imageInfoList == null)
{
return;
}
if (t_threadWriterLockWaitCount > 0)
{
// Cannot acquire reader lock at this time, frames update will be missed.
return;
}
s_rwImgListLock.AcquireReaderLock(Timeout.Infinite);
try
{
foreach (ImageInfo imageInfo in s_imageInfoList)
{
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (imageInfo.Image)
{
#pragma warning restore CA2002
imageInfo.UpdateFrame();
}
}
s_anyFrameDirty = false;
}
finally
{
s_rwImgListLock.ReleaseReaderLock();
}
}
/// <devdoc>
/// Adds an image to the image manager. If the image does not support animation this method does nothing.
/// This method creates the image list and spawns the animation thread the first time it is called.
/// </devdoc>
public static void Animate(Image image, EventHandler onFrameChangedHandler)
{
if (image == null)
{
return;
}
ImageInfo imageInfo = null;
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (image)
{
#pragma warning restore CA2002
// could we avoid creating an ImageInfo object if FrameCount == 1 ?
imageInfo = new ImageInfo(image);
}
// If the image is already animating, stop animating it
StopAnimate(image, onFrameChangedHandler);
// Acquire a writer lock to modify the image info list. If the thread has a reader lock we need to upgrade
// it to a writer lock; acquiring a reader lock in this case would block the thread on itself.
// If the thread already has a writer lock its ref count will be incremented w/o placing the request in the
// writer queue. See ReaderWriterLock.AcquireWriterLock method in the MSDN.
bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
LockCookie lockDowngradeCookie = new LockCookie();
t_threadWriterLockWaitCount++;
try
{
if (readerLockHeld)
{
lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite);
}
else
{
s_rwImgListLock.AcquireWriterLock(Timeout.Infinite);
}
}
finally
{
t_threadWriterLockWaitCount--;
Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero.");
}
try
{
if (imageInfo.Animated)
{
// Construct the image array
//
if (s_imageInfoList == null)
{
s_imageInfoList = new List<ImageInfo>();
}
// Add the new image
//
imageInfo.FrameChangedHandler = onFrameChangedHandler;
s_imageInfoList.Add(imageInfo);
// Construct a new timer thread if we haven't already
//
if (s_animationThread == null)
{
s_animationThread = new Thread(new ThreadStart(AnimateImages50ms));
s_animationThread.Name = typeof(ImageAnimator).Name;
s_animationThread.IsBackground = true;
s_animationThread.Start();
}
}
}
finally
{
if (readerLockHeld)
{
s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie);
}
else
{
s_rwImgListLock.ReleaseWriterLock();
}
}
}
/// <devdoc>
/// Whether or not the image has multiple time-based frames.
/// </devdoc>
public static bool CanAnimate(Image image)
{
if (image == null)
{
return false;
}
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (image)
{
#pragma warning restore CA2002
Guid[] dimensions = image.FrameDimensionsList;
foreach (Guid guid in dimensions)
{
FrameDimension dimension = new FrameDimension(guid);
if (dimension.Equals(FrameDimension.Time))
{
return image.GetFrameCount(FrameDimension.Time) > 1;
}
}
}
return false;
}
/// <devdoc>
/// Removes an image from the image manager so it is no longer animated.
/// </devdoc>
public static void StopAnimate(Image image, EventHandler onFrameChangedHandler)
{
// Make sure we have a list of images
if (image == null || s_imageInfoList == null)
{
return;
}
// Acquire a writer lock to modify the image info list - See comments on Animate() about this locking.
bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
LockCookie lockDowngradeCookie = new LockCookie();
t_threadWriterLockWaitCount++;
try
{
if (readerLockHeld)
{
lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite);
}
else
{
s_rwImgListLock.AcquireWriterLock(Timeout.Infinite);
}
}
finally
{
t_threadWriterLockWaitCount--;
Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero.");
}
try
{
// Find the corresponding reference and remove it
for (int i = 0; i < s_imageInfoList.Count; i++)
{
ImageInfo imageInfo = s_imageInfoList[i];
if (image == imageInfo.Image)
{
if ((onFrameChangedHandler == imageInfo.FrameChangedHandler) || (onFrameChangedHandler != null && onFrameChangedHandler.Equals(imageInfo.FrameChangedHandler)))
{
s_imageInfoList.Remove(imageInfo);
}
break;
}
}
}
finally
{
if (readerLockHeld)
{
s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie);
}
else
{
s_rwImgListLock.ReleaseWriterLock();
}
}
}
/// <devdoc>
/// Worker thread procedure which implements the main animation loop.
/// NOTE: This is the ONLY code the worker thread executes, keeping it in one method helps better understand
/// any synchronization issues.
/// WARNING: Also, this is the only place where ImageInfo objects (not the contained image object) are modified,
/// so no access synchronization is required to modify them.
/// </devdoc>
private static void AnimateImages50ms()
{
Debug.Assert(s_imageInfoList != null, "Null images list");
while (true)
{
// Acquire reader-lock to access imageInfoList, elemens in the list can be modified w/o needing a writer-lock.
// Observe that we don't need to check if the thread is waiting or a writer lock here since the thread this
// method runs in never acquires a writer lock.
s_rwImgListLock.AcquireReaderLock(Timeout.Infinite);
try
{
for (int i = 0; i < s_imageInfoList.Count; i++)
{
ImageInfo imageInfo = s_imageInfoList[i];
// Frame delay is measured in 1/100ths of a second. This thread
// sleeps for 50 ms = 5/100ths of a second between frame updates,
// so we increase the frame delay count 5/100ths of a second
// at a time.
//
imageInfo.FrameTimer += 5;
if (imageInfo.FrameTimer >= imageInfo.FrameDelay(imageInfo.Frame))
{
imageInfo.FrameTimer = 0;
if (imageInfo.Frame + 1 < imageInfo.FrameCount)
{
imageInfo.Frame++;
}
else
{
imageInfo.Frame = 0;
}
if (imageInfo.FrameDirty)
{
s_anyFrameDirty = true;
}
}
}
}
finally
{
s_rwImgListLock.ReleaseReaderLock();
}
Thread.Sleep(50);
}
}
}
}
| |
#region Foreign-License
/*
Implements the Jacl version of the Notifier class.
Copyright (c) 1997 Sun Microsystems, Inc.
Copyright (c) 2012 Sky Morey
See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#endregion
using System;
using System.Collections;
using System.Threading;
namespace Tcl.Lang
{
// Implements the Jacl version of the Notifier class. The Notifier is
// the lowest-level part of the event system. It is used by
// higher-level event sources such as file, JavaBean and timer
// events. The Notifier manages an event queue that holds TclEvent
// objects.
//
// The Jacl notifier is designed to run in a multi-threaded
// environment. Each notifier instance is associated with a primary
// thread. Any thread can queue (or dequeue) events using the
// queueEvent (or deleteEvents) call. However, only the primary thread
// may process events in the queue using the doOneEvent()
// call. Attepmts to call doOneEvent from a non-primary thread will
// cause a TclRuntimeError.
//
// This class does not have a public constructor and thus cannot be
// instantiated. The only way to for a Tcl extension to get an
// Notifier is to call Interp.getNotifier() (or
// Notifier.getNotifierForThread() ), which returns the Notifier for that
// interpreter (thread).
public class Notifier : IEventDeleter
{
private TclEvent _firstEvent; // First pending event, or null if none.
private TclEvent _lastEvent; // Last pending event, or null if none.
private TclEvent _markerEvent; // Last high-priority event in queue, or null if none.
private TclEvent _servicedEvent = null; // Event that was just processed by serviceEvent
internal Thread PrimaryThread; // The primary thread of this notifier. Only this thread should process events from the event queue.
private static Hashtable _notifierTable; // Stores the Notifier for each thread.
internal ArrayList TimerList; // List of registered timer handlers.
internal int TimerGeneration; // Used to distinguish older timer handlers from recently-created ones.
internal bool TimerPending; // True if there is a pending timer event in the event queue, false otherwise.
internal ArrayList IdleList; // List of registered idle handlers.
internal int IdleGeneration; // Used to distinguish older idle handlers from recently-created ones.
private int _refCount; // Reference count of the notifier. It's used to tell when a notifier is no longer needed.
private Notifier(Thread primaryThread)
{
PrimaryThread = primaryThread;
_firstEvent = null;
_lastEvent = null;
_markerEvent = null;
TimerList = new ArrayList(10);
TimerGeneration = 0;
IdleList = new ArrayList(10);
IdleGeneration = 0;
TimerPending = false;
_refCount = 0;
}
/// <summary>
///
/// </summary>
/// <param name="thread">The thread that owns this Notifier.</param>
/// <returns></returns>
public static Notifier GetNotifierForThread(Thread thread)
{
lock (typeof(Notifier))
{
Notifier notifier = (Notifier)_notifierTable[thread];
if (notifier == null)
{
notifier = new Notifier(thread);
SupportClass.PutElement(_notifierTable, thread, notifier);
}
return notifier;
}
}
public void Preserve()
{
lock (this)
{
if (_refCount < 0)
throw new TclRuntimeError("Attempting to preserve a freed Notifier");
++_refCount;
}
}
public void Release()
{
lock (this)
{
if (_refCount == 0 && PrimaryThread != null)
throw new TclRuntimeError("Attempting to release a Notifier before it's preserved");
if (_refCount <= 0)
throw new TclRuntimeError("Attempting to release a freed Notifier");
--_refCount;
if (_refCount == 0)
{
SupportClass.HashtableRemove(_notifierTable, PrimaryThread);
PrimaryThread = null;
}
}
}
// One of TCL.QUEUE_TAIL, TCL.QUEUE_HEAD or TCL.QUEUE_MARK.
public void QueueEvent(TclEvent evt, TCL.QUEUE position)
{
lock (this)
{
evt.notifier = this;
if (position == TCL.QUEUE.TAIL)
{
// Append the event on the end of the queue.
evt.next = null;
if (_firstEvent == null)
_firstEvent = evt;
else
_lastEvent.next = evt;
_lastEvent = evt;
}
else if (position == TCL.QUEUE.HEAD)
{
// Push the event on the head of the queue.
evt.next = _firstEvent;
if (_firstEvent == null)
_lastEvent = evt;
_firstEvent = evt;
}
else if (position == TCL.QUEUE.MARK)
{
// Insert the event after the current marker event and advance the marker to the new event.
if (_markerEvent == null)
{
evt.next = _firstEvent;
_firstEvent = evt;
}
else
{
evt.next = _markerEvent.next;
_markerEvent.next = evt;
}
_markerEvent = evt;
if (evt.next == null)
_lastEvent = evt;
}
else
{
// Wrong flag.
throw new TclRuntimeError("wrong position \"" + position + "\", must be TCL.QUEUE_HEAD, TCL.QUEUE_TAIL or TCL.QUEUE_MARK");
}
if (Thread.CurrentThread != PrimaryThread)
Monitor.PulseAll(this);
}
}
// The deleter that checks whether an event should be removed.
public void deleteEvents(IEventDeleter deleter)
{
lock (this)
{
TclEvent servicedEvent = null;
// Handle the special case of deletion of a single event that was just processed by the serviceEvent() method.
if (deleter == this)
{
servicedEvent = _servicedEvent;
if (servicedEvent == null)
throw new TclRuntimeError("servicedEvent was not set by serviceEvent()");
_servicedEvent = null;
}
for (TclEvent prev = null, evt = _firstEvent; evt != null; evt = evt.next)
{
if ((servicedEvent == null && deleter.DeleteEvent(evt)) || evt == servicedEvent)
{
if (evt == _firstEvent)
_firstEvent = evt.next;
else
prev.next = evt.next;
if (evt.next == null)
_lastEvent = prev;
if (evt == _markerEvent)
_markerEvent = prev;
if (evt == servicedEvent)
{
servicedEvent = null;
break; // Just service this one event in the special case
}
}
else
prev = evt;
}
if (servicedEvent != null)
throw new TclRuntimeError("servicedEvent was not removed from the queue");
}
}
public bool DeleteEvent(TclEvent evt)
{
throw new TclRuntimeError("The Notifier.deleteEvent() method should not be called");
}
internal int serviceEvent(int flags)
// Indicates what events should be processed.
// May be any combination of TCL.WINDOW_EVENTS
// TCL.FILE_EVENTS, TCL.TIMER_EVENTS, or other
// flags defined elsewhere. Events not
// matching this will be skipped for processing
// later.
{
TclEvent evt;
// No event flags is equivalent to TCL_ALL_EVENTS.
if ((flags & TCL.ALL_EVENTS) == 0)
{
flags |= TCL.ALL_EVENTS;
}
// Loop through all the events in the queue until we find one
// that can actually be handled.
evt = null;
while ((evt = getAvailableEvent(evt)) != null)
{
// Call the handler for the event. If it actually handles the
// event then free the storage for the event. There are two
// tricky things here, both stemming from the fact that the event
// code may be re-entered while servicing the event:
//
// 1. Set the "isProcessing" field to true. This is a signal to
// ourselves that we shouldn't reexecute the handler if the
// event loop is re-entered.
// 2. When freeing the event, must search the queue again from the
// front to find it. This is because the event queue could
// change almost arbitrarily while handling the event, so we
// can't depend on pointers found now still being valid when
// the handler returns.
evt.isProcessing = true;
if (evt.processEvent(flags) != 0)
{
evt.isProcessed = true;
// Don't allocate/grab the monitor for the event unless sync()
// has been called in another thread. This is thread safe
// since sync() checks the isProcessed flag before calling wait.
if (evt.needsNotify)
{
lock (evt)
{
System.Threading.Monitor.PulseAll(evt);
}
}
// Remove this specific event from the queue
_servicedEvent = evt;
deleteEvents(this);
return 1;
}
else
{
// The event wasn't actually handled, so we have to
// restore the isProcessing field to allow the event to be
// attempted again.
evt.isProcessing = false;
}
// The handler for this event asked to defer it. Just go on to
// the next event.
continue;
}
return 0;
}
private TclEvent getAvailableEvent(TclEvent skipEvent)
// Indicates that the given event should not
// be returned. This argument can be null.
{
lock (this)
{
TclEvent evt;
for (evt = _firstEvent; evt != null; evt = evt.next)
{
if ((evt.isProcessing == false) && (evt.isProcessed == false) && (evt != skipEvent))
{
return evt;
}
}
return null;
}
}
public int doOneEvent(int flags)
// Miscellaneous flag values: may be any
// combination of TCL.DONT_WAIT,
// TCL.WINDOW_EVENTS, TCL.FILE_EVENTS,
// TCL.TIMER_EVENTS, TCL.IDLE_EVENTS,
// or others defined by event sources.
{
int result = 0;
// No event flags is equivalent to TCL_ALL_EVENTS.
if ((flags & TCL.ALL_EVENTS) == 0)
{
flags |= TCL.ALL_EVENTS;
}
// The core of this procedure is an infinite loop, even though
// we only service one event. The reason for this is that we
// may be processing events that don't do anything inside of Tcl.
while (true)
{
// If idle events are the only things to service, skip the
// main part of the loop and go directly to handle idle
// events (i.e. don't wait even if TCL_DONT_WAIT isn't set).
if ((flags & TCL.ALL_EVENTS) == TCL.IDLE_EVENTS)
{
return serviceIdle();
}
long sysTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
// If some timers have been expired, queue them into the
// event queue. We can't process expired times right away,
// because there may already be other events on the queue.
if (!TimerPending && (TimerList.Count > 0))
{
TimerHandler h = (TimerHandler)TimerList[0];
if (h.atTime <= sysTime)
{
TimerEvent Tevent = new TimerEvent();
Tevent.notifier = this;
QueueEvent(Tevent, TCL.QUEUE.TAIL);
TimerPending = true;
}
}
// Service a queued event, if there are any.
if (serviceEvent(flags) != 0)
{
result = 1;
break;
}
// There is no event on the queue. Check for idle events.
if ((flags & TCL.IDLE_EVENTS) != 0)
{
if (serviceIdle() != 0)
{
result = 1;
break;
}
}
if ((flags & TCL.DONT_WAIT) != 0)
{
break;
}
// We don't have any event to service. We'll wait if
// TCL.DONT_WAIT. When the following wait() call returns,
// one of the following things may happen:
//
// (1) waitTime milliseconds has elasped (if waitTime != 0);
//
// (2) The primary notifier has been notify()'ed by other threads:
// (a) an event is queued by queueEvent().
// (b) a timer handler was created by new TimerHandler();
// (c) an idle handler was created by new IdleHandler();
// (3) We receive an InterruptedException.
//
try
{
// Don't acquire the monitor until we are about to wait
// for notification from another thread. It is critical
// that this entire method not be synchronized since
// a call to processEvent via serviceEvent could take
// a very long time. We don't want the monitor held
// during that time since that would force calls to
// queueEvent in other threads to wait.
lock (this)
{
if (TimerList.Count > 0)
{
TimerHandler h = (TimerHandler)TimerList[0];
long waitTime = h.atTime - sysTime;
if (waitTime > 0)
{
System.Threading.Monitor.Wait(this, TimeSpan.FromMilliseconds(waitTime));
}
}
else
{
System.Threading.Monitor.Wait(this);
}
} // synchronized (this)
}
catch (System.Threading.ThreadInterruptedException e)
{
// We ignore any InterruptedException and loop continuously
// until we receive an event.
}
}
return result;
}
private int serviceIdle()
{
int result = 0;
int gen = IdleGeneration;
IdleGeneration++;
// The code below is trickier than it may look, for the following
// reasons:
//
// 1. New handlers can get added to the list while the current
// one is being processed. If new ones get added, we don't
// want to process them during this pass through the list (want
// to check for other work to do first). This is implemented
// using the generation number in the handler: new handlers
// will have a different generation than any of the ones currently
// on the list.
// 2. The handler can call doOneEvent, so we have to remove
// the handler from the list before calling it. Otherwise an
// infinite loop could result.
while (IdleList.Count > 0)
{
IdleHandler h = (IdleHandler)IdleList[0];
if (h.Generation > gen)
{
break;
}
IdleList.RemoveAt(0);
if (h.Invoke() != 0)
{
result = 1;
}
}
return result;
}
static Notifier()
{
_notifierTable = new Hashtable();
}
} // end Notifier
class TimerEvent : TclEvent
{
// The notifier what owns this TimerEvent.
new internal Notifier notifier;
public override int processEvent(int flags)
// Same as flags passed to Notifier.doOneEvent.
{
if ((flags & TCL.TIMER_EVENTS) == 0)
{
return 0;
}
long sysTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;
int gen = notifier.TimerGeneration;
notifier.TimerGeneration++;
// The code below is trickier than it may look, for the following
// reasons:
//
// 1. New handlers can get added to the list while the current
// one is being processed. If new ones get added, we don't
// want to process them during this pass through the list to
// avoid starving other event sources. This is implemented
// using the timer generation number: new handlers will have
// a newer generation number than any of the ones currently on
// the list.
// 2. The handler can call doOneEvent, so we have to remove
// the handler from the list before calling it. Otherwise an
// infinite loop could result.
// 3. Because we only fetch the current time before entering the loop,
// the only way a new timer will even be considered runnable is if
// its expiration time is within the same millisecond as the
// current time. This is fairly likely on Windows, since it has
// a course granularity clock. Since timers are placed
// on the queue in time order with the most recently created
// handler appearing after earlier ones with the same expiration
// time, we don't have to worry about newer generation timers
// appearing before later ones.
while (notifier.TimerList.Count > 0)
{
TimerHandler h = (TimerHandler)notifier.TimerList[0];
if (h.generation > gen)
{
break;
}
if (h.atTime > sysTime)
{
break;
}
notifier.TimerList.RemoveAt(0);
h.invoke();
}
notifier.TimerPending = false;
return 1;
}
} // end TimerEvent
}
| |
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace Newtonsoft.Json.Utilities
{
internal static class TypeExtensions
{
private static BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo)
{
return propertyInfo.GetGetMethod(false);
}
public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic)
{
MethodInfo getMethod = propertyInfo.GetMethod;
if (getMethod != null && (getMethod.IsPublic || nonPublic))
return getMethod;
return null;
}
public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo)
{
return propertyInfo.GetSetMethod(false);
}
public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic)
{
MethodInfo setMethod = propertyInfo.SetMethod;
if (setMethod != null && (setMethod.IsPublic || nonPublic))
return setMethod;
return null;
}
public static bool IsSubclassOf(this Type type, Type c)
{
return type.GetTypeInfo().IsSubclassOf(c);
}
public static bool IsAssignableFrom(this Type type, Type c)
{
return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo());
}
public static MethodInfo Method(this Delegate d)
{
return d.GetMethodInfo();
}
public static MemberTypes MemberType(this MemberInfo memberInfo)
{
if (memberInfo is PropertyInfo)
return MemberTypes.Property;
else if (memberInfo is FieldInfo)
return MemberTypes.Field;
else if (memberInfo is EventInfo)
return MemberTypes.Event;
else if (memberInfo is MethodInfo)
return MemberTypes.Method;
else
return MemberTypes.Other;
}
public static bool ContainsGenericParameters(this Type type)
{
return type.GetTypeInfo().ContainsGenericParameters;
}
public static bool IsInterface(this Type type)
{
return type.GetTypeInfo().IsInterface;
}
public static bool IsGenericType(this Type type)
{
return type.GetTypeInfo().IsGenericType;
}
public static bool IsGenericTypeDefinition(this Type type)
{
return type.GetTypeInfo().IsGenericTypeDefinition;
}
public static Type BaseType(this Type type)
{
return type.GetTypeInfo().BaseType;
}
public static bool IsEnum(this Type type)
{
return type.GetTypeInfo().IsEnum;
}
public static bool IsClass(this Type type)
{
return type.GetTypeInfo().IsClass;
}
public static bool IsSealed(this Type type)
{
return type.GetTypeInfo().IsSealed;
}
public static MethodInfo GetBaseDefinition(this MethodInfo method)
{
return method.GetRuntimeBaseDefinition();
}
public static bool IsDefined(this Type type, Type attributeType, bool inherit)
{
return type.GetTypeInfo().CustomAttributes.Any(a => a.AttributeType == attributeType);
}
public static MethodInfo GetMethod(this Type type, string name)
{
return type.GetMethod(name, DefaultFlags);
}
public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags)
{
return type.GetTypeInfo().GetDeclaredMethod(name);
}
public static MethodInfo GetMethod(this Type type, IList<Type> parameterTypes)
{
return type.GetMethod(null, parameterTypes);
}
public static MethodInfo GetMethod(this Type type, string name, IList<Type> parameterTypes)
{
return type.GetMethod(name, DefaultFlags, null, parameterTypes, null);
}
public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags, object placeHolder1, IList<Type> parameterTypes, object placeHolder2)
{
return type.GetTypeInfo().DeclaredMethods.Where(m =>
{
if (name != null && m.Name != name)
return false;
if (!TestAccessibility(m, bindingFlags))
return false;
return m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes);
}).SingleOrDefault();
}
public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags, object placeholder1, Type propertyType, IList<Type> indexParameters, object placeholder2)
{
return type.GetTypeInfo().DeclaredProperties.Where(p =>
{
if (name != null && name != p.Name)
return false;
if (propertyType != null && propertyType != p.PropertyType)
return false;
if (indexParameters != null)
{
if (!p.GetIndexParameters().Select(ip => ip.ParameterType).SequenceEqual(indexParameters))
return false;
}
return true;
}).SingleOrDefault();
}
public static IEnumerable<MemberInfo> GetMember(this Type type, string name, MemberTypes memberType, BindingFlags bindingFlags)
{
return type.GetTypeInfo().GetMembersRecursive().Where(m =>
{
if (name != null && name != m.Name)
return false;
if (m.MemberType() != memberType)
return false;
if (!TestAccessibility(m, bindingFlags))
return false;
return true;
});
}
public static IEnumerable<ConstructorInfo> GetConstructors(this Type type)
{
return type.GetConstructors(DefaultFlags);
}
public static IEnumerable<ConstructorInfo> GetConstructors(this Type type, BindingFlags bindingFlags)
{
return type.GetConstructors(bindingFlags, null);
}
private static IEnumerable<ConstructorInfo> GetConstructors(this Type type, BindingFlags bindingFlags, IList<Type> parameterTypes)
{
return type.GetTypeInfo().DeclaredConstructors.Where(c =>
{
if (!TestAccessibility(c, bindingFlags))
return false;
if (parameterTypes != null && !c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes))
return false;
return true;
});
}
public static ConstructorInfo GetConstructor(this Type type, IList<Type> parameterTypes)
{
return type.GetConstructor(DefaultFlags, null, parameterTypes, null);
}
public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object placeholder1, IList<Type> parameterTypes, object placeholder2)
{
return type.GetConstructors(bindingFlags, parameterTypes).SingleOrDefault();
}
public static MemberInfo[] GetMember(this Type type, string member)
{
return type.GetMember(member, DefaultFlags);
}
public static MemberInfo[] GetMember(this Type type, string member, BindingFlags bindingFlags)
{
return type.GetTypeInfo().GetMembersRecursive().Where(m => m.Name == member && TestAccessibility(m, bindingFlags)).ToArray();
}
public static MemberInfo GetField(this Type type, string member)
{
return type.GetField(member, DefaultFlags);
}
public static MemberInfo GetField(this Type type, string member, BindingFlags bindingFlags)
{
return type.GetTypeInfo().GetDeclaredField(member);
}
public static IEnumerable<PropertyInfo> GetProperties(this Type type, BindingFlags bindingFlags)
{
IList<PropertyInfo> properties = (bindingFlags.HasFlag(BindingFlags.DeclaredOnly))
? type.GetTypeInfo().DeclaredProperties.ToList()
: type.GetTypeInfo().GetPropertiesRecursive();
return properties.Where(p => TestAccessibility(p, bindingFlags));
}
private static IList<MemberInfo> GetMembersRecursive(this TypeInfo type)
{
TypeInfo t = type;
IList<MemberInfo> members = new List<MemberInfo>();
while (t != null)
{
foreach (var member in t.DeclaredMembers)
{
if (!members.Any(p => p.Name == member.Name))
members.Add(member);
}
t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null;
}
return members;
}
private static IList<PropertyInfo> GetPropertiesRecursive(this TypeInfo type)
{
TypeInfo t = type;
IList<PropertyInfo> properties = new List<PropertyInfo>();
while (t != null)
{
foreach (var member in t.DeclaredProperties)
{
if (!properties.Any(p => p.Name == member.Name))
properties.Add(member);
}
t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null;
}
return properties;
}
private static IList<FieldInfo> GetFieldsRecursive(this TypeInfo type)
{
TypeInfo t = type;
IList<FieldInfo> fields = new List<FieldInfo>();
while (t != null)
{
foreach (var member in t.DeclaredFields)
{
if (!fields.Any(p => p.Name == member.Name))
fields.Add(member);
}
t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null;
}
return fields;
}
public static IEnumerable<MethodInfo> GetMethods(this Type type, BindingFlags bindingFlags)
{
return type.GetTypeInfo().DeclaredMethods;
}
public static PropertyInfo GetProperty(this Type type, string name)
{
return type.GetProperty(name, DefaultFlags);
}
public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags)
{
return type.GetTypeInfo().GetDeclaredProperty(name);
}
public static IEnumerable<FieldInfo> GetFields(this Type type)
{
return type.GetFields(DefaultFlags);
}
public static IEnumerable<FieldInfo> GetFields(this Type type, BindingFlags bindingFlags)
{
IList<FieldInfo> fields = (bindingFlags.HasFlag(BindingFlags.DeclaredOnly))
? type.GetTypeInfo().DeclaredFields.ToList()
: type.GetTypeInfo().GetFieldsRecursive();
return fields.Where(f => TestAccessibility(f, bindingFlags)).ToList();
}
private static bool TestAccessibility(PropertyInfo member, BindingFlags bindingFlags)
{
if (member.GetMethod != null && TestAccessibility(member.GetMethod, bindingFlags))
return true;
if (member.SetMethod != null && TestAccessibility(member.SetMethod, bindingFlags))
return true;
return false;
}
private static bool TestAccessibility(MemberInfo member, BindingFlags bindingFlags)
{
if (member is FieldInfo)
{
return TestAccessibility((FieldInfo)member, bindingFlags);
}
else if (member is MethodBase)
{
return TestAccessibility((MethodBase)member, bindingFlags);
}
else if (member is PropertyInfo)
{
return TestAccessibility((PropertyInfo)member, bindingFlags);
}
throw new Exception("Unexpected member type.");
}
private static bool TestAccessibility(FieldInfo member, BindingFlags bindingFlags)
{
bool visibility = (member.IsPublic && bindingFlags.HasFlag(BindingFlags.Public)) ||
(!member.IsPublic && bindingFlags.HasFlag(BindingFlags.NonPublic));
bool instance = (member.IsStatic && bindingFlags.HasFlag(BindingFlags.Static)) ||
(!member.IsStatic && bindingFlags.HasFlag(BindingFlags.Instance));
return visibility && instance;
}
private static bool TestAccessibility(MethodBase member, BindingFlags bindingFlags)
{
bool visibility = (member.IsPublic && bindingFlags.HasFlag(BindingFlags.Public)) ||
(!member.IsPublic && bindingFlags.HasFlag(BindingFlags.NonPublic));
bool instance = (member.IsStatic && bindingFlags.HasFlag(BindingFlags.Static)) ||
(!member.IsStatic && bindingFlags.HasFlag(BindingFlags.Instance));
return visibility && instance;
}
public static Type[] GetGenericArguments(this Type type)
{
return type.GetTypeInfo().GenericTypeArguments;
}
public static IEnumerable<Type> GetInterfaces(this Type type)
{
return type.GetTypeInfo().ImplementedInterfaces;
}
public static IEnumerable<MethodInfo> GetMethods(this Type type)
{
return type.GetTypeInfo().DeclaredMethods;
}
public static bool IsAbstract(this Type type)
{
return type.GetTypeInfo().IsAbstract;
}
public static bool IsVisible(this Type type)
{
return type.GetTypeInfo().IsVisible;
}
public static bool IsValueType(this Type type)
{
return type.GetTypeInfo().IsValueType;
}
public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match)
{
Type current = type;
while (current != null)
{
if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal))
{
match = current;
return true;
}
current = current.BaseType();
}
foreach (Type i in type.GetInterfaces())
{
if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal))
{
match = type;
return true;
}
}
match = null;
return false;
}
public static bool AssignableToTypeName(this Type type, string fullTypeName)
{
Type match;
return type.AssignableToTypeName(fullTypeName, out match);
}
public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes)
{
var methods = type.GetMethods().Where(method => method.Name == name);
foreach (var method in methods)
{
if (method.HasParameters(parameterTypes))
return method;
}
return null;
}
public static bool HasParameters(this MethodInfo method, params Type[] parameterTypes)
{
var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray();
if (methodParameters.Length != parameterTypes.Length)
return false;
for (int i = 0; i < methodParameters.Length; i++)
if (methodParameters[i].ToString() != parameterTypes[i].ToString())
return false;
return true;
}
public static IEnumerable<Type> GetAllInterfaces(this Type target)
{
foreach (var i in target.GetInterfaces())
{
yield return i;
foreach (var ci in i.GetInterfaces())
{
yield return ci;
}
}
}
public static IEnumerable<MethodInfo> GetAllMethods(this Type target)
{
var allTypes = target.GetAllInterfaces().ToList();
allTypes.Add(target);
return from type in allTypes
from method in type.GetMethods()
select method;
}
}
}
#endif
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UseIntegralOrStringArgumentForIndexersAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UseIntegralOrStringArgumentForIndexersAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class UseIntegralOrStringArgumentForIndexersTests
{
[Fact]
public async Task TestBasicUseIntegralOrStringArgumentForIndexersWarning1Async()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class Months
Private month() As String = {""Jan"", ""Feb"", ""...""}
Default ReadOnly Property Item(index As Single) As String
Get
Return month(index)
End Get
End Property
End Class
", CreateBasicResult(6, 35));
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TestBasicUseIntegralOrStringArgumentForIndexersNoWarning_InternalAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Friend Class Months
Private month() As String = {""Jan"", ""Feb"", ""...""}
Public Default ReadOnly Property Item(index As Single) As String
Get
Return month(index)
End Get
End Property
End Class
Public Class Months2
Private month() As String = {""Jan"", ""Feb"", ""...""}
Friend Default ReadOnly Property Item(index As Single) As String
Get
Return month(index)
End Get
End Property
End Class
");
}
[Fact]
public async Task TestBasicUseIntegralOrStringArgumentForIndexersNoWarning1Async()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Months
Private month() As String = {""Jan"", ""Feb"", ""...""}
Default ReadOnly Property Item(index As String) As String
Get
Return month(index)
End Get
End Property
End Class
");
}
[Fact]
public async Task TestCSharpUseIntegralOrStringArgumentForIndexersWarning1Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Months
{
string[] month = new string[] {""Jan"", ""Feb"", ""...""};
public string this[char index]
{
get
{
return month[index];
}
}
}", CreateCSharpResult(5, 23));
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TestCSharpUseIntegralOrStringArgumentForIndexersNoWarning_InternalAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
internal class Months
{
string[] month = new string[] {""Jan"", ""Feb"", ""...""};
public string this[char index]
{
get
{
return month[index];
}
}
}
public class Months2
{
string[] month = new string[] {""Jan"", ""Feb"", ""...""};
internal string this[char index]
{
get
{
return month[index];
}
}
}");
}
[Fact]
public async Task TestCSharpUseIntegralOrStringArgumentForIndexersNoWarning1Async()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Months
{
string[] month = new string[] {""Jan"", ""Feb"", ""...""};
public string this[int index]
{
get
{
return month[index];
}
}
}");
}
[Fact]
public async Task TestCSharpGenericIndexerAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Months<T>
{
public string this[T index]
{
get
{
return null;
}
}
}");
}
[Fact]
public async Task TestBasicGenericIndexerAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Months(Of T)
Default Public ReadOnly Property Item(index As T)
Get
Return Nothing
End Get
End Property
End Class");
}
[Fact]
public async Task TestCSharpEnumIndexerAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Months<T>
{
public enum SomeEnum { }
public string this[SomeEnum index]
{
get
{
return null;
}
}
}");
}
[Fact]
public async Task TestBasicEnumIndexerAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Months(Of T)
Public Enum SomeEnum
Val1
End Enum
Default Public ReadOnly Property Item(index As SomeEnum)
Get
Return Nothing
End Get
End Property
End Class");
}
[Fact, WorkItem(3638, "https://github.com/dotnet/roslyn-analyzers/issues/3638")]
public async Task CA1043_IndexerOfTypeSystemIndex_NoDiagnosticAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp30,
TestCode = @"
public class C
{
public string this[System.Index index]
{
get => null;
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp30,
TestCode = @"
Public Class Months
Default ReadOnly Property Item(index As System.Index) As String
Get
Return Nothing
End Get
End Property
End Class",
}.RunAsync();
}
[Fact, WorkItem(3638, "https://github.com/dotnet/roslyn-analyzers/issues/3638")]
public async Task CA1043_IndexerOfTypeSystemRange_NoDiagnosticAsync()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp30,
TestCode = @"
public class C
{
public string this[System.Range range]
{
get => null;
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp30,
TestCode = @"
Public Class Months
Default ReadOnly Property Item(index As System.Range) As String
Get
Return Nothing
End Get
End Property
End Class",
}.RunAsync();
}
private static DiagnosticResult CreateCSharpResult(int line, int col)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, col);
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult CreateBasicResult(int line, int col)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, col);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace PatternsIntro.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Table;
using MS.Test.Common.MsTestLib;
namespace Commands.Storage.ScenarioTest
{
public abstract class Agent
{
/// <summary>
/// output data returned after agent operation
/// </summary>
public Collection<Dictionary<string, object>> Output { get { return _Output; } }
/// <summary>
/// error messages returned after agent operation
/// </summary>
public Collection<string> ErrorMessages { get { return _ErrorMessages; } }
public bool UseContextParam
{
set {_UseContextParam = value;}
get {return _UseContextParam;}
}
/// <summary>
/// Return true if succeed otherwise return false
/// </summary>
public abstract bool NewAzureStorageContainer(string ContainerName);
/// <summary>
/// Parameters:
/// ContainerName:
/// 1. Could be empty if no Container parameter specified
/// 2. Could contain wildcards
/// </summary>
public abstract bool GetAzureStorageContainer(string ContainerName);
public abstract bool GetAzureStorageContainerByPrefix(string Prefix);
public abstract bool SetAzureStorageContainerACL(string ContainerName, BlobContainerPublicAccessType PublicAccess, bool PassThru = true);
public abstract bool RemoveAzureStorageContainer(string ContainerName, bool Force = true);
/// <summary>
/// For pipeline, new/remove a list of container names
/// </summary>
public abstract bool NewAzureStorageContainer(string[] ContainerNames);
public abstract bool RemoveAzureStorageContainer(string[] ContainerNames, bool Force = true);
public abstract bool NewAzureStorageQueue(string QueueName);
/// <summary>
/// Parameters:
/// ContainerName:
/// 1. Could be empty if no Queue parameter specified
/// 2. Could contain wildcards
/// </summary>
public abstract bool GetAzureStorageQueue(string QueueName);
public abstract bool GetAzureStorageQueueByPrefix(string Prefix);
public abstract bool RemoveAzureStorageQueue(string QueueName, bool Force = true);
/// <summary>
/// For pipeline, new/remove a list of queue names
/// </summary>
public abstract bool NewAzureStorageQueue(string[] QueueNames);
public abstract bool RemoveAzureStorageQueue(string[] QueueNames, bool Force = true);
/// <summary>
/// Parameters:
/// Block:
/// true for BlockBlob, false for PageBlob
/// ConcurrentCount:
/// -1 means use the default value
/// </summary>
public abstract bool SetAzureStorageBlobContent(string FileName, string ContainerName, BlobType Type, string BlobName = "",
bool Force = true, int ConcurrentCount = -1, Hashtable properties = null, Hashtable metadata = null);
public abstract bool GetAzureStorageBlobContent(string Blob, string FileName, string ContainerName,
bool Force = true, int ConcurrentCount = -1);
public abstract bool GetAzureStorageBlob(string BlobName, string ContainerName);
public abstract bool GetAzureStorageBlobByPrefix(string Prefix, string ContainerName);
/// <summary>
///
/// Remarks:
/// currently there is no Force param, may add it later on
/// </summary>
public abstract bool RemoveAzureStorageBlob(string BlobName, string ContainerName, bool onlySnapshot = false, bool force = true);
public abstract bool NewAzureStorageTable(string TableName);
public abstract bool NewAzureStorageTable(string[] TableNames);
public abstract bool GetAzureStorageTable(string TableName);
public abstract bool GetAzureStorageTableByPrefix(string Prefix);
public abstract bool RemoveAzureStorageTable(string TableName, bool Force = true);
public abstract bool RemoveAzureStorageTable(string[] TableNames, bool Force = true);
public abstract bool NewAzureStorageContext(string StorageAccountName, string StorageAccountKey, string endPoint = "");
public abstract bool NewAzureStorageContext(string ConnectionString);
public abstract bool StartAzureStorageBlobCopy(string sourceUri, string destContainerName, string destBlobName, object destContext, bool force = true);
public abstract bool StartAzureStorageBlobCopy(string srcContainerName, string srcBlobName, string destContainerName, string destBlobName, object destContext = null, bool force = true);
public abstract bool StartAzureStorageBlobCopy(ICloudBlob srcBlob, string destContainerName, string destBlobName, object destContext = null, bool force = true);
public abstract bool GetAzureStorageBlobCopyState(string containerName, string blobName, bool waitForComplete);
public abstract bool GetAzureStorageBlobCopyState(ICloudBlob blob, object context, bool waitForComplete);
public abstract bool StopAzureStorageBlobCopy(string containerName, string blobName, string copyId, bool force);
/// <summary>
/// Compare the output collection data with comp
///
/// Parameters:
/// comp: comparsion data
/// </summary>
public void OutputValidation(Collection<Dictionary<string, object>> comp)
{
Test.Info("Validate Dictionary objects");
Test.Assert(comp.Count == Output.Count, "Comparison size: {0} = {1} Output size", comp.Count, Output.Count);
if (comp.Count != Output.Count)
return;
// first check whether Key exists and then check value if it's not null
for (int i = 0; i < comp.Count; ++i)
{
foreach (string str in comp[i].Keys)
{
Test.Assert(Output[i].ContainsKey(str), "{0} should be in the ouput columns", str);
switch(str)
{
case "Context":
break;
case "CloudTable":
Test.Assert(Utility.CompareEntity((CloudTable)comp[i][str], (CloudTable)Output[i][str]),
"CloudTable Column {0}: {1} = {2}", str, comp[i][str], Output[i][str]);
break;
case "CloudQueue":
Test.Assert(Utility.CompareEntity((CloudQueue)comp[i][str], (CloudQueue)Output[i][str]),
"CloudQueue Column {0}: {1} = {2}", str, comp[i][str], Output[i][str]);
break;
case "CloudBlobContainer":
Test.Assert(Utility.CompareEntity((CloudBlobContainer)comp[i][str], (CloudBlobContainer)Output[i][str]),
"CloudBlobContainer Column {0}: {1} = {2}", str, comp[i][str], Output[i][str]);
break;
case "ICloudBlob":
Test.Assert(Utility.CompareEntity((ICloudBlob)comp[i][str], (ICloudBlob)Output[i][str]),
"ICloudBlob Column {0}: {1} = {2}", str, comp[i][str], Output[i][str]);
break;
case "Permission":
Test.Assert(Utility.CompareEntity((BlobContainerPermissions)comp[i][str], (BlobContainerPermissions)Output[i][str]),
"Permission Column {0}: {1} = {2}", str, comp[i][str], Output[i][str]);
break;
default:
if(comp[i][str] == null)
{
Test.Assert(Output[i][str] == null, "Column {0}: {1} = {2}", str, comp[i][str], Output[i][str]);
}
else
{
Test.Assert(comp[i][str].Equals(Output[i][str]), "Column {0}: {1} = {2}", str, comp[i][str], Output[i][str]);
}
break;
}
}
}
}
/// <summary>
/// Compare the output collection data with containers
///
/// Parameters:
/// containers: comparsion data
/// </summary>
public void OutputValidation(IEnumerable<CloudBlobContainer> containers)
{
Test.Info("Validate CloudBlobContainer objects");
Test.Assert(containers.Count() == Output.Count, "Comparison size: {0} = {1} Output size", containers.Count(), Output.Count);
if (containers.Count() != Output.Count)
return;
int count = 0;
foreach (CloudBlobContainer container in containers)
{
container.FetchAttributes();
Test.Assert(Utility.CompareEntity(container, (CloudBlobContainer)Output[count]["CloudBlobContainer"]), "container equality checking: {0}", container.Name);
++count;
}
}
/// <summary>
/// Compare the output collection data with container permissions
/// </summary>
/// <param name="containers">a list of cloudblobcontainer objects</param>
public void OutputValidation(IEnumerable<BlobContainerPermissions> permissions)
{
Test.Info("Validate BlobContainerPermissions");
Test.Assert(permissions.Count() == Output.Count, "Comparison size: {0} = {1} Output size", permissions.Count(), Output.Count);
if (permissions.Count() != Output.Count)
return;
int count = 0;
foreach (BlobContainerPermissions permission in permissions)
{
Test.Assert(Utility.CompareEntity(permission, (BlobContainerPermissions)Output[count]["Permission"]), "container permision equality checking ");
++count;
}
}
/// <summary>
/// Compare the output collection data with ICloudBlob
/// </summary>
/// <param name="containers">a list of cloudblobcontainer objects</param>
public void OutputValidation(IEnumerable<ICloudBlob> blobs)
{
Test.Info("Validate ICloudBlob objects");
Test.Assert(blobs.Count() == Output.Count, "Comparison size: {0} = {1} Output size", blobs.Count(), Output.Count);
if (blobs.Count() != Output.Count)
return;
int count = 0;
foreach (ICloudBlob blob in blobs)
{
Test.Assert(Utility.CompareEntity(blob, (ICloudBlob)Output[count]["ICloudBlob"]), string.Format("ICloudBlob equality checking for blob '{0}'", blob.Name));
++count;
}
}
/// <summary>
/// Compare the output collection data with queues
///
/// Parameters:
/// queues: comparsion data
/// </summary>
public void OutputValidation(IEnumerable<CloudQueue> queues)
{
Test.Info("Validate CloudQueue objects");
Test.Assert(queues.Count() == Output.Count, "Comparison size: {0} = {1} Output size", queues.Count(), Output.Count);
if (queues.Count() != Output.Count)
return;
int count = 0;
foreach (CloudQueue queue in queues)
{
queue.FetchAttributes();
Test.Assert(Utility.CompareEntity(queue, (CloudQueue)Output[count]["CloudQueue"]), "queue equality checking: {0}", queue.Name);
++count;
}
}
/// <summary>
/// Compare the output collection data with tables
///
/// Parameters:
/// tables: comparsion data
/// </summary>
public void OutputValidation(IEnumerable<CloudTable> tables)
{
Test.Info("Validate CloudTable objects");
Test.Assert(tables.Count() == Output.Count, "Comparison size: {0} = {1} Output size", tables.Count(), Output.Count);
if (tables.Count() != Output.Count)
return;
int count = 0;
foreach (CloudTable table in tables)
{
Test.Assert(Utility.CompareEntity(table, (CloudTable)Output[count]["CloudTable"]), "table equality checking: {0}", table.Name);
++count;
}
}
protected static Random _random = new Random((int)(DateTime.Now.Ticks)); // for generating random object names
protected Collection<Dictionary<string, object>> _Output = new Collection<Dictionary<string, object>>();
protected Collection<string> _ErrorMessages = new Collection<string>();
protected bool _UseContextParam = true; // decide whether to specify the Context parameter
}
}
| |
using System;
using System.ComponentModel;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Sync;
using umbraco.interfaces;
namespace Umbraco.Web.Cache
{
/// <summary>
/// Represents the entry point into Umbraco's distributed cache infrastructure.
/// </summary>
/// <remarks>
/// <para>
/// The distributed cache infrastructure ensures that distributed caches are
/// invalidated properly in load balancing environments.
/// </para>
/// <para>
/// Distribute caches include static (in-memory) cache, runtime cache, front-end content cache, Examine/Lucene indexes
/// </para>
/// </remarks>
public sealed class DistributedCache
{
#region Public constants/Ids
public const string ApplicationTreeCacheRefresherId = "0AC6C028-9860-4EA4-958D-14D39F45886E";
public const string ApplicationCacheRefresherId = "B15F34A1-BC1D-4F8B-8369-3222728AB4C8";
public const string TemplateRefresherId = "DD12B6A0-14B9-46e8-8800-C154F74047C8";
public const string PageCacheRefresherId = "27AB3022-3DFA-47b6-9119-5945BC88FD66";
public const string UnpublishedPageCacheRefresherId = "55698352-DFC5-4DBE-96BD-A4A0F6F77145";
public const string MemberCacheRefresherId = "E285DF34-ACDC-4226-AE32-C0CB5CF388DA";
public const string MemberGroupCacheRefresherId = "187F236B-BD21-4C85-8A7C-29FBA3D6C00C";
public const string MediaCacheRefresherId = "B29286DD-2D40-4DDB-B325-681226589FEC";
public const string MacroCacheRefresherId = "7B1E683C-5F34-43dd-803D-9699EA1E98CA";
public const string UserCacheRefresherId = "E057AF6D-2EE6-41F4-8045-3694010F0AA6";
public const string UserPermissionsCacheRefresherId = "840AB9C5-5C0B-48DB-A77E-29FE4B80CD3A";
public const string UserTypeCacheRefresherId = "7E707E21-0195-4522-9A3C-658CC1761BD4";
public const string ContentTypeCacheRefresherId = "6902E22C-9C10-483C-91F3-66B7CAE9E2F5";
public const string LanguageCacheRefresherId = "3E0F95D8-0BE5-44B8-8394-2B8750B62654";
public const string DomainCacheRefresherId = "11290A79-4B57-4C99-AD72-7748A3CF38AF";
[Obsolete("This is no longer used and will be removed in future versions")]
[EditorBrowsable(EditorBrowsableState.Never)]
public const string StylesheetCacheRefresherId = "E0633648-0DEB-44AE-9A48-75C3A55CB670";
public const string StylesheetPropertyCacheRefresherId = "2BC7A3A4-6EB1-4FBC-BAA3-C9E7B6D36D38";
public const string DataTypeCacheRefresherId = "35B16C25-A17E-45D7-BC8F-EDAB1DCC28D2";
public const string DictionaryCacheRefresherId = "D1D7E227-F817-4816-BFE9-6C39B6152884";
public const string PublicAccessCacheRefresherId = "1DB08769-B104-4F8B-850E-169CAC1DF2EC";
public static readonly Guid ApplicationTreeCacheRefresherGuid = new Guid(ApplicationTreeCacheRefresherId);
public static readonly Guid ApplicationCacheRefresherGuid = new Guid(ApplicationCacheRefresherId);
public static readonly Guid TemplateRefresherGuid = new Guid(TemplateRefresherId);
public static readonly Guid PageCacheRefresherGuid = new Guid(PageCacheRefresherId);
public static readonly Guid UnpublishedPageCacheRefresherGuid = new Guid(UnpublishedPageCacheRefresherId);
public static readonly Guid MemberCacheRefresherGuid = new Guid(MemberCacheRefresherId);
public static readonly Guid MemberGroupCacheRefresherGuid = new Guid(MemberGroupCacheRefresherId);
public static readonly Guid MediaCacheRefresherGuid = new Guid(MediaCacheRefresherId);
public static readonly Guid MacroCacheRefresherGuid = new Guid(MacroCacheRefresherId);
public static readonly Guid UserCacheRefresherGuid = new Guid(UserCacheRefresherId);
public static readonly Guid UserPermissionsCacheRefresherGuid = new Guid(UserPermissionsCacheRefresherId);
public static readonly Guid UserTypeCacheRefresherGuid = new Guid(UserTypeCacheRefresherId);
public static readonly Guid ContentTypeCacheRefresherGuid = new Guid(ContentTypeCacheRefresherId);
public static readonly Guid LanguageCacheRefresherGuid = new Guid(LanguageCacheRefresherId);
public static readonly Guid DomainCacheRefresherGuid = new Guid(DomainCacheRefresherId);
public static readonly Guid StylesheetCacheRefresherGuid = new Guid(StylesheetCacheRefresherId);
public static readonly Guid StylesheetPropertyCacheRefresherGuid = new Guid(StylesheetPropertyCacheRefresherId);
public static readonly Guid DataTypeCacheRefresherGuid = new Guid(DataTypeCacheRefresherId);
public static readonly Guid DictionaryCacheRefresherGuid = new Guid(DictionaryCacheRefresherId);
public static readonly Guid PublicAccessCacheRefresherGuid = new Guid(PublicAccessCacheRefresherId);
#endregion
#region Constructor & Singleton
// note - should inject into the application instead of using a singleton
private static readonly DistributedCache InstanceObject = new DistributedCache();
/// <summary>
/// Initializes a new instance of the <see cref="DistributedCache"/> class.
/// </summary>
private DistributedCache()
{ }
/// <summary>
/// Gets the static unique instance of the <see cref="DistributedCache"/> class.
/// </summary>
/// <returns>The static unique instance of the <see cref="DistributedCache"/> class.</returns>
/// <remarks>Exists so that extension methods can be added to the distributed cache.</remarks>
public static DistributedCache Instance
{
get
{
return InstanceObject;
}
}
#endregion
#region Core notification methods
/// <summary>
/// Notifies the distributed cache of specifieds item invalidation, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <typeparam name="T">The type of the invalidated items.</typeparam>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="getNumericId">A function returning the unique identifier of items.</param>
/// <param name="instances">The invalidated items.</param>
/// <remarks>
/// This method is much better for performance because it does not need to re-lookup object instances.
/// </remarks>
public void Refresh<T>(Guid factoryGuid, Func<T, int> getNumericId, params T[] instances)
{
if (factoryGuid == Guid.Empty || instances.Length == 0 || getNumericId == null) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
getNumericId,
instances);
}
/// <summary>
/// Notifies the distributed cache of a specified item invalidation, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="id">The unique identifier of the invalidated item.</param>
public void Refresh(Guid factoryGuid, int id)
{
if (factoryGuid == Guid.Empty || id == default(int)) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
id);
}
/// <summary>
/// Notifies the distributed cache of a specified item invalidation, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="id">The unique identifier of the invalidated item.</param>
public void Refresh(Guid factoryGuid, Guid id)
{
if (factoryGuid == Guid.Empty || id == Guid.Empty) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
id);
}
public void RefreshByPayload(Guid factoryGuid, object payload)
{
if (factoryGuid == Guid.Empty || payload == null) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
payload);
}
/// <summary>
/// Notifies the distributed cache, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="jsonPayload">The notification content.</param>
public void RefreshByJson(Guid factoryGuid, string jsonPayload)
{
if (factoryGuid == Guid.Empty || jsonPayload.IsNullOrWhiteSpace()) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
jsonPayload);
}
///// <summary>
///// Notifies the distributed cache, for a specified <see cref="ICacheRefresher"/>.
///// </summary>
///// <param name="refresherId">The unique identifier of the ICacheRefresher.</param>
///// <param name="payload">The notification content.</param>
//internal void Notify(Guid refresherId, object payload)
//{
// if (refresherId == Guid.Empty || payload == null) return;
// ServerMessengerResolver.Current.Messenger.Notify(
// ServerRegistrarResolver.Current.Registrar.Registrations,
// GetRefresherById(refresherId),
// json);
//}
/// <summary>
/// Notifies the distributed cache of a global invalidation for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
public void RefreshAll(Guid factoryGuid)
{
if (factoryGuid == Guid.Empty) return;
ServerMessengerResolver.Current.Messenger.PerformRefreshAll(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid));
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is no longer in use and does not work as advertised, the allServers parameter doesnt have any affect for database server messengers, do not use!")]
public void RefreshAll(Guid factoryGuid, bool allServers)
{
if (factoryGuid == Guid.Empty) return;
if (allServers)
{
RefreshAll(factoryGuid);
}
else
{
ServerMessengerResolver.Current.Messenger.PerformRefreshAll(
Enumerable.Empty<IServerAddress>(),
GetRefresherById(factoryGuid));
}
}
/// <summary>
/// Notifies the distributed cache of a specified item removal, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="id">The unique identifier of the removed item.</param>
public void Remove(Guid factoryGuid, int id)
{
if (factoryGuid == Guid.Empty || id == default(int)) return;
ServerMessengerResolver.Current.Messenger.PerformRemove(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
id);
}
/// <summary>
/// Notifies the distributed cache of specifieds item removal, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <typeparam name="T">The type of the removed items.</typeparam>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="getNumericId">A function returning the unique identifier of items.</param>
/// <param name="instances">The removed items.</param>
/// <remarks>
/// This method is much better for performance because it does not need to re-lookup object instances.
/// </remarks>
public void Remove<T>(Guid factoryGuid, Func<T, int> getNumericId, params T[] instances)
{
ServerMessengerResolver.Current.Messenger.PerformRemove(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
getNumericId,
instances);
}
#endregion
// helper method to get an ICacheRefresher by its unique identifier
private static ICacheRefresher GetRefresherById(Guid uniqueIdentifier)
{
return CacheRefreshersResolver.Current.GetById(uniqueIdentifier);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Xml.Tests
{
public class DateTimeOffsetTests
{
[Fact]
public static void ReadContentAsDateTimeOffset1()
{
var reader = Utils.CreateFragmentReader("<Root> <![CDATA[0]]>001Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset10()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[9]]>999Z</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(9999, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset11()
{
var reader = Utils.CreateFragmentReader("<Root> 2000-0<![CDATA[2]]>-29T23:59:59.999<?a?>9999 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2000, 2, 29, 23, 59, 59, DateTimeKind.Local).AddTicks(9999999)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset12()
{
var reader = Utils.CreateFragmentReader("<Root> 2<?a?>00<!-- Comment inbetween-->0-02-29T23:59:5<?a?>9-13:<![CDATA[60]]> </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(2000, 2, 29, 23, 59, 59, new TimeSpan(-14, 0, 0)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset13()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[9]]>999Z</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(9999, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset14()
{
var reader = Utils.CreateFragmentReader("<Root> 20<?a?>02-1<![CDATA[2]]>-3<!-- Comment inbetween-->0 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2002, 12, 30, 0, 0, 0, DateTimeKind.Local)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset15()
{
var reader = Utils.CreateFragmentReader("<Root> <![CDATA[2]]>00<?a?>2-1<!-- Comment inbetween-->2-30Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2002, 12, 30, 0, 0, 0, 0, DateTimeKind.Utc)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset16()
{
var reader = Utils.CreateFragmentReader("<Root> <!-- Comment inbetween-->0002-01-01T00:00:00+00:00 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2, 1, 1, 0, 0, 0, DateTimeKind.Utc)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset17()
{
var reader = Utils.CreateFragmentReader("<Root>99<!-- Comment inbetween-->99-1<?a?>2-31T1<![CDATA[2]]>:59:59</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(9999, 12, 31, 12, 59, 59, DateTimeKind.Local)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset18()
{
var reader = Utils.CreateFragmentReader("<Root> 999<!-- Comment inbetween-->9 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(9999, 1, 1, 0, 0, 0, DateTimeKind.Local)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset19()
{
var reader = Utils.CreateFragmentReader("<Root>001-01-01T00:00:00+00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset2()
{
var reader = Utils.CreateFragmentReader("<Root> 2000-0<![CDATA[2]]>-29T23:59:59.999<?a?>9999 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2000, 2, 29, 23, 59, 59, DateTimeKind.Local).AddTicks(9999999)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset20()
{
var reader = Utils.CreateFragmentReader("<Root>99<?a?>99-12-31T12:59:59+14:00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset21()
{
var reader = Utils.CreateFragmentReader("<Root>0<?a?></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset22()
{
var reader = Utils.CreateFragmentReader("<Root> 9<?a?>999 Z</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset23()
{
var reader = Utils.CreateFragmentReader("<Root> ABC<?a?>D </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset24()
{
var reader = Utils.CreateFragmentReader("<Root>yyy<?a?>y-MM-ddTHH:mm</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset25()
{
var reader = Utils.CreateFragmentReader("<Root>21<?a?>00-02-29T23:59:59.9999999+13:60 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset26()
{
var reader = Utils.CreateFragmentReader("<Root>3 000-0<?a?>2-29T23:59:59.999999999999-13:60</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset27()
{
var reader = Utils.CreateFragmentReader("<Root> 200<?a?>2-12-33</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset28()
{
var reader = Utils.CreateFragmentReader("<Root>20<?a?>0<![CDATA[2<?a?>]]>-13-30 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset29()
{
var reader = Utils.CreateFragmentReader("<Root> 001-01-01<?a?>T00:00:00+00:00 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset3()
{
var reader = Utils.CreateFragmentReader("<Root> 2<?a?>00<!-- Comment inbetween-->0-02-29T23:59:5<?a?>9-13:<![CDATA[60]]> </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(2000, 2, 29, 23, 59, 59, new TimeSpan(-14, 0, 0)), (DateTimeOffset)reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset30()
{
var reader = Utils.CreateFragmentReader("<Root>9999-1<![CDATA[2]]>-31T12:59:59+14:00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset31()
{
var reader = Utils.CreateFragmentReader("<Root><?a?>0<!-- Comment inbetween--></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset32()
{
var reader = Utils.CreateFragmentReader("<Root> 9<?a?>9<!-- Comment inbetween-->99 Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset33()
{
var reader = Utils.CreateFragmentReader("<Root>A<?a?>B<!-- Comment inbetween-->CD</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset34()
{
var reader = Utils.CreateFragmentReader("<Root>yyyy-MM-ddTHH:mm</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset35()
{
var reader = Utils.CreateFragmentReader("<Root> 21<?a?>00<!-- Comment inbetween-->-02-29T23:59:59.9999999+13:60 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset36()
{
var reader = Utils.CreateFragmentReader("<Root>3000-<?a?>02-29T<!-- Comment inbetween-->23:59:59.999999999999-13:60</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset37()
{
var reader = Utils.CreateFragmentReader("<Root>2002-12-33</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset38()
{
var reader = Utils.CreateFragmentReader("<Root >2002-13-30 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset39()
{
var reader = Utils.CreateFragmentReader("<Root> 200<!-- Comment inbetween-->2-<![CDATA[12]]>-3<?a?>0Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(2002, 12, 30, 0, 0, 0, TimeSpan.FromHours(0)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset4()
{
var reader = Utils.CreateFragmentReader("<Root> 20<?a?>02-1<![CDATA[2]]>-3<!-- Comment inbetween-->0 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2002, 12, 30, 0, 0, 0, DateTimeKind.Local)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset40()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[00]]>01-01-01<?a?>T00:00:0<!-- Comment inbetween-->0+00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(1, 1, 1, 0, 0, 0, TimeSpan.FromHours(0)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset41()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[9]]>99<?a?>9-12-31T12:<!-- Comment inbetween-->5<![CDATA[9]]>:5<![CDATA[9]]>+14:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(9999, 12, 31, 12, 59, 59, TimeSpan.FromHours(+14)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset42()
{
var reader = Utils.CreateFragmentReader("<Root> 9<![CDATA[9]]>99-1<?a?>2-31T1<!-- Comment inbetween-->2:59:59-10:60 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(9999, 12, 31, 12, 59, 59, TimeSpan.FromHours(-11)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset43()
{
var reader = Utils.CreateFragmentReader("<Root> 20<!-- Comment inbetween-->05 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(2005, 1, 1, 0, 0, 0, TimeZoneInfo.Local.GetUtcOffset(new DateTime(2005, 1, 1))).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset44()
{
var reader = Utils.CreateFragmentReader("<Root> 9<![CDATA[9]]>9<!-- Comment inbetween-->9<?a?> </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(9999, 1, 1, 0, 0, 0, TimeZoneInfo.Local.GetUtcOffset(new DateTime(9999, 1, 1))).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset45()
{
var reader = Utils.CreateFragmentReader("<Root> 0<?a?>0<!-- Comment inbetween-->01Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(1, 1, 1, 0, 0, 0, TimeSpan.FromHours(0)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset46()
{
var reader = Utils.CreateFragmentReader("<Root>99<!-- Comment inbetween-->9<![CDATA[9]]>Z<?a?></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(9999, 1, 1, 0, 0, 0, TimeSpan.FromHours(0)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset47()
{
var reader = Utils.CreateFragmentReader("<Root>2<!-- Comment inbetween-->000-02-29T23:5<?a?>9:5<![CDATA[9]]>.999999<![CDATA[9]]>+13:60 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(2000, 2, 29, 23, 59, 59, TimeSpan.FromHours(14)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset48()
{
var reader = Utils.CreateFragmentReader("<Root> 20<?a?>00-02-29T23:59:59.999999999999-<!-- Comment inbetween-->13:60</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(2000, 3, 1, 0, 0, 0, TimeSpan.FromHours(-14)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset49()
{
var reader = Utils.CreateFragmentReader("<Root> 0001-01-01T00<?a?>:00:00<!-- Comment inbetween-->-1<!-- Comment inbetween-->3:<![CDATA[60]]> </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(1, 1, 1, 0, 0, 0, TimeSpan.FromHours(-14)).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset5()
{
var reader = Utils.CreateFragmentReader("<Root> <![CDATA[2]]>00<?a?>2-1<!-- Comment inbetween-->2-30Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2002, 12, 30, 0, 0, 0, 0, DateTimeKind.Utc)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset50()
{
var reader = Utils.CreateFragmentReader("<Root>2<?a?>00<!-- Comment inbetween-->2-12-3<![CDATA[0]]></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(2002, 12, 30, 0, 0, 0, TimeZoneInfo.Local.GetUtcOffset(new DateTime(2002, 12, 30))).ToString(), reader.ReadContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadContentAsDateTimeOffset51()
{
var reader = Utils.CreateFragmentReader("<Root> 20<?9?>02-1<![CDATA[2]]>-3<!-- Comment inbetween-->0 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset52()
{
var reader = Utils.CreateFragmentReader("<Root>9999-12-31T12:5<?a?>9:59+14:00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset53()
{
var reader = Utils.CreateFragmentReader("<Root>0<?a?></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset54()
{
var reader = Utils.CreateFragmentReader("<Root>99<?a?>9Z</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset55()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[z<!-- Comment inbetween-->]]></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset56()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[Z<!-- Comment inbetween-->]]></Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset57()
{
var reader = Utils.CreateFragmentReader("<Root>21<!-- Comment inbetween-->00-02-29T23:59:59.9999999+13:60</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset58()
{
var reader = Utils.CreateFragmentReader("<Root>3000-02-29T23:59:<!-- Comment inbetween-->9.999999999999-13:60</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset59()
{
var reader = Utils.CreateFragmentReader("<Root>001-01-01T0<?a?>0:00:00<!-- Comment inbetween-->+00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset6()
{
var reader = Utils.CreateFragmentReader("<Root> <!-- Comment inbetween-->0002-01-01T00:00:00+00:00 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(2, 1, 1, 0, 0, 0, DateTimeKind.Utc)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset60()
{
var reader = Utils.CreateFragmentReader("<Root>0001-<![CDATA[0<!-- Comment inbetween-->1]]>-01T0<?a?>0:00:00</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadContentAsDateTimeOffset7()
{
var reader = Utils.CreateFragmentReader("<Root>99<!-- Comment inbetween-->99-1<?a?>2-31T1<![CDATA[2]]>:59:59</Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(9999, 12, 31, 12, 59, 59, DateTimeKind.Local)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset8()
{
var reader = Utils.CreateFragmentReader("<Root> 999<!-- Comment inbetween-->9 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(9999, 1, 1, 0, 0, 0, DateTimeKind.Local)), reader.ReadContentAsDateTimeOffset());
}
[Fact]
public static void ReadContentAsDateTimeOffset9()
{
var reader = Utils.CreateFragmentReader("<Root> <![CDATA[0]]>001Z </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Equal(new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)), reader.ReadContentAsDateTimeOffset());
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Threading;
namespace Rainbow.Framework.Scheduler
{
//Author: Federico Dal Maso
//e-mail: ifof@libero.it
//date: 2003-06-17
/// <summary>
/// SimpleScheduler, perform a select every call to Scheduler
/// Usefull only for long period timer.
/// </summary>
public class SimpleScheduler : IScheduler
{
/// <summary>
///
/// </summary>
protected class TimerState
{
private int counter;
/// <summary>
///
/// </summary>
public int Counter
{
get { return counter; }
set { counter = value; }
}
// = 0;
private Timer timer;
/// <summary>
///
/// </summary>
public Timer Timer
{
get { return timer; }
set { timer = value; }
}
}
/// <summary>
///
/// </summary>
private static volatile SimpleScheduler _theScheduler = null;
/// <summary>
///
/// </summary>
internal SchedulerDB localSchDB;
/// <summary>
///
/// </summary>
protected TimerState localTimerState;
/// <summary>
///
/// </summary>
protected long localPeriod;
/// <summary>
///
/// </summary>
/// <param name="applicationMapPath"></param>
/// <param name="connection"></param>
/// <param name="period"></param>
protected SimpleScheduler(string applicationMapPath, IDbConnection connection, long period)
{
localSchDB = new SchedulerDB(connection, applicationMapPath);
localPeriod = period;
localTimerState = new TimerState();
Timer t = new Timer(
new TimerCallback(Schedule),
localTimerState,
Timeout.Infinite,
Timeout.Infinite);
localTimerState.Timer = t;
}
/// <summary>
///
/// </summary>
/// <param name="applicationMapPath"></param>
/// <param name="connection"></param>
/// <param name="period"></param>
/// <returns></returns>
public static SimpleScheduler GetScheduler(string applicationMapPath, IDbConnection connection, long period)
{
//Sigleton
if (_theScheduler == null)
{
lock (typeof (CachedScheduler))
{
if (_theScheduler == null)
_theScheduler = new SimpleScheduler(applicationMapPath, connection, period);
}
}
return _theScheduler;
}
/// <summary>
///
/// </summary>
/// <param name="timerState"></param>
protected virtual void Schedule(object timerState)
{
lock (this)
{
localTimerState.Counter++;
SchedulerTask[] tsks = localSchDB.GetExpiredTask();
Stop(); //Stop the timer while it works
foreach (SchedulerTask tsk in tsks)
{
try
{
ExecuteTask(tsk);
}
catch
{
//TODO: We have to apply some policy here...
//i.e. Move failed tasks on a log, call a Module feedback interface,....
//now task is removed always
}
RemoveTask(tsk);
}
Start(); //restart the timer
}
}
/// <summary>
/// Start the scheduler timer
/// </summary>
public virtual void Start()
{
localTimerState.Timer.Change(localPeriod, localPeriod);
}
/// <summary>
/// Stop the scheduler timer
/// </summary>
public virtual void Stop()
{
localTimerState.Timer.Change(Timeout.Infinite, Timeout.Infinite);
}
/// <summary>
/// Get or set the timer period.
/// </summary>
public virtual long Period
{
get { return localPeriod; }
set
{
localPeriod = value;
localTimerState.Timer.Change(0L, localPeriod);
}
}
/// <summary>
/// Get an array of tasks of the specified module owner
/// </summary>
/// <param name="idModuleOwner"></param>
/// <returns></returns>
public virtual SchedulerTask[] GetTasksByOwner(int idModuleOwner)
{
IDataReader dr = localSchDB.GetTasksByOwner(idModuleOwner);
ArrayList ary = new ArrayList();
while (dr.Read())
ary.Add(new SchedulerTask(dr));
dr.Close();
return (SchedulerTask[]) ary.ToArray(typeof (SchedulerTask));
}
/// <summary>
/// Get an array of tasks of the specified module target
/// </summary>
/// <param name="idModuleTarget"></param>
/// <returns></returns>
public virtual SchedulerTask[] GetTasksByTarget(int idModuleTarget)
{
IDataReader dr = localSchDB.GetTasksByOwner(idModuleTarget);
ArrayList ary = new ArrayList();
while (dr.Read())
ary.Add(new SchedulerTask(dr));
dr.Close();
return (SchedulerTask[]) ary.ToArray(typeof (SchedulerTask));
}
/// <summary>
/// Insert a new task
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
public virtual SchedulerTask InsertTask(SchedulerTask task)
{
if (task.IDTask != -1)
throw new SchedulerException("Could not insert an inserted task");
task.SetIDTask(localSchDB.InsertTask(task));
return task;
}
/// <summary>
/// Remove a task
/// </summary>
/// <param name="task"></param>
public virtual void RemoveTask(SchedulerTask task)
{
if (task.IDTask == -1)
return;
localSchDB.RemoveTask(task.IDTask);
return;
}
/// <summary>
/// Call the correct ISchedulable methods of a target module assigned to the task.
/// </summary>
/// <param name="task"></param>
protected void ExecuteTask(SchedulerTask task)
{
ISchedulable module;
try
{
module = localSchDB.GetModuleInstance(task.IDModuleTarget);
}
catch
{
//TODO:
return;
}
try
{
module.ScheduleDo(task);
}
catch (Exception ex)
{
try
{
module.ScheduleRollback(task);
}
catch (Exception ex2)
{
throw new SchedulerException("ScheduleDo fail. Rollback fails", ex2);
}
throw new SchedulerException("ScheduleDo fails. Rollback called successfully", ex);
}
try
{
module.ScheduleCommit(task);
}
catch (Exception ex)
{
throw new SchedulerException("ScheduleDo called successfully. Commit fails", ex);
}
}
}
}
| |
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 Provisioning.Extensibility.Providers
{
/// <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
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Threading
{
//
// AsyncLocal<T> represents "ambient" data that is local to a given asynchronous control flow, such as an
// async method. For example, say you want to associate a culture with a given async flow:
//
// static AsyncLocal<Culture> s_currentCulture = new AsyncLocal<Culture>();
//
// static async Task SomeOperationAsync(Culture culture)
// {
// s_currentCulture.Value = culture;
//
// await FooAsync();
// }
//
// static async Task FooAsync()
// {
// PrintStringWithCulture(s_currentCulture.Value);
// }
//
// AsyncLocal<T> also provides optional notifications when the value associated with the current thread
// changes, either because it was explicitly changed by setting the Value property, or implicitly changed
// when the thread encountered an "await" or other context transition. For example, we might want our
// current culture to be communicated to the OS as well:
//
// static AsyncLocal<Culture> s_currentCulture = new AsyncLocal<Culture>(
// args =>
// {
// NativeMethods.SetThreadCulture(args.CurrentValue.LCID);
// });
//
public sealed class AsyncLocal<T> : IAsyncLocal
{
private readonly Action<AsyncLocalValueChangedArgs<T>>? m_valueChangedHandler;
//
// Constructs an AsyncLocal<T> that does not receive change notifications.
//
public AsyncLocal()
{
}
//
// Constructs an AsyncLocal<T> with a delegate that is called whenever the current value changes
// on any thread.
//
public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>>? valueChangedHandler)
{
m_valueChangedHandler = valueChangedHandler;
}
[MaybeNull]
public T Value
{
get
{
object? obj = ExecutionContext.GetLocalValue(this);
return (obj == null) ? default : (T)obj;
}
set
{
ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null);
}
}
void IAsyncLocal.OnValueChanged(object? previousValueObj, object? currentValueObj, bool contextChanged)
{
Debug.Assert(m_valueChangedHandler != null);
T previousValue = previousValueObj == null ? default! : (T)previousValueObj;
T currentValue = currentValueObj == null ? default! : (T)currentValueObj;
m_valueChangedHandler(new AsyncLocalValueChangedArgs<T>(previousValue, currentValue, contextChanged));
}
}
//
// Interface to allow non-generic code in ExecutionContext to call into the generic AsyncLocal<T> type.
//
internal interface IAsyncLocal
{
void OnValueChanged(object? previousValue, object? currentValue, bool contextChanged);
}
public readonly struct AsyncLocalValueChangedArgs<T>
{
[MaybeNull] public T PreviousValue { get; }
[MaybeNull] public T CurrentValue { get; }
//
// If the value changed because we changed to a different ExecutionContext, this is true. If it changed
// because someone set the Value property, this is false.
//
public bool ThreadContextChanged { get; }
internal AsyncLocalValueChangedArgs([AllowNull] T previousValue, [AllowNull] T currentValue, bool contextChanged)
{
PreviousValue = previousValue;
CurrentValue = currentValue;
ThreadContextChanged = contextChanged;
}
}
//
// Interface used to store an IAsyncLocal => object mapping in ExecutionContext.
// Implementations are specialized based on the number of elements in the immutable
// map in order to minimize memory consumption and look-up times.
//
internal interface IAsyncLocalValueMap
{
bool TryGetValue(IAsyncLocal key, out object? value);
IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent);
}
//
// Utility functions for getting/creating instances of IAsyncLocalValueMap
//
internal static class AsyncLocalValueMap
{
public static IAsyncLocalValueMap Empty { get; } = new EmptyAsyncLocalValueMap();
public static bool IsEmpty(IAsyncLocalValueMap asyncLocalValueMap)
{
Debug.Assert(asyncLocalValueMap != null);
Debug.Assert(asyncLocalValueMap == Empty || asyncLocalValueMap.GetType() != typeof(EmptyAsyncLocalValueMap));
return asyncLocalValueMap == Empty;
}
public static IAsyncLocalValueMap Create(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent)
{
// If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map
// to store the key/value pair. Otherwise, use the empty map.
return value != null || !treatNullValueAsNonexistent ?
new OneElementAsyncLocalValueMap(key, value) :
Empty;
}
// Instance without any key/value pairs. Used as a singleton/
private sealed class EmptyAsyncLocalValueMap : IAsyncLocalValueMap
{
public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent)
{
// If the value isn't null or a null value may not be treated as nonexistent, then create a new one-element map
// to store the key/value pair. Otherwise, use the empty map.
return value != null || !treatNullValueAsNonexistent ?
new OneElementAsyncLocalValueMap(key, value) :
(IAsyncLocalValueMap)this;
}
public bool TryGetValue(IAsyncLocal key, out object? value)
{
value = null;
return false;
}
}
// Instance with one key/value pair.
private sealed class OneElementAsyncLocalValueMap : IAsyncLocalValueMap
{
private readonly IAsyncLocal _key1;
private readonly object? _value1;
public OneElementAsyncLocalValueMap(IAsyncLocal key, object? value)
{
_key1 = key; _value1 = value;
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent)
{
if (value != null || !treatNullValueAsNonexistent)
{
// If the key matches one already contained in this map, then create a new one-element map with the updated
// value, otherwise create a two-element map with the additional key/value.
return ReferenceEquals(key, _key1) ?
new OneElementAsyncLocalValueMap(key, value) :
(IAsyncLocalValueMap)new TwoElementAsyncLocalValueMap(_key1, _value1, key, value);
}
else
{
// If the key exists in this map, remove it by downgrading to an empty map. Otherwise, there's nothing to
// add or remove, so just return this map.
return ReferenceEquals(key, _key1) ?
Empty :
(IAsyncLocalValueMap)this;
}
}
public bool TryGetValue(IAsyncLocal key, out object? value)
{
if (ReferenceEquals(key, _key1))
{
value = _value1;
return true;
}
else
{
value = null;
return false;
}
}
}
// Instance with two key/value pairs.
private sealed class TwoElementAsyncLocalValueMap : IAsyncLocalValueMap
{
private readonly IAsyncLocal _key1, _key2;
private readonly object? _value1, _value2;
public TwoElementAsyncLocalValueMap(IAsyncLocal key1, object? value1, IAsyncLocal key2, object? value2)
{
_key1 = key1; _value1 = value1;
_key2 = key2; _value2 = value2;
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent)
{
if (value != null || !treatNullValueAsNonexistent)
{
// If the key matches one already contained in this map, then create a new two-element map with the updated
// value, otherwise create a three-element map with the additional key/value.
return
ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(key, value, _key2, _value2) :
ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, key, value) :
(IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
}
else
{
// If the key exists in this map, remove it by downgrading to a one-element map without the key. Otherwise,
// there's nothing to add or remove, so just return this map.
return
ReferenceEquals(key, _key1) ? new OneElementAsyncLocalValueMap(_key2, _value2) :
ReferenceEquals(key, _key2) ? new OneElementAsyncLocalValueMap(_key1, _value1) :
(IAsyncLocalValueMap)this;
}
}
public bool TryGetValue(IAsyncLocal key, out object? value)
{
if (ReferenceEquals(key, _key1))
{
value = _value1;
return true;
}
else if (ReferenceEquals(key, _key2))
{
value = _value2;
return true;
}
else
{
value = null;
return false;
}
}
}
// Instance with three key/value pairs.
private sealed class ThreeElementAsyncLocalValueMap : IAsyncLocalValueMap
{
private readonly IAsyncLocal _key1, _key2, _key3;
private readonly object? _value1, _value2, _value3;
public ThreeElementAsyncLocalValueMap(IAsyncLocal key1, object? value1, IAsyncLocal key2, object? value2, IAsyncLocal key3, object? value3)
{
_key1 = key1; _value1 = value1;
_key2 = key2; _value2 = value2;
_key3 = key3; _value3 = value3;
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent)
{
if (value != null || !treatNullValueAsNonexistent)
{
// If the key matches one already contained in this map, then create a new three-element map with the
// updated value.
if (ReferenceEquals(key, _key1)) return new ThreeElementAsyncLocalValueMap(key, value, _key2, _value2, _key3, _value3);
if (ReferenceEquals(key, _key2)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, key, value, _key3, _value3);
if (ReferenceEquals(key, _key3)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
// The key doesn't exist in this map, so upgrade to a multi map that contains
// the additional key/value pair.
var multi = new MultiElementAsyncLocalValueMap(4);
multi.UnsafeStore(0, _key1, _value1);
multi.UnsafeStore(1, _key2, _value2);
multi.UnsafeStore(2, _key3, _value3);
multi.UnsafeStore(3, key, value);
return multi;
}
else
{
// If the key exists in this map, remove it by downgrading to a two-element map without the key. Otherwise,
// there's nothing to add or remove, so just return this map.
return
ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(_key2, _value2, _key3, _value3) :
ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key3, _value3) :
ReferenceEquals(key, _key3) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key2, _value2) :
(IAsyncLocalValueMap)this;
}
}
public bool TryGetValue(IAsyncLocal key, out object? value)
{
if (ReferenceEquals(key, _key1))
{
value = _value1;
return true;
}
else if (ReferenceEquals(key, _key2))
{
value = _value2;
return true;
}
else if (ReferenceEquals(key, _key3))
{
value = _value3;
return true;
}
else
{
value = null;
return false;
}
}
}
// Instance with up to 16 key/value pairs.
private sealed class MultiElementAsyncLocalValueMap : IAsyncLocalValueMap
{
internal const int MaxMultiElements = 16;
private readonly KeyValuePair<IAsyncLocal, object?>[] _keyValues;
internal MultiElementAsyncLocalValueMap(int count)
{
Debug.Assert(count <= MaxMultiElements);
_keyValues = new KeyValuePair<IAsyncLocal, object?>[count];
}
internal void UnsafeStore(int index, IAsyncLocal key, object? value)
{
Debug.Assert(index < _keyValues.Length);
_keyValues[index] = new KeyValuePair<IAsyncLocal, object?>(key, value);
}
public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent)
{
// Find the key in this map.
for (int i = 0; i < _keyValues.Length; i++)
{
if (ReferenceEquals(key, _keyValues[i].Key))
{
// The key is in the map.
if (value != null || !treatNullValueAsNonexistent)
{
// Create a new map of the same size that has all of the same pairs, with this new key/value pair
// overwriting the old.
var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length);
Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
multi._keyValues[i] = new KeyValuePair<IAsyncLocal, object?>(key, value);
return multi;
}
else if (_keyValues.Length == 4)
{
// We only have four elements, one of which we're removing, so downgrade to a three-element map,
// without the matching element.
return
i == 0 ? new ThreeElementAsyncLocalValueMap(_keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
i == 1 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
i == 2 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[3].Key, _keyValues[3].Value) :
(IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value);
}
else
{
// We have enough elements remaining to warrant a multi map. Create a new one and copy all of the
// elements from this one, except the one to be removed.
var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length - 1);
if (i != 0) Array.Copy(_keyValues, 0, multi._keyValues, 0, i);
if (i != _keyValues.Length - 1) Array.Copy(_keyValues, i + 1, multi._keyValues, i, _keyValues.Length - i - 1);
return multi;
}
}
}
// The key does not already exist in this map.
if (value == null && treatNullValueAsNonexistent)
{
// We can simply return this same map, as there's nothing to add or remove.
return this;
}
// We need to create a new map that has the additional key/value pair.
// If with the addition we can still fit in a multi map, create one.
if (_keyValues.Length < MaxMultiElements)
{
var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length + 1);
Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
multi._keyValues[_keyValues.Length] = new KeyValuePair<IAsyncLocal, object?>(key, value);
return multi;
}
// Otherwise, upgrade to a many map.
var many = new ManyElementAsyncLocalValueMap(MaxMultiElements + 1);
foreach (KeyValuePair<IAsyncLocal, object?> pair in _keyValues)
{
many[pair.Key] = pair.Value;
}
many[key] = value;
return many;
}
public bool TryGetValue(IAsyncLocal key, out object? value)
{
foreach (KeyValuePair<IAsyncLocal, object?> pair in _keyValues)
{
if (ReferenceEquals(key, pair.Key))
{
value = pair.Value;
return true;
}
}
value = null;
return false;
}
}
// Instance with any number of key/value pairs.
private sealed class ManyElementAsyncLocalValueMap : Dictionary<IAsyncLocal, object?>, IAsyncLocalValueMap
{
public ManyElementAsyncLocalValueMap(int capacity) : base(capacity) { }
public IAsyncLocalValueMap Set(IAsyncLocal key, object? value, bool treatNullValueAsNonexistent)
{
int count = Count;
bool containsKey = ContainsKey(key);
// If the value being set exists, create a new many map, copy all of the elements from this one,
// and then store the new key/value pair into it. This is the most common case.
if (value != null || !treatNullValueAsNonexistent)
{
var map = new ManyElementAsyncLocalValueMap(count + (containsKey ? 0 : 1));
foreach (KeyValuePair<IAsyncLocal, object?> pair in this)
{
map[pair.Key] = pair.Value;
}
map[key] = value;
return map;
}
// Otherwise, the value is null and a null value may be treated as nonexistent. We can downgrade to a smaller
// map rather than storing null.
// If the key is contained in this map, we're going to create a new map that's one pair smaller.
if (containsKey)
{
// If the new count would be within range of a multi map instead of a many map,
// downgrade to the multi map, which uses less memory and is faster to access.
// Otherwise, just create a new many map that's missing this key.
if (count == MultiElementAsyncLocalValueMap.MaxMultiElements + 1)
{
var multi = new MultiElementAsyncLocalValueMap(MultiElementAsyncLocalValueMap.MaxMultiElements);
int index = 0;
foreach (KeyValuePair<IAsyncLocal, object?> pair in this)
{
if (!ReferenceEquals(key, pair.Key))
{
multi.UnsafeStore(index++, pair.Key, pair.Value);
}
}
Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
return multi;
}
else
{
var map = new ManyElementAsyncLocalValueMap(count - 1);
foreach (KeyValuePair<IAsyncLocal, object?> pair in this)
{
if (!ReferenceEquals(key, pair.Key))
{
map[pair.Key] = pair.Value;
}
}
Debug.Assert(map.Count == count - 1);
return map;
}
}
// We were storing null and a null value may be treated as nonexistent, but the key wasn't in the map, so
// there's nothing to change. Just return this instance.
return this;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Threading;
using Internal.Runtime.Augments;
namespace System.Buffers
{
/// <summary>
/// Provides an ArrayPool implementation meant to be used as the singleton returned from ArrayPool.Shared.
/// </summary>
/// <remarks>
/// The implementation uses a tiered caching scheme, with a small per-thread cache for each array size, followed
/// by a cache per array size shared by all threads, split into per-core stacks meant to be used by threads
/// running on that core. Locks are used to protect each per-core stack, because a thread can migrate after
/// checking its processor number, because multiple threads could interleave on the same core, and because
/// a thread is allowed to check other core's buckets if its core's bucket is empty/full.
/// </remarks>
internal sealed partial class TlsOverPerCoreLockedStacksArrayPool<T> : ArrayPool<T>
{
// TODO: #7747: "Investigate optimizing ArrayPool heuristics"
// - Explore caching in TLS more than one array per size per thread, and moving stale buffers to the global queue.
// - Explore dumping stale buffers from the global queue, similar to PinnableBufferCache (maybe merging them).
// - Explore changing the size of each per-core bucket, potentially dynamically or based on other factors like array size.
// - Explore changing number of buckets and what sizes of arrays are cached.
// - Investigate whether false sharing is causing any issues, in particular on LockedStack's count and the contents of its array.
// ...
/// <summary>The number of buckets (array sizes) in the pool, one for each array length, starting from length 16.</summary>
private const int NumBuckets = 17; // Utilities.SelectBucketIndex(2*1024*1024)
/// <summary>Maximum number of per-core stacks to use per array size.</summary>
private const int MaxPerCorePerArraySizeStacks = 64; // selected to avoid needing to worry about processor groups
/// <summary>The maximum number of buffers to store in a bucket's global queue.</summary>
private const int MaxBuffersPerArraySizePerCore = 8;
/// <summary>The length of arrays stored in the corresponding indices in <see cref="_buckets"/> and <see cref="t_tlsBuckets"/>.</summary>
private readonly int[] _bucketArraySizes;
/// <summary>
/// An array of per-core array stacks. The slots are lazily initialized to avoid creating
/// lots of overhead for unused array sizes.
/// </summary>
private readonly PerCoreLockedStacks[] _buckets = new PerCoreLockedStacks[NumBuckets];
/// <summary>A per-thread array of arrays, to cache one array per array size per thread.</summary>
[ThreadStatic]
private static T[][] t_tlsBuckets;
/// <summary>Initialize the pool.</summary>
public TlsOverPerCoreLockedStacksArrayPool()
{
var sizes = new int[NumBuckets];
for (int i = 0; i < sizes.Length; i++)
{
sizes[i] = Utilities.GetMaxSizeForBucket(i);
}
_bucketArraySizes = sizes;
}
/// <summary>Allocate a new PerCoreLockedStacks and try to store it into the <see cref="_buckets"/> array.</summary>
private PerCoreLockedStacks CreatePerCoreLockedStacks(int bucketIndex)
{
var inst = new PerCoreLockedStacks();
return Interlocked.CompareExchange(ref _buckets[bucketIndex], inst, null) ?? inst;
}
/// <summary>Gets an ID for the pool to use with events.</summary>
private int Id => GetHashCode();
public override T[] Rent(int minimumLength)
{
// Arrays can't be smaller than zero. We allow requesting zero-length arrays (even though
// pooling such an array isn't valuable) as it's a valid length array, and we want the pool
// to be usable in general instead of using `new`, even for computed lengths.
if (minimumLength < 0)
{
throw new ArgumentOutOfRangeException(nameof(minimumLength));
}
else if (minimumLength == 0)
{
// No need to log the empty array. Our pool is effectively infinite
// and we'll never allocate for rents and never store for returns.
return Array.Empty<T>();
}
ArrayPoolEventSource log = ArrayPoolEventSource.Log;
T[] buffer;
// Get the bucket number for the array length
int bucketIndex = Utilities.SelectBucketIndex(minimumLength);
// If the array could come from a bucket...
if (bucketIndex < _buckets.Length)
{
// First try to get it from TLS if possible.
T[][] tlsBuckets = t_tlsBuckets;
if (tlsBuckets != null)
{
buffer = tlsBuckets[bucketIndex];
if (buffer != null)
{
tlsBuckets[bucketIndex] = null;
if (log.IsEnabled())
{
log.BufferRented(buffer.GetHashCode(), buffer.Length, Id, bucketIndex);
}
return buffer;
}
}
// We couldn't get a buffer from TLS, so try the global stack.
PerCoreLockedStacks b = _buckets[bucketIndex];
if (b != null)
{
buffer = b.TryPop();
if (buffer != null)
{
if (log.IsEnabled())
{
log.BufferRented(buffer.GetHashCode(), buffer.Length, Id, bucketIndex);
}
return buffer;
}
}
// No buffer available. Allocate a new buffer with a size corresponding to the appropriate bucket.
buffer = new T[_bucketArraySizes[bucketIndex]];
}
else
{
// The request was for a size too large for the pool. Allocate an array of exactly the requested length.
// When it's returned to the pool, we'll simply throw it away.
buffer = new T[minimumLength];
}
if (log.IsEnabled())
{
int bufferId = buffer.GetHashCode(), bucketId = -1; // no bucket for an on-demand allocated buffer
log.BufferRented(bufferId, buffer.Length, Id, bucketId);
log.BufferAllocated(bufferId, buffer.Length, Id, bucketId, bucketIndex >= _buckets.Length ?
ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize :
ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted);
}
return buffer;
}
public override void Return(T[] array, bool clearArray = false)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// Determine with what bucket this array length is associated
int bucketIndex = Utilities.SelectBucketIndex(array.Length);
// If we can tell that the buffer was allocated (or empty), drop it. Otherwise, check if we have space in the pool.
if (bucketIndex < _buckets.Length)
{
// Clear the array if the user requests.
if (clearArray)
{
Array.Clear(array, 0, array.Length);
}
// Check to see if the buffer is the correct size for this bucket
if (array.Length != _bucketArraySizes[bucketIndex])
{
throw new ArgumentException(SR.ArgumentException_BufferNotFromPool, nameof(array));
}
// Write through the TLS bucket. If there weren't any buckets, create them
// and store this array into it. If there were, store this into it, and
// if there was a previous one there, push that to the global stack. This
// helps to keep LIFO access such that the most recently pushed stack will
// be in TLS and the first to be popped next.
T[][] tlsBuckets = t_tlsBuckets;
if (tlsBuckets == null)
{
t_tlsBuckets = tlsBuckets = new T[NumBuckets][];
tlsBuckets[bucketIndex] = array;
}
else
{
T[] prev = tlsBuckets[bucketIndex];
tlsBuckets[bucketIndex] = array;
if (prev != null)
{
PerCoreLockedStacks bucket = _buckets[bucketIndex] ?? CreatePerCoreLockedStacks(bucketIndex);
bucket.TryPush(prev);
}
}
}
// Log that the buffer was returned
ArrayPoolEventSource log = ArrayPoolEventSource.Log;
if (log.IsEnabled())
{
log.BufferReturned(array.GetHashCode(), array.Length, Id);
}
}
/// <summary>
/// Stores a set of stacks of arrays, with one stack per core.
/// </summary>
private sealed class PerCoreLockedStacks
{
/// <summary>The stacks.</summary>
private readonly LockedStack[] _perCoreStacks;
/// <summary>Initializes the stacks.</summary>
public PerCoreLockedStacks()
{
// Create the stacks. We create as many as there are processors, limited by our max.
var stacks = new LockedStack[Math.Min(Environment.ProcessorCount, MaxPerCorePerArraySizeStacks)];
for (int i = 0; i < stacks.Length; i++)
{
stacks[i] = new LockedStack();
}
_perCoreStacks = stacks;
}
/// <summary>Try to push the array into the stacks. If each is full when it's tested, the array will be dropped.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void TryPush(T[] array)
{
// Try to push on to the associated stack first. If that fails,
// round-robin through the other stacks.
LockedStack[] stacks = _perCoreStacks;
int index = RuntimeThread.GetCurrentProcessorId() % stacks.Length;
for (int i = 0; i < stacks.Length; i++)
{
if (stacks[index].TryPush(array)) return;
if (++index == stacks.Length) index = 0;
}
}
/// <summary>Try to get an array from the stacks. If each is empty when it's tested, null will be returned.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T[] TryPop()
{
// Try to pop from the associated stack first. If that fails,
// round-robin through the other stacks.
T[] arr;
LockedStack[] stacks = _perCoreStacks;
int index = RuntimeThread.GetCurrentProcessorId() % stacks.Length;
for (int i = 0; i < stacks.Length; i++)
{
if ((arr = stacks[index].TryPop()) != null) return arr;
if (++index == stacks.Length) index = 0;
}
return null;
}
}
/// <summary>Provides a simple stack of arrays, protected by a lock.</summary>
private sealed class LockedStack
{
private readonly T[][] _arrays = new T[MaxBuffersPerArraySizePerCore][];
private int _count;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryPush(T[] array)
{
bool enqueued = false;
Monitor.Enter(this);
if (_count < MaxBuffersPerArraySizePerCore)
{
_arrays[_count++] = array;
enqueued = true;
}
Monitor.Exit(this);
return enqueued;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T[] TryPop()
{
T[] arr = null;
Monitor.Enter(this);
if (_count > 0)
{
arr = _arrays[--_count];
_arrays[_count] = null;
}
Monitor.Exit(this);
return arr;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="MailAddress.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Net.Mail
{
using System;
using System.Text;
using System.Net.Mime;
using System.Diagnostics;
using System.Globalization;
//
// This class stores the basic components of an e-mail address as described in RFC 2822 Section 3.4.
// Any parsing required is done with the MailAddressParser class.
//
public class MailAddress
{
// These components form an e-mail address when assembled as follows:
// "EncodedDisplayname" <userName@host>
private readonly Encoding displayNameEncoding;
private readonly string displayName;
private readonly string userName;
private readonly string host;
// For internal use only by MailAddressParser.
// The components were already validated before this is called.
internal MailAddress(string displayName, string userName, string domain) {
this.host = domain;
this.userName = userName;
this.displayName = displayName;
this.displayNameEncoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet);
Debug.Assert(host != null,
"host was null in internal constructor");
Debug.Assert(userName != null,
"userName was null in internal constructor");
Debug.Assert(displayName != null,
"displayName was null in internal constructor");
}
public MailAddress(string address) : this(address, null, (Encoding)null) {
}
public MailAddress(string address, string displayName) : this(address, displayName, (Encoding)null) {
}
//
// This constructor validates and stores the components of an e-mail address.
//
// Preconditions:
// - 'address' must not be null or empty.
//
// Postconditions:
// - The e-mail address components from the given 'address' are parsed, which should be formatted as:
// "EncodedDisplayname" <username@host>
// - If a 'displayName' is provided separately, it overrides whatever display name is parsed from the 'address'
// field. The display name does not need to be pre-encoded if a 'displayNameEncoding' is provided.
//
// A FormatException will be thrown if any of the components in 'address' are invalid.
public MailAddress(string address, string displayName, Encoding displayNameEncoding) {
if (address == null){
throw new ArgumentNullException("address");
}
if (address == String.Empty){
throw new ArgumentException(SR.GetString(SR.net_emptystringcall,"address"), "address");
}
this.displayNameEncoding = displayNameEncoding ?? Encoding.GetEncoding(MimeBasePart.defaultCharSet);
this.displayName = displayName ?? string.Empty;
// Check for bounding quotes
if (!String.IsNullOrEmpty(this.displayName)) {
this.displayName = MailAddressParser.NormalizeOrThrow(this.displayName);
if (this.displayName.Length >= 2 && this.displayName[0] == '\"'
&& this.displayName[this.displayName.Length - 1] == '\"') {
// Peal bounding quotes, they'll get re-added later.
this.displayName = this.displayName.Substring(1, this.displayName.Length - 2);
}
}
MailAddress result = MailAddressParser.ParseAddress(address);
this.host = result.host;
this.userName = result.userName;
// If we were not given a display name, use the one parsed from 'address'.
if (String.IsNullOrEmpty(this.displayName)) {
this.displayName = result.displayName;
}
}
public string DisplayName
{
get
{
return displayName;
}
}
public string User
{
get
{
return this.userName;
}
}
private string GetUser(bool allowUnicode)
{
// Unicode usernames cannot be downgraded
if (!allowUnicode && !MimeBasePart.IsAscii(userName, true))
{
throw new SmtpException(SR.GetString(SR.SmtpNonAsciiUserNotSupported, Address));
}
return userName;
}
public string Host
{
get
{
return this.host;
}
}
private string GetHost(bool allowUnicode)
{
string domain = host;
// Downgrade Unicode domain names
if (!allowUnicode && !MimeBasePart.IsAscii(domain, true))
{
IdnMapping mapping = new IdnMapping();
try
{
domain = mapping.GetAscii(domain);
}
catch (ArgumentException argEx)
{
throw new SmtpException(SR.GetString(SR.SmtpInvalidHostName, Address), argEx);
}
}
return domain;
}
public string Address
{
get
{
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", userName, host);
}
}
private string GetAddress(bool allowUnicode)
{
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}",
GetUser(allowUnicode), GetHost(allowUnicode));
}
private string SmtpAddress {
get{
return String.Format(CultureInfo.InvariantCulture, "<{0}>", Address);
}
}
internal string GetSmtpAddress(bool allowUnicode)
{
return String.Format(CultureInfo.InvariantCulture, "<{0}>", GetAddress(allowUnicode));
}
/// <summary>
/// this returns the full address with quoted display name.
/// i.e. "some email address display name" <user@host>
/// if displayname is not provided then this returns only user@host (no angle brackets)
/// </summary>
/// <returns></returns>
public override string ToString() {
if (String.IsNullOrEmpty(DisplayName)) {
return this.Address;
}
else {
return String.Format("\"{0}\" {1}", DisplayName, SmtpAddress);
}
}
public override bool Equals(object value) {
if (value == null) {
return false;
}
return ToString().Equals(value.ToString(),StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCode(){
return ToString().GetHashCode();
}
static EncodedStreamFactory encoderFactory = new EncodedStreamFactory();
// Encodes the full email address, folding as needed
internal string Encode(int charsConsumed, bool allowUnicode)
{
string encodedAddress = String.Empty;
IEncodableStream encoder;
byte[] buffer;
Debug.Assert(this.Address != null, "address was null");
//do we need to take into account the Display name? If so, encode it
if (!String.IsNullOrEmpty(this.displayName))
{
//figure out the encoding type. If it's all ASCII and contains no CRLF then
//it does not need to be encoded for parity with other email clients. We will
//however fold at the end of the display name so that the email address itself can
//be appended.
if (MimeBasePart.IsAscii(this.displayName, false) || allowUnicode)
{
encodedAddress = String.Format(CultureInfo.InvariantCulture, "\"{0}\"", this.displayName);
}
else
{
//encode the displayname since it's non-ascii
encoder = encoderFactory.GetEncoderForHeader(this.displayNameEncoding, false, charsConsumed);
buffer = displayNameEncoding.GetBytes(this.displayName);
encoder.EncodeBytes(buffer, 0, buffer.Length);
encodedAddress = encoder.GetEncodedString();
}
//address should be enclosed in <> when a display name is present
encodedAddress += " " + GetSmtpAddress(allowUnicode);
}
else
{
//no display name, just return the address
encodedAddress = GetAddress(allowUnicode);
}
return encodedAddress;
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="FixUpCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Data;
using System.Data.EntityModel.SchemaObjectModel;
using System.Data.Entity.Design;
namespace System.Data.EntityModel.Emitters
{
internal sealed class FixUpCollection : List<FixUp>
{
#region Private Types
private enum CSDeclType
{
Method,
Property,
Other,
}
public enum VBStatementType
{
BeginClass,
EndClass,
BeginProperty,
EndProperty,
BeginMethod,
EndMethod,
BeginPropertyGetter,
EndPropertyGetter,
BeginPropertySetter,
EndPropertySetter,
Other,
}
#endregion
#region Instance Fields
private Dictionary<string,List<FixUp>> _classFixUps = null;
private LanguageOption _language;
#endregion
#region Static Fields
static readonly char[] _CSEndOfClassDelimiters = new char[] { ' ',':' };
const string _CSClassKeyWord = " class ";
static readonly char[] _CSFieldMarkers = new char[] { '=',';' };
static readonly char[] _VBEndOfClassDelimiters = new char[] { ' ', '(' };
static readonly char[] _VBNonDeclMarkers = new char[] { '=', '"', '\'' };
#endregion
#region Public Methods
/// <summary>
///
/// </summary>
public FixUpCollection()
{
}
public static bool IsLanguageSupported(LanguageOption language)
{
switch ( language )
{
case LanguageOption.GenerateVBCode:
case LanguageOption.GenerateCSharpCode:
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="writer"></param>
/// <param name="language"></param>
public void Do(System.IO.TextReader reader, System.IO.TextWriter writer, LanguageOption language, bool hasNamespace)
{
Language = language;
// set up the fix ups for each class.
foreach ( FixUp fixUp in this )
{
List<FixUp> fixUps = null;
if ( ClassFixUps.ContainsKey(fixUp.Class) )
{
fixUps = ClassFixUps[fixUp.Class];
}
else
{
fixUps = new List<FixUp>();
ClassFixUps.Add(fixUp.Class,fixUps);
}
fixUps.Add(fixUp);
}
switch ( Language )
{
case LanguageOption.GenerateVBCode:
DoFixUpsForVB(reader, writer);
break;
case LanguageOption.GenerateCSharpCode:
DoFixUpsForCS(reader, writer, hasNamespace);
break;
default:
Debug.Assert(false,"Unexpected language value: "+Language.ToString());
CopyFile(reader,writer);
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="writer"></param>
private static void CopyFile(System.IO.TextReader reader, System.IO.TextWriter writer)
{
string line;
while ( (line=reader.ReadLine()) != null )
writer.WriteLine(line);
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="writer"></param>
private void DoFixUpsForCS(System.IO.TextReader reader, System.IO.TextWriter writer, bool hasNamespace)
{
int braceCount = 0;
string line;
string trimmedLine;
string currentOuterClass = null;
string className;
bool classWanted = false;
FixUp getterFixUp = null;
FixUp setterFixUp = null;
int nameSpaceLevel = hasNamespace ? 1 : 0;
while ( (line=reader.ReadLine()) != null )
{
trimmedLine = line.Trim();
if ( trimmedLine == "{" )
++braceCount;
else if ( trimmedLine == "}" )
{
--braceCount;
if (braceCount < nameSpaceLevel + 2)
{
setterFixUp = null;
if (braceCount < nameSpaceLevel + 1)
{
currentOuterClass = null;
classWanted = false;
}
}
}
else if ( string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith("//",StringComparison.Ordinal) )
{
// comment, just emit as is....
}
else if ( IsCSClassDefinition(line,out className) )
{
if (braceCount == nameSpaceLevel)
{
currentOuterClass = className;
className = null;
classWanted = IsClassWanted(currentOuterClass);
if ( classWanted )
line = FixUpClassDecl(currentOuterClass,line);
}
}
else if ( classWanted )
{
//we only care about methods/properties in top level classes
if (braceCount == nameSpaceLevel + 1)
{
string name;
switch ( GetCSDeclType(trimmedLine,out name) )
{
case CSDeclType.Method:
line = FixUpMethodDecl(currentOuterClass,name,line);
break;
case CSDeclType.Property:
setterFixUp = FixUpSetter(currentOuterClass, name);
getterFixUp = FixUpGetter(currentOuterClass, name);
break;
}
}
else if (braceCount == nameSpaceLevel + 2)
{
if (trimmedLine == "set" && setterFixUp != null)
{
line = setterFixUp.Fix(LanguageOption.GenerateCSharpCode, line);
setterFixUp = null;
}
else if (trimmedLine == "get" && getterFixUp != null)
{
line = getterFixUp.Fix(LanguageOption.GenerateCSharpCode, line);
getterFixUp = null;
}
}
}
writer.WriteLine(line);
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="writer"></param>
public void DoFixUpsForVB(System.IO.TextReader reader, System.IO.TextWriter writer)
{
Language = LanguageOption.GenerateVBCode;
string line;
Stack<VBStatementType> context = new Stack<VBStatementType>();
int classDepth = 0;
string currentOuterClass = null;
bool classWanted = false;
FixUp getterFixUp = null;
FixUp setterFixUp = null;
while ( (line=reader.ReadLine()) != null )
{
if ( line == null || line.Length == 0 || line[0] == '\'' )
{
// empty line or comment, ouput as is
}
else
{
string name;
switch ( GetVBStatementType(context, line, out name) )
{
case VBStatementType.BeginClass:
++classDepth;
setterFixUp = null;
if ( classDepth == 1 )
{
currentOuterClass = name;
classWanted = IsClassWanted(name);
if ( classWanted )
line = FixUpClassDecl(currentOuterClass, line);
}
break;
case VBStatementType.EndClass:
--classDepth;
if (classDepth == 0)
{
currentOuterClass = null;
}
break;
case VBStatementType.BeginProperty:
if (classWanted)
{
getterFixUp = FixUpGetter(currentOuterClass, name);
setterFixUp = FixUpSetter(currentOuterClass, name);
}
else
{
getterFixUp = null;
setterFixUp = null;
}
break;
case VBStatementType.EndProperty:
getterFixUp = null;
setterFixUp = null;
break;
case VBStatementType.BeginMethod:
if (classWanted)
{
line = FixUpMethodDecl(currentOuterClass, name, line);
}
break;
case VBStatementType.BeginPropertySetter:
if (setterFixUp != null)
{
line = setterFixUp.Fix(Language, line);
}
setterFixUp = null;
break;
case VBStatementType.BeginPropertyGetter:
if (getterFixUp != null)
{
line = getterFixUp.Fix(Language, line);
}
getterFixUp = null;
break;
}
}
writer.WriteLine(line);
}
}
#endregion
#region Private Methods
/// <summary>
///
/// </summary>
/// <param name="className"></param>
/// <returns></returns>
private bool IsClassWanted(string className)
{
return ClassFixUps.ContainsKey(className);
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <param name="className"></param>
/// <returns></returns>
private static bool IsCSClassDefinition(string line,out string className)
{
int index = line.IndexOf(_CSClassKeyWord,StringComparison.Ordinal);
if ( index < 0 )
{
className = null;
return false;
}
index += _CSClassKeyWord.Length;
int end = line.IndexOfAny(_CSEndOfClassDelimiters, index);
if ( end < 0 )
className = line.Substring(index);
else
className = line.Substring(index,end-index);
if (className.StartsWith("@", StringComparison.Ordinal))
{
// remove the escaping mechanisim for C# keywords
className = className.Substring(1);
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="className"></param>
/// <param name="line"></param>
/// <returns></returns>
private string FixUpClassDecl(string className,string line)
{
IList<FixUp> fixUps = ClassFixUps[className];
foreach ( FixUp fixUp in fixUps )
{
if ( fixUp.Type == FixUpType.MarkClassAsStatic )
{
return fixUp.Fix(Language,line);
}
}
return line;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <param name="name"></param>
/// <returns></returns>
private static CSDeclType GetCSDeclType(string line, out string name)
{
// we know we're at the class member level.
// things we could encounter are (limited to things we actually emit):
// nested classes (already identified)
// attributes
// fields
// methods
// properties
name = null;
//Attributes
if (line[0] == '[')
return CSDeclType.Other;
// Methods have ( and ) without a =
int parIdx1 = line.IndexOf('(');
int parIdx2 = line.IndexOf(')');
int equIdx = line.IndexOf('='); //return -1 for absent equal sign.
if (equIdx == -1 && parIdx1 >= 0 && parIdx2 > parIdx1)
{
line = line.Substring(0, parIdx1).TrimEnd(null);
name = line.Substring(line.LastIndexOf(' ') + 1);
return CSDeclType.Method;
}
//we assume fields have = or ;
if (line.IndexOfAny(_CSFieldMarkers, 0) >= 0)
return CSDeclType.Other;
//Properties
CSDeclType declType = CSDeclType.Property;
name = line.Substring(line.LastIndexOf(' ') + 1);
return declType;
}
/// <summary>
///
/// </summary>
/// <param name="className"></param>
/// <param name="methodName"></param>
/// <param name="line"></param>
/// <returns></returns>
private string FixUpMethodDecl(string className,string methodName,string line)
{
IList<FixUp> fixUps = ClassFixUps[className];
foreach ( FixUp fixUp in fixUps )
{
if ( fixUp.Method == methodName &&
(fixUp.Type == FixUpType.MarkOverrideMethodAsSealed || fixUp.Type == FixUpType.MarkAbstractMethodAsPartial) )
{
return fixUp.Fix(Language,line);
}
}
return line;
}
/// <summary>
///
/// </summary>
/// <param name="className"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
private FixUp FixUpSetter(string className,string propertyName)
{
IList<FixUp> fixUps = ClassFixUps[className];
foreach ( FixUp fixUp in fixUps )
{
if (fixUp.Property == propertyName &&
(fixUp.Type == FixUpType.MarkPropertySetAsPrivate ||
fixUp.Type == FixUpType.MarkPropertySetAsInternal ||
fixUp.Type == FixUpType.MarkPropertySetAsPublic ||
fixUp.Type == FixUpType.MarkPropertySetAsProtected))
{
return fixUp;
}
}
return null;
}
private FixUp FixUpGetter(string className, string propertyName)
{
IList<FixUp> fixUps = ClassFixUps[className];
foreach (FixUp fixUp in fixUps)
{
if (fixUp.Property == propertyName &&
(fixUp.Type == FixUpType.MarkPropertyGetAsPrivate ||
fixUp.Type == FixUpType.MarkPropertyGetAsInternal ||
fixUp.Type == FixUpType.MarkPropertyGetAsPublic ||
fixUp.Type == FixUpType.MarkPropertyGetAsProtected))
{
return fixUp;
}
}
return null;
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
/// <param name="line"></param>
/// <param name="name"></param>
/// <returns></returns>
private static VBStatementType GetVBStatementType(Stack<VBStatementType> context, string line, out string name)
{
name = null;
VBStatementType current = VBStatementType.Other;
// if the statement constains ", =, or... then it's not a statement type we care about
if ( line.IndexOfAny(_VBNonDeclMarkers) >= 0 )
return current;
string normalizedLine = NormalizeForVB(line);
if ( context.Count <= 0 )
{
// without context we only accept BeginClass
if ( LineIsVBBeginClassMethodProperty(normalizedLine, "Class", ref name) )
{
current = VBStatementType.BeginClass;
context.Push(current);
}
}
else
{
// we only look for things based on context:
switch ( context.Peek() )
{
// at BeginClass we only accept
// BeginClass
// EndClass
// BeginProperty
// BeginMethod
case VBStatementType.BeginClass:
if ( normalizedLine == "End Class" )
{
current = VBStatementType.EndClass;
context.Pop();
}
else
{
if ( LineIsVBBeginClassMethodProperty(normalizedLine, "Class", ref name) )
{
current = VBStatementType.BeginClass;
context.Push(current);
}
else if ( LineIsVBBeginClassMethodProperty(normalizedLine, "MustOverride Sub", ref name) )
{
// Abstract methods do not have an "End Sub", this don't push the context.
current = VBStatementType.BeginMethod;
}
else if ( LineIsVBBeginClassMethodProperty(normalizedLine, "Function", ref name)
|| LineIsVBBeginClassMethodProperty(normalizedLine, "Sub", ref name) )
{
current = VBStatementType.BeginMethod;
context.Push(current);
}
else if ( LineIsVBBeginClassMethodProperty(normalizedLine, "Property", ref name) )
{
current = VBStatementType.BeginProperty;
context.Push(current);
}
}
break;
// at BeginProperty we only accept
// EndProperty
// BeginPropertyGetter
// BeginPropertySetter
case VBStatementType.BeginProperty:
if ( normalizedLine == "End Property" )
{
current = VBStatementType.EndProperty;
context.Pop();
}
else
{
if ( LineIsVBBeginSetterGetter(normalizedLine, "Get") )
{
current = VBStatementType.BeginPropertyGetter;
context.Push(current);
}
else if ( LineIsVBBeginSetterGetter(normalizedLine, "Set") )
{
current = VBStatementType.BeginPropertySetter;
context.Push(current);
}
}
break;
// at BeginMethod we only accept
// EndMethod
case VBStatementType.BeginMethod:
if ( normalizedLine == "End Sub" || normalizedLine == "End Function" )
{
current = VBStatementType.EndMethod;
context.Pop();
}
break;
// at BeginPropertyGetter we only accept
// EndPropertyGetter
case VBStatementType.BeginPropertyGetter:
if ( normalizedLine == "End Get" )
{
current = VBStatementType.EndPropertyGetter;
context.Pop();
}
break;
// at BeginPropertySetter we only accept
// EndPropertySetter
case VBStatementType.BeginPropertySetter:
if ( normalizedLine == "End Set" )
{
current = VBStatementType.EndPropertySetter;
context.Pop();
}
break;
}
}
return current;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
private static string NormalizeForVB(string line)
{
// no leading or trailing spaces and tabs are replaced with spaces
line = line.Replace('\t', ' ').Trim();
// consecutuve spaces are replaced with single spaces...
// (we don't care about hammering strings; we just use the normalized line for statment identification...
while ( line.IndexOf(" ", 0,StringComparison.Ordinal) >= 0 )
line = line.Replace(" ", " ");
return line;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <param name="keyword"></param>
/// <returns></returns>
private static bool LineIsVBBeginSetterGetter(string line, string keyword)
{
return IndexOfKeyword(line, keyword) >= 0;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <param name="keyword"></param>
/// <returns></returns>
private static int IndexOfKeyword(string line, string keyword)
{
int index = line.IndexOf(keyword,StringComparison.Ordinal);
if ( index < 0 )
return index;
char ch;
int indexAfter = index+keyword.Length;
if ( (index == 0 || char.IsWhiteSpace(line, index-1)) && (indexAfter == line.Length || (ch=line[indexAfter]) == '(' || char.IsWhiteSpace(ch)) )
return index;
return -1;
}
/// <summary>
///
/// </summary>
/// <param name="line"></param>
/// <param name="keyword"></param>
/// <param name="name"></param>
/// <returns></returns>
private static bool LineIsVBBeginClassMethodProperty(string line, string keyword, ref string name)
{
// line must contain the keyword
int index = IndexOfKeyword(line, keyword);
if ( index < 0 )
return false;
// after the keyword we expact a space and the name
index += keyword.Length;
if ( index >= line.Length || !char.IsWhiteSpace(line, index) )
return false;
++index;
if ( index >= line.Length )
return false;
// after the name we expect a EOL or a delimiter...
int end = line.IndexOfAny(_VBEndOfClassDelimiters, index);
if ( end < 0 )
end = line.Length;
name = line.Substring(index, end-index).Trim();
if (name.StartsWith("[", StringComparison.Ordinal) && name.EndsWith("]", StringComparison.Ordinal))
{
// remove the vb keyword escaping mechanisim
name = name.Substring(1, name.Length - 2);
}
return true;
}
#endregion
#region Private Properties
/// <summary>
///
/// </summary>
private LanguageOption Language
{
get
{
return _language;
}
set
{
_language = value;
}
}
/// <summary>
///
/// </summary>
/// <value></value>
private Dictionary<string,List<FixUp>> ClassFixUps
{
get
{
if ( _classFixUps == null )
{
_classFixUps = new Dictionary<string,List<FixUp>>();
}
return _classFixUps;
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlTextReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Collections;
using System.Security.Policy;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Runtime.Versioning;
namespace System.Xml {
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )]
public class XmlTextReader : XmlReader, IXmlLineInfo, IXmlNamespaceResolver {
//
// Member fields
//
XmlTextReaderImpl impl;
//
//
// Constructors
//
protected XmlTextReader() {
impl = new XmlTextReaderImpl();
impl.OuterReader = this;
}
protected XmlTextReader( XmlNameTable nt ) {
impl = new XmlTextReaderImpl( nt );
impl.OuterReader = this;
}
public XmlTextReader( Stream input ) {
impl = new XmlTextReaderImpl( input );
impl.OuterReader = this;
}
public XmlTextReader( string url, Stream input ) {
impl = new XmlTextReaderImpl( url, input );
impl.OuterReader = this;
}
public XmlTextReader( Stream input, XmlNameTable nt ) {
impl = new XmlTextReaderImpl( input, nt );
impl.OuterReader = this;
}
public XmlTextReader( string url, Stream input, XmlNameTable nt ) {
impl = new XmlTextReaderImpl( url, input, nt );
impl.OuterReader = this;
}
public XmlTextReader( TextReader input ) {
impl = new XmlTextReaderImpl( input );
impl.OuterReader = this;
}
public XmlTextReader( string url, TextReader input ) {
impl = new XmlTextReaderImpl( url, input );
impl.OuterReader = this;
}
public XmlTextReader( TextReader input, XmlNameTable nt ) {
impl = new XmlTextReaderImpl( input, nt );
impl.OuterReader = this;
}
public XmlTextReader( string url, TextReader input, XmlNameTable nt ) {
impl = new XmlTextReaderImpl( url, input, nt );
impl.OuterReader = this;
}
public XmlTextReader( Stream xmlFragment, XmlNodeType fragType, XmlParserContext context ) {
impl = new XmlTextReaderImpl( xmlFragment, fragType, context );
impl.OuterReader = this;
}
public XmlTextReader( string xmlFragment, XmlNodeType fragType, XmlParserContext context ) {
impl = new XmlTextReaderImpl( xmlFragment, fragType, context );
impl.OuterReader = this;
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public XmlTextReader( string url ) {
impl = new XmlTextReaderImpl( url, new NameTable() );
impl.OuterReader = this;
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public XmlTextReader( String url, XmlNameTable nt ) {
impl = new XmlTextReaderImpl( url, nt );
impl.OuterReader = this;
}
//
// XmlReader members
//
public override XmlNodeType NodeType {
get { return impl.NodeType; }
}
public override string Name {
get { return impl.Name; }
}
public override string LocalName {
get { return impl.LocalName; }
}
public override string NamespaceURI {
get { return impl.NamespaceURI; }
}
public override string Prefix {
get { return impl.Prefix; }
}
public override bool HasValue {
get { return impl.HasValue; }
}
public override string Value {
get { return impl.Value; }
}
public override int Depth {
get { return impl.Depth; }
}
public override string BaseURI {
get { return impl.BaseURI; }
}
public override bool IsEmptyElement {
get { return impl.IsEmptyElement; }
}
public override bool IsDefault {
get { return impl.IsDefault; }
}
public override char QuoteChar {
get { return impl.QuoteChar; }
}
public override XmlSpace XmlSpace {
get { return impl.XmlSpace; }
}
public override string XmlLang {
get { return impl.XmlLang; }
}
// XmlTextReader does not override SchemaInfo, ValueType and ReadTypeValue
public override int AttributeCount { get { return impl.AttributeCount; } }
public override string GetAttribute( string name ) {
return impl.GetAttribute( name );
}
public override string GetAttribute( string localName, string namespaceURI ) {
return impl.GetAttribute( localName, namespaceURI );
}
public override string GetAttribute( int i ) {
return impl.GetAttribute( i );
}
public override bool MoveToAttribute( string name ) {
return impl.MoveToAttribute( name );
}
public override bool MoveToAttribute( string localName, string namespaceURI ) {
return impl.MoveToAttribute( localName, namespaceURI );
}
public override void MoveToAttribute( int i ) {
impl.MoveToAttribute( i );
}
public override bool MoveToFirstAttribute() {
return impl.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute() {
return impl.MoveToNextAttribute();
}
public override bool MoveToElement() {
return impl.MoveToElement();
}
public override bool ReadAttributeValue() {
return impl.ReadAttributeValue();
}
public override bool Read() {
return impl.Read();
}
public override bool EOF {
get { return impl.EOF; }
}
public override void Close() {
impl.Close();
}
public override ReadState ReadState {
get { return impl.ReadState; }
}
public override void Skip() {
impl.Skip();
}
public override XmlNameTable NameTable {
get { return impl.NameTable; }
}
public override String LookupNamespace( String prefix ) {
string ns = impl.LookupNamespace( prefix );
if ( ns != null && ns.Length == 0 ) {
ns = null;
}
return ns;
}
public override bool CanResolveEntity {
get { return true; }
}
public override void ResolveEntity() {
impl.ResolveEntity();
}
// Binary content access methods
public override bool CanReadBinaryContent {
get { return true; }
}
public override int ReadContentAsBase64( byte[] buffer, int index, int count ) {
return impl.ReadContentAsBase64( buffer, index, count );
}
public override int ReadElementContentAsBase64( byte[] buffer, int index, int count ) {
return impl.ReadElementContentAsBase64( buffer, index, count );
}
public override int ReadContentAsBinHex( byte[] buffer, int index, int count ) {
return impl.ReadContentAsBinHex( buffer, index, count );
}
public override int ReadElementContentAsBinHex( byte[] buffer, int index, int count ) {
return impl.ReadElementContentAsBinHex( buffer, index, count );
}
// Text streaming methods
// XmlTextReader does do support streaming of Value (there are backwards compatibility issues when enabled)
public override bool CanReadValueChunk {
get { return false; }
}
// Overriden helper methods
public override string ReadString() {
impl.MoveOffEntityReference();
return base.ReadString();
}
//
// IXmlLineInfo members
//
public bool HasLineInfo() { return true; }
public int LineNumber { get { return impl.LineNumber; } }
public int LinePosition { get { return impl.LinePosition; } }
//
// IXmlNamespaceResolver members
//
IDictionary<string,string> IXmlNamespaceResolver.GetNamespacesInScope( XmlNamespaceScope scope ) {
return impl.GetNamespacesInScope( scope );
}
string IXmlNamespaceResolver.LookupNamespace(string prefix) {
return impl.LookupNamespace( prefix );
}
string IXmlNamespaceResolver.LookupPrefix( string namespaceName ) {
return impl.LookupPrefix( namespaceName );
}
// This pragma disables a warning that the return type is not CLS-compliant, but generics are part of CLS in Whidbey.
#pragma warning disable 3002
// FXCOP: ExplicitMethodImplementationsInUnsealedClassesHaveVisibleAlternates
// public versions of IXmlNamespaceResolver methods, so that XmlTextReader subclasses can access them
public IDictionary<string,string> GetNamespacesInScope( XmlNamespaceScope scope ) {
return impl.GetNamespacesInScope( scope );
}
#pragma warning restore 3002
//
// XmlTextReader
//
public bool Namespaces {
get { return impl.Namespaces; }
set { impl.Namespaces = value; }
}
public bool Normalization {
get { return impl.Normalization; }
set { impl.Normalization = value; }
}
public Encoding Encoding {
get { return impl.Encoding; }
}
public WhitespaceHandling WhitespaceHandling {
get { return impl.WhitespaceHandling; }
set { impl.WhitespaceHandling = value; }
}
[Obsolete("Use DtdProcessing property instead.")]
public bool ProhibitDtd {
get { return impl.DtdProcessing == DtdProcessing.Prohibit; }
set { impl.DtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse; }
}
public DtdProcessing DtdProcessing {
get { return impl.DtdProcessing; }
set { impl.DtdProcessing = value; }
}
public EntityHandling EntityHandling {
get { return impl.EntityHandling; }
set { impl.EntityHandling = value; }
}
public XmlResolver XmlResolver {
set { impl.XmlResolver = value; }
}
public void ResetState() {
impl.ResetState();
}
public TextReader GetRemainder() {
return impl.GetRemainder();
}
public int ReadChars( char[] buffer, int index, int count ) {
return impl.ReadChars( buffer, index, count );
}
public int ReadBase64( byte[] array, int offset, int len ) {
return impl.ReadBase64( array, offset, len );
}
public int ReadBinHex( byte[] array, int offset, int len ) {
return impl.ReadBinHex( array, offset, len );
}
//
// Internal helper methods
//
internal XmlTextReaderImpl Impl {
get { return impl; }
}
internal override XmlNamespaceManager NamespaceManager {
get { return impl.NamespaceManager; }
}
// NOTE: System.Data.SqlXml.XmlDataSourceResolver accesses this property via reflection
internal bool XmlValidatingReaderCompatibilityMode {
set { impl.XmlValidatingReaderCompatibilityMode = value; }
}
internal override IDtdInfo DtdInfo {
get { return impl.DtdInfo; }
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Xml
{
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Runtime;
public abstract class XmlDictionaryWriter : XmlWriter
{
// Derived classes that implements WriteBase64Async should override
// this flag to true so that the base XmlDictionaryWriter would use the
// faster WriteBase64Async APIs instead of the default BeginWrite() implementation.
internal virtual bool FastAsync
{
get { return false; }
}
internal virtual AsyncCompletionResult WriteBase64Async(AsyncEventArgs<XmlWriteBase64AsyncArguments> state)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
return Task.Factory.FromAsync(this.BeginWriteBase64, this.EndWriteBase64, buffer, index, count, null);
}
internal virtual IAsyncResult BeginWriteBase64(byte[] buffer, int index, int count, AsyncCallback callback, object state)
{
return new WriteBase64AsyncResult(buffer, index, count, this, callback, state);
}
internal virtual void EndWriteBase64(IAsyncResult result)
{
WriteBase64AsyncResult.End(result);
}
static public XmlDictionaryWriter CreateBinaryWriter(Stream stream)
{
return CreateBinaryWriter(stream, null);
}
static public XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary)
{
return CreateBinaryWriter(stream, dictionary, null);
}
static public XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session)
{
return CreateBinaryWriter(stream, dictionary, session, true);
}
static public XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream)
{
XmlBinaryWriter writer = new XmlBinaryWriter();
writer.SetOutput(stream, dictionary, session, ownsStream);
return writer;
}
static public XmlDictionaryWriter CreateTextWriter(Stream stream)
{
return CreateTextWriter(stream, Encoding.UTF8, true);
}
static public XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding)
{
return CreateTextWriter(stream, encoding, true);
}
static public XmlDictionaryWriter CreateTextWriter(Stream stream, Encoding encoding, bool ownsStream)
{
XmlUTF8TextWriter writer = new XmlUTF8TextWriter();
writer.SetOutput(stream, encoding, ownsStream);
return writer;
}
static public XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo)
{
return CreateMtomWriter(stream, encoding, maxSizeInBytes, startInfo, null, null, true, true);
}
static public XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream)
{
XmlMtomWriter writer = new XmlMtomWriter();
writer.SetOutput(stream, encoding, maxSizeInBytes, startInfo, boundary, startUri, writeMessageHeaders, ownsStream);
return writer;
}
static public XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer)
{
if (writer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
XmlDictionaryWriter dictionaryWriter = writer as XmlDictionaryWriter;
if (dictionaryWriter == null)
{
dictionaryWriter = new XmlWrappedWriter(writer);
}
return dictionaryWriter;
}
public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartElement((string)null, localName, namespaceUri);
}
public virtual void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartElement(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartAttribute((string)null, localName, namespaceUri);
}
public virtual void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
WriteStartAttribute(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteAttributeString((string)null, localName, namespaceUri, value);
}
public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
if (prefix == null)
{
if (LookupPrefix(namespaceUri) != null)
return;
#pragma warning suppress 56506 // [....], namespaceUri is already checked
prefix = namespaceUri.Length == 0 ? string.Empty : string.Concat("d", namespaceUri.Length.ToString(System.Globalization.NumberFormatInfo.InvariantInfo));
}
WriteAttributeString("xmlns", prefix, null, namespaceUri);
}
public virtual void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri)
{
WriteXmlnsAttribute(prefix, XmlDictionaryString.GetString(namespaceUri));
}
public virtual void WriteXmlAttribute(string localName, string value)
{
WriteAttributeString("xml", localName, null, value);
}
public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value)
{
WriteXmlAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(value));
}
public void WriteAttributeString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteStartAttribute(prefix, localName, namespaceUri);
WriteString(value);
WriteEndAttribute();
}
public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteElementString((string)null, localName, namespaceUri, value);
}
public void WriteElementString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteString(value);
WriteEndElement();
}
public virtual void WriteString(XmlDictionaryString value)
{
WriteString(XmlDictionaryString.GetString(value));
}
public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("localName"));
if (namespaceUri == null)
namespaceUri = XmlDictionaryString.Empty;
#pragma warning suppress 56506 // [....], XmlDictionaryString.Empty is never null
WriteQualifiedName(localName.Value, namespaceUri.Value);
}
public virtual void WriteValue(XmlDictionaryString value)
{
WriteValue(XmlDictionaryString.GetString(value));
}
public virtual void WriteValue(IStreamProvider value)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
Stream stream = value.GetStream();
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidStream)));
int blockSize = 256;
int bytesRead = 0;
byte[] block = new byte[blockSize];
while (true)
{
bytesRead = stream.Read(block, 0, blockSize);
if (bytesRead > 0)
WriteBase64(block, 0, bytesRead);
else
break;
if (blockSize < 65536 && bytesRead == blockSize)
{
blockSize = blockSize * 16;
block = new byte[blockSize];
}
}
value.ReleaseStream(stream);
}
public virtual Task WriteValueAsync(IStreamProvider value)
{
return Task.Factory.FromAsync(this.BeginWriteValue, this.EndWriteValue, value, null);
}
internal virtual IAsyncResult BeginWriteValue(IStreamProvider value, AsyncCallback callback, object state)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
if (this.FastAsync)
{
return new WriteValueFastAsyncResult(this, value, callback, state);
}
else
{
return new WriteValueAsyncResult(this, value, callback, state);
}
}
internal virtual void EndWriteValue(IAsyncResult result)
{
if (this.FastAsync)
{
WriteValueFastAsyncResult.End(result);
}
else
{
WriteValueAsyncResult.End(result);
}
}
class WriteValueFastAsyncResult : AsyncResult
{
bool completed;
int blockSize;
byte[] block;
int bytesRead;
Stream stream;
Operation nextOperation;
IStreamProvider streamProvider;
XmlDictionaryWriter writer;
AsyncEventArgs<XmlWriteBase64AsyncArguments> writerAsyncState;
XmlWriteBase64AsyncArguments writerAsyncArgs;
static AsyncCallback onReadComplete = Fx.ThunkCallback(OnReadComplete);
static AsyncEventArgsCallback onWriteComplete;
public WriteValueFastAsyncResult(XmlDictionaryWriter writer, IStreamProvider value, AsyncCallback callback, object state)
: base(callback, state)
{
this.streamProvider = value;
this.writer = writer;
this.stream = value.GetStream();
if (this.stream == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidStream)));
}
this.blockSize = 256;
this.bytesRead = 0;
this.block = new byte[this.blockSize];
this.nextOperation = Operation.Read;
this.ContinueWork(true);
}
void CompleteAndReleaseStream(bool completedSynchronously, Exception completionException = null)
{
if (completionException == null)
{
// only release stream when no exception (mirrors [....] behaviour)
this.streamProvider.ReleaseStream(this.stream);
this.stream = null;
}
this.Complete(completedSynchronously, completionException);
}
void ContinueWork(bool completedSynchronously, Exception completionException = null)
{
// Individual Reads or writes may complete [....] or async. A callback however
// will always all ContinueWork() with CompletedSynchronously=false this flag
// is used to complete this AsyncResult.
try
{
while (true)
{
if (this.nextOperation == Operation.Read)
{
if (ReadAsync() != AsyncCompletionResult.Completed)
{
return;
}
}
else if (this.nextOperation == Operation.Write)
{
if (WriteAsync() != AsyncCompletionResult.Completed)
{
return;
}
}
else if (this.nextOperation == Operation.Complete)
{
break;
}
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
if (completedSynchronously)
{
throw;
}
if (completionException == null)
{
completionException = ex;
}
}
if (!completed)
{
this.completed = true;
this.CompleteAndReleaseStream(completedSynchronously, completionException);
}
}
AsyncCompletionResult ReadAsync()
{
IAsyncResult result = this.stream.BeginRead(this.block, 0, blockSize, onReadComplete, this);
if (result.CompletedSynchronously)
{
this.HandleReadComplete(result);
return AsyncCompletionResult.Completed;
}
return AsyncCompletionResult.Queued;
}
void HandleReadComplete(IAsyncResult result)
{
this.bytesRead = this.stream.EndRead(result);
if (this.bytesRead > 0)
{
this.nextOperation = Operation.Write;
}
else
{
this.nextOperation = Operation.Complete;
}
}
static void OnReadComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
Exception completionException = null;
WriteValueFastAsyncResult thisPtr = (WriteValueFastAsyncResult)result.AsyncState;
bool sucess = false;
try
{
thisPtr.HandleReadComplete(result);
sucess = true;
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
completionException = ex;
}
if (!sucess)
{
thisPtr.nextOperation = Operation.Complete;
}
thisPtr.ContinueWork(false, completionException);
}
AsyncCompletionResult WriteAsync()
{
if (this.writerAsyncState == null)
{
this.writerAsyncArgs = new XmlWriteBase64AsyncArguments();
this.writerAsyncState = new AsyncEventArgs<XmlWriteBase64AsyncArguments>();
}
if (onWriteComplete == null)
{
onWriteComplete = new AsyncEventArgsCallback(OnWriteComplete);
}
this.writerAsyncArgs.Buffer = this.block;
this.writerAsyncArgs.Offset = 0;
this.writerAsyncArgs.Count = this.bytesRead;
this.writerAsyncState.Set(onWriteComplete, this.writerAsyncArgs, this);
if (this.writer.WriteBase64Async(this.writerAsyncState) == AsyncCompletionResult.Completed)
{
this.HandleWriteComplete();
this.writerAsyncState.Complete(true);
return AsyncCompletionResult.Completed;
}
return AsyncCompletionResult.Queued;
}
void HandleWriteComplete()
{
this.nextOperation = Operation.Read;
// Adjust block size for next read
if (this.blockSize < 65536 && this.bytesRead == this.blockSize)
{
this.blockSize = this.blockSize * 16;
this.block = new byte[this.blockSize];
}
}
static void OnWriteComplete(IAsyncEventArgs asyncState)
{
WriteValueFastAsyncResult thisPtr = (WriteValueFastAsyncResult)asyncState.AsyncState;
Exception completionException = null;
bool success = false;
try
{
if (asyncState.Exception != null)
{
completionException = asyncState.Exception;
}
else
{
thisPtr.HandleWriteComplete();
success = true;
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
completionException = ex;
}
if (!success)
{
thisPtr.nextOperation = Operation.Complete;
}
thisPtr.ContinueWork(false, completionException);
}
internal static void End(IAsyncResult result)
{
AsyncResult.End<WriteValueFastAsyncResult>(result);
}
enum Operation
{
Read,
Write,
Complete
}
}
class WriteValueAsyncResult : AsyncResult
{
enum Operation
{
Read,
Write
}
int blockSize;
byte[] block;
int bytesRead;
Stream stream;
Operation operation = Operation.Read;
IStreamProvider streamProvider;
XmlDictionaryWriter writer;
static AsyncCallback onContinueWork = Fx.ThunkCallback(OnContinueWork);
public WriteValueAsyncResult(XmlDictionaryWriter writer, IStreamProvider value, AsyncCallback callback, object state)
: base(callback, state)
{
this.streamProvider = value;
this.writer = writer;
this.stream = value.GetStream();
if (this.stream == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidStream)));
}
this.blockSize = 256;
this.bytesRead = 0;
this.block = new byte[blockSize]; //
bool completeSelf = ContinueWork(null);
if (completeSelf)
{
this.CompleteAndReleaseStream(true, null);
}
}
void AdjustBlockSize()
{
if (this.blockSize < 65536 && this.bytesRead == this.blockSize)
{
this.blockSize = this.blockSize * 16;
this.block = new byte[this.blockSize];
}
}
void CompleteAndReleaseStream(bool completedSynchronously, Exception completionException)
{
if (completionException == null)
{
// only release stream when no exception (mirrors [....] behaviour)
this.streamProvider.ReleaseStream(this.stream);
this.stream = null;
}
this.Complete(completedSynchronously, completionException);
}
//returns whether or not the entire operation is completed
bool ContinueWork(IAsyncResult result)
{
while (true)
{
if (this.operation == Operation.Read)
{
if (HandleReadBlock(result))
{
// Read completed ([....] or async, doesn't matter)
if (this.bytesRead > 0)
{
// allow loop to continue at Write
operation = Operation.Write;
}
else
{
// Exit loop, entire source stream has been read.
return true;
}
}
else
{
// Read completed async, jump out of loop, callback resumes at writing.
return false;
}
}
else
{
if (HandleWriteBlock(result))
{
// Write completed ([....] or async, doesn't matter)
AdjustBlockSize();
operation = Operation.Read;
}
else
{
// Write completed async, jump out of loop, callback should resume at reading
return false;
}
}
result = null;
}
}
//returns whether or not I completed.
bool HandleReadBlock(IAsyncResult result)
{
if (result == null)
{
result = this.stream.BeginRead(this.block, 0, blockSize, onContinueWork, this);
if (!result.CompletedSynchronously)
{
return false;
}
}
this.bytesRead = this.stream.EndRead(result);
return true;
}
//returns whether or not I completed.
bool HandleWriteBlock(IAsyncResult result)
{
if (result == null)
{
result = this.writer.BeginWriteBase64(this.block, 0, this.bytesRead, onContinueWork, this);
if (!result.CompletedSynchronously)
{
return false;
}
}
this.writer.EndWriteBase64(result);
return true;
}
static void OnContinueWork(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
Exception completionException = null;
WriteValueAsyncResult thisPtr = (WriteValueAsyncResult)result.AsyncState;
bool completeSelf = false;
try
{
completeSelf = thisPtr.ContinueWork(result);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
completeSelf = true;
completionException = ex;
}
if (completeSelf)
{
thisPtr.CompleteAndReleaseStream(false, completionException);
}
}
public static void End(IAsyncResult result)
{
AsyncResult.End<WriteValueAsyncResult>(result);
}
}
public virtual void WriteValue(UniqueId value)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
WriteString(value.ToString());
}
public virtual void WriteValue(Guid value)
{
WriteString(value.ToString());
}
public virtual void WriteValue(TimeSpan value)
{
WriteString(XmlConvert.ToString(value));
}
public virtual bool CanCanonicalize
{
get
{
return false;
}
}
public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
void WriteElementNode(XmlDictionaryReader reader, bool defattr)
{
XmlDictionaryString localName;
XmlDictionaryString namespaceUri;
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
{
WriteStartElement(reader.Prefix, localName, namespaceUri);
}
else
{
WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
}
if (defattr || (!reader.IsDefault && (reader.SchemaInfo == null || !reader.SchemaInfo.IsDefault)))
{
if (reader.MoveToFirstAttribute())
{
do
{
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
{
WriteStartAttribute(reader.Prefix, localName, namespaceUri);
}
else
{
WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
}
while (reader.ReadAttributeValue())
{
if (reader.NodeType == XmlNodeType.EntityReference)
{
WriteEntityRef(reader.Name);
}
else
{
WriteTextNode(reader, true);
}
}
WriteEndAttribute();
}
while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
}
if (reader.IsEmptyElement)
{
WriteEndElement();
}
}
void WriteArrayNode(XmlDictionaryReader reader, string prefix, string localName, string namespaceUri, Type type)
{
if (type == typeof(bool))
BooleanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Int16))
Int16ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Int32))
Int32ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Int64))
Int64ArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(float))
SingleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(double))
DoubleArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(decimal))
DecimalArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(DateTime))
DateTimeArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Guid))
GuidArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(TimeSpan))
TimeSpanArrayHelperWithString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else
{
WriteElementNode(reader, false);
reader.Read();
}
}
void WriteArrayNode(XmlDictionaryReader reader, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Type type)
{
if (type == typeof(bool))
BooleanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Int16))
Int16ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Int32))
Int32ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Int64))
Int64ArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(float))
SingleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(double))
DoubleArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(decimal))
DecimalArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(DateTime))
DateTimeArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(Guid))
GuidArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else if (type == typeof(TimeSpan))
TimeSpanArrayHelperWithDictionaryString.Instance.WriteArray(this, prefix, localName, namespaceUri, reader);
else
{
WriteElementNode(reader, false);
reader.Read();
}
}
void WriteArrayNode(XmlDictionaryReader reader, Type type)
{
XmlDictionaryString localName;
XmlDictionaryString namespaceUri;
if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri))
WriteArrayNode(reader, reader.Prefix, localName, namespaceUri, type);
else
WriteArrayNode(reader, reader.Prefix, reader.LocalName, reader.NamespaceURI, type);
}
protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribute)
{
XmlDictionaryString value;
if (reader.TryGetValueAsDictionaryString(out value))
{
WriteString(value);
}
else
{
WriteString(reader.Value);
}
if (!isAttribute)
{
reader.Read();
}
}
public override void WriteNode(XmlReader reader, bool defattr)
{
XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
if (dictionaryReader != null)
WriteNode(dictionaryReader, defattr);
else
base.WriteNode(reader, defattr);
}
public virtual void WriteNode(XmlDictionaryReader reader, bool defattr)
{
if (reader == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
int d = (reader.NodeType == XmlNodeType.None ? -1 : reader.Depth);
do
{
XmlNodeType nodeType = reader.NodeType;
Type type;
if (nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace)
{
// This will advance if necessary, so we don't need to call Read() explicitly
WriteTextNode(reader, false);
}
else if (reader.Depth > d && reader.IsStartArray(out type))
{
WriteArrayNode(reader, type);
}
else
{
// These will not advance, so we must call Read() explicitly
switch (nodeType)
{
case XmlNodeType.Element:
WriteElementNode(reader, defattr);
break;
case XmlNodeType.CDATA:
WriteCData(reader.Value);
break;
case XmlNodeType.EntityReference:
WriteEntityRef(reader.Name);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.DocumentType:
WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value);
break;
case XmlNodeType.Comment:
WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
WriteFullEndElement();
break;
}
if (!reader.Read())
break;
}
}
while (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement));
}
void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("array"));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
// bool
public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int16
public virtual void WriteArray(string prefix, string localName, string namespaceUri, Int16[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int16[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int32
public virtual void WriteArray(string prefix, string localName, string namespaceUri, Int32[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int32[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int64
public virtual void WriteArray(string prefix, string localName, string namespaceUri, Int64[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Int64[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// float
public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// double
public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// decimal
public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// DateTime
public virtual void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Guid
public virtual void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// TimeSpan
public virtual void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
for (int i = 0; i < count; i++)
{
WriteStartElement(prefix, localName, namespaceUri);
WriteValue(array[offset + i]);
WriteEndElement();
}
}
public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
class WriteBase64AsyncResult : ScheduleActionItemAsyncResult
{
byte[] buffer;
int index;
int count;
XmlDictionaryWriter writer;
public WriteBase64AsyncResult(byte[] buffer, int index, int count, XmlDictionaryWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
Fx.Assert(writer != null, "writer should never be null");
this.buffer = buffer;
this.index = index;
this.count = count;
this.writer = writer;
Schedule();
}
protected override void OnDoWork()
{
this.writer.WriteBase64(this.buffer, this.index, this.count);
}
}
class XmlWrappedWriter : XmlDictionaryWriter
{
XmlWriter writer;
int depth;
int prefix;
public XmlWrappedWriter(XmlWriter writer)
{
this.writer = writer;
this.depth = 0;
}
public override void Close()
{
writer.Close();
}
public override void Flush()
{
writer.Flush();
}
public override string LookupPrefix(string namespaceUri)
{
return writer.LookupPrefix(namespaceUri);
}
public override void WriteAttributes(XmlReader reader, bool defattr)
{
writer.WriteAttributes(reader, defattr);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
writer.WriteBase64(buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
writer.WriteBinHex(buffer, index, count);
}
public override void WriteCData(string text)
{
writer.WriteCData(text);
}
public override void WriteCharEntity(char ch)
{
writer.WriteCharEntity(ch);
}
public override void WriteChars(char[] buffer, int index, int count)
{
writer.WriteChars(buffer, index, count);
}
public override void WriteComment(string text)
{
writer.WriteComment(text);
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
writer.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteEndAttribute()
{
writer.WriteEndAttribute();
}
public override void WriteEndDocument()
{
writer.WriteEndDocument();
}
public override void WriteEndElement()
{
writer.WriteEndElement();
this.depth--;
}
public override void WriteEntityRef(string name)
{
writer.WriteEntityRef(name);
}
public override void WriteFullEndElement()
{
writer.WriteFullEndElement();
}
public override void WriteName(string name)
{
writer.WriteName(name);
}
public override void WriteNmToken(string name)
{
writer.WriteNmToken(name);
}
public override void WriteNode(XmlReader reader, bool defattr)
{
writer.WriteNode(reader, defattr);
}
public override void WriteProcessingInstruction(string name, string text)
{
writer.WriteProcessingInstruction(name, text);
}
public override void WriteQualifiedName(string localName, string namespaceUri)
{
writer.WriteQualifiedName(localName, namespaceUri);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
writer.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
writer.WriteRaw(data);
}
public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
{
writer.WriteStartAttribute(prefix, localName, namespaceUri);
this.prefix++;
}
public override void WriteStartDocument()
{
writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
writer.WriteStartDocument(standalone);
}
public override void WriteStartElement(string prefix, string localName, string namespaceUri)
{
writer.WriteStartElement(prefix, localName, namespaceUri);
this.depth++;
this.prefix = 1;
}
public override WriteState WriteState
{
get
{
return writer.WriteState;
}
}
public override void WriteString(string text)
{
writer.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteWhitespace(string whitespace)
{
writer.WriteWhitespace(whitespace);
}
public override void WriteValue(object value)
{
writer.WriteValue(value);
}
public override void WriteValue(string value)
{
writer.WriteValue(value);
}
public override void WriteValue(bool value)
{
writer.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
writer.WriteValue(value);
}
public override void WriteValue(double value)
{
writer.WriteValue(value);
}
public override void WriteValue(int value)
{
writer.WriteValue(value);
}
public override void WriteValue(long value)
{
writer.WriteValue(value);
}
#if DECIMAL_FLOAT_API
public override void WriteValue(decimal value)
{
writer.WriteValue(value);
}
public override void WriteValue(float value)
{
writer.WriteValue(value);
}
#endif
public override void WriteXmlnsAttribute(string prefix, string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("namespaceUri");
if (prefix == null)
{
if (LookupPrefix(namespaceUri) != null)
return;
if (namespaceUri.Length == 0)
{
prefix = string.Empty;
}
else
{
string depthStr = this.depth.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
string prefixStr = this.prefix.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
prefix = string.Concat("d", depthStr, "p", prefixStr);
}
}
WriteAttributeString("xmlns", prefix, null, namespaceUri);
}
public override string XmlLang
{
get
{
return writer.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return writer.XmlSpace;
}
}
}
}
}
| |
using System.Collections.Generic;
using libLSD.Formats;
using libLSD.Formats.Packets;
using libLSD.Types;
using UnityEngine;
namespace LSDR.SDK.IO
{
/// <summary>
/// Contains numerous utility methods for converting data in original game format to formats Unity likes.
/// Utilises LibLSD to do this.
/// </summary>
public static class LibLSDUnity
{
// as it was in PSX datasheets
public const int VRAM_WIDTH = 2056;
public const int VRAM_HEIGHT = 512;
/// <summary>
/// A struct to store data from a PS1 TIM file.
/// </summary>
public struct TimData
{
public IColor[,] Colors;
public int Width;
public int Height;
}
public static List<GameObject> CreateGameObjectsFromMOM(MOM mom, Material mat)
{
var meshes = CreateMeshesFromTMD(mom.TMD);
List<GameObject> meshObjects = new List<GameObject>();
foreach (var mesh in meshes)
{
GameObject meshObj = new GameObject($"mesh {meshObjects.Count}");
MeshRenderer mr = meshObj.AddComponent<MeshRenderer>();
MeshFilter mf = meshObj.AddComponent<MeshFilter>();
mr.sharedMaterial = mat;
mf.sharedMesh = mesh;
meshObjects.Add(meshObj);
}
return meshObjects;
}
/// <summary>
/// Create a list of meshes based on the contents of a TMD model file.
/// </summary>
/// <param name="tmd">The loaded TMD to use.</param>
/// <returns>The loaded list of meshes.</returns>
public static List<Mesh> CreateMeshesFromTMD(TMD tmd)
{
List<Mesh> meshList = new List<Mesh>();
foreach (var obj in tmd.ObjectTable)
{
Mesh m = MeshFromTMDObject(obj);
meshList.Add(m);
}
return meshList;
}
/// <summary>
/// Create a mesh from an object stored inside a TMD model file.
/// </summary>
/// <param name="obj">The TMD object to create a mesh from.</param>
/// <returns>The Mesh created from the object.</returns>
public static Mesh MeshFromTMDObject(TMDObject obj)
{
// create the mesh, and lists of vertices, normals, colors, uvs, and indices
Mesh result = new Mesh();
List<Vector3> verts = new List<Vector3>();
List<Vector3> normals = new List<Vector3>();
List<Color32> colors = new List<Color32>();
List<Vector2> uvs = new List<Vector2>();
List<int> indices = new List<int>();
List<int> alphaBlendIndices = new List<int>(); // alpha blended polygons are stored in a submesh
// TMD objects are built from 'primitives'
foreach (var prim in obj.Primitives)
{
// currently only polygon primitives are supported
if (prim.Type != TMDPrimitivePacket.Types.POLYGON) continue;
// check which index list to use based on whether this primitive is alpha blended or not
List<int> indicesList = (prim.Options & TMDPrimitivePacket.OptionsFlags.AlphaBlended) != 0
? alphaBlendIndices
: indices;
// get interfaces for different packet types from LibLSD
ITMDPrimitivePacket primitivePacket = prim.PacketData;
ITMDTexturedPrimitivePacket texturedPrimitivePacket = prim.PacketData as ITMDTexturedPrimitivePacket;
ITMDColoredPrimitivePacket coloredPrimitivePacket = prim.PacketData as ITMDColoredPrimitivePacket;
ITMDLitPrimitivePacket litPrimitivePacket = prim.PacketData as ITMDLitPrimitivePacket;
// for each vertex in the primitive
List<int> polyIndices = new List<int>();
int[] packetIndices = new int[primitivePacket.Vertices.Length];
for (int i = 0; i < primitivePacket.Vertices.Length; i++)
{
// get its index into the vertices array
int vertIndex = primitivePacket.Vertices[i];
packetIndices[i] = verts.Count;
// create variables for each of the vertex types
Vec3 vertPos = obj.Vertices[vertIndex];
Vector3 vec3VertPos = new Vector3(vertPos.X, -vertPos.Y, vertPos.Z) / 2048f;
Color32 vertCol = Color.white;
Vector3 vertNorm = Vector3.zero;
Vector2 vertUV = Vector2.one;
// handle packet colour
if (coloredPrimitivePacket != null)
{
Vec3 packetVertCol =
coloredPrimitivePacket.Colors[coloredPrimitivePacket.Colors.Length > 1 ? i : 0];
vertCol = new Color(packetVertCol.X, packetVertCol.Y, packetVertCol.Z);
if (vertCol.r > 0 && vertCol.g > 0 && vertCol.b > 0
&& (prim.Options & TMDPrimitivePacket.OptionsFlags.Textured) == 0
&& (prim.Options & TMDPrimitivePacket.OptionsFlags.AlphaBlended) != 0)
{
vertCol.a = 127;
}
}
// handle packet normals
if (litPrimitivePacket != null)
{
TMDNormal packetVertNorm =
obj.Normals[litPrimitivePacket.Normals[litPrimitivePacket.Normals.Length > 1 ? i : 0]];
vertNorm = new Vector3(packetVertNorm.X, packetVertNorm.Y, packetVertNorm.Z);
}
// handle packet UVs
if (texturedPrimitivePacket != null)
{
// calculate which texture page we're on
int texPage = texturedPrimitivePacket.Texture.TexturePageNumber;
int texPageXPos = ((texPage % 16) * 128) - 640;
int texPageYPos = texPage < 16 ? 256 : 0;
// derive UV coords from the texture page
int uvIndex = i * 2;
int vramXPos = texPageXPos + texturedPrimitivePacket.UVs[uvIndex];
int vramYPos = texPageYPos + (256 - texturedPrimitivePacket.UVs[uvIndex + 1]);
float uCoord =
(vramXPos + 0.5f) / VRAM_WIDTH; // half-texel correction to prevent bleeding
float vCoord =
(vramYPos - 0.5f) / VRAM_HEIGHT; // half-texel correction to prevent bleeding
vertUV = new Vector2(uCoord, vCoord);
}
// add all computed aspects of vertex to lists
verts.Add(vec3VertPos);
normals.Add(vertNorm);
colors.Add(vertCol);
uvs.Add(vertUV);
}
// we want to add extra indices if this primitive is a quad (to triangulate)
bool isQuad = (prim.Options & TMDPrimitivePacket.OptionsFlags.Quad) != 0;
polyIndices.Add(packetIndices[0]);
polyIndices.Add(packetIndices[1]);
polyIndices.Add(packetIndices[2]);
if (isQuad)
{
polyIndices.Add(packetIndices[2]);
polyIndices.Add(packetIndices[1]);
polyIndices.Add(packetIndices[3]);
}
// if this primitive is double sided we want to add more vertices with opposite winding order
if ((prim.Flags & TMDPrimitivePacket.PrimitiveFlags.DoubleSided) != 0)
{
polyIndices.Add(packetIndices[1]);
polyIndices.Add(packetIndices[0]);
polyIndices.Add(packetIndices[2]);
if (isQuad)
{
polyIndices.Add(packetIndices[1]);
polyIndices.Add(packetIndices[2]);
polyIndices.Add(packetIndices[3]);
}
}
// add the indices to the list
indicesList.AddRange(polyIndices);
}
// set the mesh arrays
result.vertices = verts.ToArray();
result.normals = normals.ToArray();
result.colors32 = colors.ToArray();
result.uv = uvs.ToArray();
// regular mesh
if (indices.Count >= 3)
{
result.SetTriangles(indices, 0, false, 0);
}
// alpha blended mesh
if (alphaBlendIndices.Count >= 3)
{
result.subMeshCount = 2;
result.SetTriangles(alphaBlendIndices, 1, false, 0);
}
return result;
}
/// <summary>
/// Create an LBD tilemap GameObject from an LSD level tileset.
/// </summary>
/// <param name="lbd">The loaded LBD file.</param>
/// <returns>A GameObject containing loaded meshes for all tiles in their layout.</returns>
public static GameObject CreateLBDTileMap(LBD lbd)
{
GameObject lbdTilemap = new GameObject("LBD TileMap");
List<CombineInstance>
meshesCreated = new List<CombineInstance>(); // we're combining meshes into a collision mesh
// for each tile in the tilemap
int tileNo = 0;
foreach (LBDTile tile in lbd.TileLayout)
{
int x = tileNo / lbd.Header.TileWidth;
int y = tileNo % lbd.Header.TileWidth;
// create an LBD tile if we should draw it
if (tile.DrawTile)
{
GameObject lbdTile = createLBDTile(tile, lbd.ExtraTiles, x, y, lbd.Tiles, meshesCreated);
lbdTile.transform.SetParent(lbdTilemap.transform);
}
tileNo++;
}
// combine all tiles into mesh for efficient collision
Mesh combined = new Mesh();
combined.CombineMeshes(meshesCreated.ToArray(), true);
MeshCollider mc = lbdTilemap.AddComponent<MeshCollider>();
mc.sharedMesh = combined;
return lbdTilemap;
}
// create an LBD tile GameObject
private static GameObject createLBDTile(LBDTile tile,
LBDTile[] extraTiles,
int x,
int y,
TMD tilesTmd,
List<CombineInstance> meshesCreated)
{
// create the GameObject for the base tile
GameObject lbdTile = createSingleLBDTile(tile, x, y, tilesTmd, meshesCreated);
// now see if it has any extra tiles, and create those
LBDTile curTile = tile;
int i = 0;
while (curTile.ExtraTileIndex >= 0 && i <= 1)
{
LBDTile extraTile = extraTiles[curTile.ExtraTileIndex];
GameObject extraTileObj = createSingleLBDTile(extraTile, x, y, tilesTmd, meshesCreated);
extraTileObj.transform.SetParent(lbdTile.transform, true); // parent them to original tile
curTile = extraTile;
i++;
}
return lbdTile;
}
// create a single LBD tile GameObject (not including extra tiles)
private static GameObject createSingleLBDTile(LBDTile tile,
int x,
int y,
TMD tilesTmd,
List<CombineInstance> meshesCreated)
{
// create the GameObject and add/setup necessary components
GameObject lbdTile = new GameObject($"Tile {tile.TileType}");
MeshFilter mf = lbdTile.AddComponent<MeshFilter>();
MeshRenderer mr = lbdTile.AddComponent<MeshRenderer>();
TMDObject tileObj = tilesTmd.ObjectTable[tile.TileType];
Mesh tileMesh = MeshFromTMDObject(tileObj);
mf.mesh = tileMesh;
// the renderer needs to use virtual PSX Vram as its materials
//mr.sharedMaterials = new[] {PsxVram.VramMaterial, PsxVram.VramAlphaBlendMaterial};
// rotate the tile based on its direction
switch (tile.TileDirection)
{
case LBDTile.TileDirections.Deg90:
{
lbdTile.transform.Rotate(Vector3.up, 90);
break;
}
case LBDTile.TileDirections.Deg180:
{
lbdTile.transform.Rotate(Vector3.up, 180);
break;
}
case LBDTile.TileDirections.Deg270:
{
lbdTile.transform.Rotate(Vector3.up, 270);
break;
}
}
// set the tile's height
lbdTile.transform.position = new Vector3(x, -tile.TileHeight, y);
// make a CombineInstance for combining all tiles into one mesh later on
var localToWorldMatrix = lbdTile.transform.localToWorldMatrix;
CombineInstance combine = new CombineInstance()
{
mesh = tileMesh,
transform = localToWorldMatrix,
subMeshIndex = 0
};
meshesCreated.Add(combine);
// if tile has transparent part, do the same for the transparent mesh
if (tileMesh.subMeshCount > 1)
{
CombineInstance combineTrans = new CombineInstance()
{
mesh = tileMesh,
transform = localToWorldMatrix,
subMeshIndex = 1
};
meshesCreated.Add(combineTrans);
}
return lbdTile;
}
/// <summary>
/// Get a Unity Texture2D from a loaded TIX image archive.
/// </summary>
/// <param name="tix">The TIX file loaded.</param>
/// <returns>A Texture2D containing all images inside the TIX archive laid out as if in VRAM.</returns>
public static Texture2D GetTextureFromTIX(TIX tix)
{
// create a texture 2D with the required format
Texture2D tex = new Texture2D(VRAM_WIDTH, VRAM_HEIGHT, TextureFormat.ARGB32, false)
{
wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Point, mipMapBias = -0.5f, anisoLevel = 2
};
// fill the texture with a white colour
Color[] fill = new Color[VRAM_WIDTH * VRAM_HEIGHT];
for (int i = 0; i < fill.Length; i++)
{
fill[i] = new Color(1, 1, 1, 1);
}
tex.SetPixels(fill);
tex.Apply();
// for each image within the archive, load it and paint it on the 'canvas' we created above
foreach (var chunk in tix.Chunks)
{
foreach (var tim in chunk.TIMs)
{
var image = GetImageDataFromTIM(tim);
int actualXPos = (tim.PixelData.XPosition - 320) * 2;
int actualYPos = 512 - tim.PixelData.YPosition - image.Height;
tex.SetPixels(actualXPos, actualYPos, image.Width, image.Height, TimDataToColors(image));
tex.Apply();
}
}
return tex;
}
/// <summary>
/// Load a PS1 TIM image to a Unity Texture2D.
/// </summary>
/// <param name="tim">The loaded TIM image.</param>
/// <param name="clutIndex">The index of the CLUT to get the texture from.</param>
/// <param name="flip">Whether or not we should flip the loaded image.</param>
/// <returns></returns>
public static Texture2D GetTextureFromTIM(TIM tim, int clutIndex = 0, bool flip = true)
{
// get the image data
TimData data = GetImageDataFromTIM(tim, clutIndex);
// create a texture with the required format
Texture2D tex = new Texture2D(data.Width, data.Height, TextureFormat.ARGB32, false)
{
wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Point
};
// set the texture's pixels to the TIM pixels
tex.SetPixels(TimDataToColors(data, flip));
tex.Apply();
return tex;
}
/// <summary>
/// Get the pixels and width/height from a loaded TIM.
/// </summary>
/// <param name="tim">The loaded TIM.</param>
/// <param name="clutIndex">The index of the CLUT to get the texture from.</param>
/// <returns>TimData containing the TIM data.</returns>
public static TimData GetImageDataFromTIM(TIM tim, int clutIndex = 0)
{
TimData data;
data.Colors = tim.GetImage(clutIndex);
data.Width = data.Colors.GetLength(1);
data.Height = data.Colors.GetLength(0);
return data;
}
/// <summary>
/// Convert a TimData struct to an array of Colors to be used for setting pixels in a texture.
/// </summary>
/// <param name="data">The TimData to use.</param>
/// <param name="flip">Whether or not to flip the image.</param>
/// <returns>The Color array corresponding to this TIM data.</returns>
public static Color[] TimDataToColors(TimData data, bool flip = true)
{
// create the array
Color[] imageData = new Color[data.Colors.Length];
// iterate through each pixel and create its entry in the array
int i = 0;
if (flip)
{
for (int y = data.Height - 1; y >= 0; y--)
{
for (int x = 0; x < data.Width; x++)
{
IColor col = data.Colors[y, x];
imageData[i] = new Color(col.Red, col.Green,
col.Blue, col.Alpha);
i++;
}
}
}
else
{
for (int y = 0; y < data.Height; y++)
{
for (int x = 0; x < data.Width; x++)
{
IColor col = data.Colors[y, x];
imageData[i] = new Color(col.Red, col.Green,
col.Blue, col.Alpha);
i++;
}
}
}
return imageData;
}
}
}
| |
// 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.Specialized;
using System.Globalization;
using System.Net.Mail;
using System.Text;
namespace System.Net.Mime
{
/// <summary>
/// Summary description for HeaderCollection.
/// </summary>
internal class HeaderCollection : NameValueCollection
{
private MimeBasePart _part = null;
// default constructor
// intentionally override the default comparer in the derived base class
internal HeaderCollection() : base(StringComparer.OrdinalIgnoreCase)
{
}
public override void Remove(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name));
}
MailHeaderID id = MailHeaderInfo.GetID(name);
if (id == MailHeaderID.ContentType && _part != null)
{
_part.ContentType = null;
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
((MimePart)_part).ContentDisposition = null;
}
base.Remove(name);
}
public override string Get(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name));
}
MailHeaderID id = MailHeaderInfo.GetID(name);
if (id == MailHeaderID.ContentType && _part != null)
{
_part.ContentType.PersistIfNeeded(this, false);
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false);
}
return base.Get(name);
}
public override string[] GetValues(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name));
}
MailHeaderID id = MailHeaderInfo.GetID(name);
if (id == MailHeaderID.ContentType && _part != null)
{
_part.ContentType.PersistIfNeeded(this, false);
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false);
}
return base.GetValues(name);
}
internal void InternalRemove(string name) => base.Remove(name);
//set an existing header's value
internal void InternalSet(string name, string value) => base.Set(name, value);
//add a new header and set its value
internal void InternalAdd(string name, string value)
{
if (MailHeaderInfo.IsSingleton(name))
{
base.Set(name, value);
}
else
{
base.Add(name, value);
}
}
public override void Set(string name, string value)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (name == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name));
}
if (value == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(value)), nameof(value));
}
if (!MimeBasePart.IsAscii(name, false))
{
throw new FormatException(SR.InvalidHeaderName);
}
// normalize the case of well known headers
name = MailHeaderInfo.NormalizeCase(name);
MailHeaderID id = MailHeaderInfo.GetID(name);
value = value.Normalize(NormalizationForm.FormC);
if (id == MailHeaderID.ContentType && _part != null)
{
_part.ContentType.Set(value.ToLower(CultureInfo.InvariantCulture), this);
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
((MimePart)_part).ContentDisposition.Set(value.ToLower(CultureInfo.InvariantCulture), this);
}
else
{
base.Set(name, value);
}
}
public override void Add(string name, string value)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (name == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name));
}
if (value == string.Empty)
{
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(value)), nameof(value));
}
MailBnfHelper.ValidateHeaderName(name);
// normalize the case of well known headers
name = MailHeaderInfo.NormalizeCase(name);
MailHeaderID id = MailHeaderInfo.GetID(name);
value = value.Normalize(NormalizationForm.FormC);
if (id == MailHeaderID.ContentType && _part != null)
{
_part.ContentType.Set(value.ToLower(CultureInfo.InvariantCulture), this);
}
else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
{
((MimePart)_part).ContentDisposition.Set(value.ToLower(CultureInfo.InvariantCulture), this);
}
else
{
InternalAdd(name, value);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using GoCardless.Internals;
namespace GoCardless.Resources
{
/// <summary>
/// Represents a redirect flow resource.
///
/// Redirect flows enable you to use GoCardless' [hosted payment
/// pages](https://pay-sandbox.gocardless.com/AL000000AKFPFF) to set up
/// mandates with your customers. These pages are fully compliant and have
/// been translated into Danish, Dutch, French, German, Italian, Norwegian,
/// Portuguese, Slovak, Spanish and Swedish.
///
/// The overall flow is:
///
/// 1. You [create](#redirect-flows-create-a-redirect-flow) a redirect flow
/// for your customer, and redirect them to the returned redirect url, e.g.
/// `https://pay.gocardless.com/flow/RE123`.
///
/// 2. Your customer supplies their name, email, address, and bank account
/// details, and submits the form. This securely stores their details, and
/// redirects them back to your `success_redirect_url` with
/// `redirect_flow_id=RE123` in the querystring.
///
/// 3. You [complete](#redirect-flows-complete-a-redirect-flow) the redirect
/// flow, which creates a [customer](#core-endpoints-customers), [customer
/// bank account](#core-endpoints-customer-bank-accounts), and
/// [mandate](#core-endpoints-mandates), and returns the ID of the mandate.
/// You may wish to create a [subscription](#core-endpoints-subscriptions)
/// or [payment](#core-endpoints-payments) at this point.
///
/// Once you have [completed](#redirect-flows-complete-a-redirect-flow) the
/// redirect flow via the API, you should display a confirmation page to
/// your customer, confirming that their Direct Debit has been set up. You
/// can build your own page, or redirect to the one we provide in the
/// `confirmation_url` attribute of the redirect flow.
///
/// Redirect flows expire 30 minutes after they are first created. You
/// cannot complete an expired redirect flow.
/// </summary>
public class RedirectFlow
{
/// <summary>
/// The URL of a confirmation page, which you may optionally redirect
/// the customer to rather than use your own page, that confirms in
/// their chosen language that their Direct Debit has been set up
/// successfully. Only returned once the customer has set up their
/// mandate via the payment pages and the redirect flow has been
/// [completed](#redirect-flows-complete-a-redirect-flow), and only
/// available for 15 minutes from when you complete the redirect flow.
/// The structure of this URL may change at any time, so you should read
/// it directly from the API response.
/// </summary>
[JsonProperty("confirmation_url")]
public string ConfirmationUrl { get; set; }
/// <summary>
/// Fixed [timestamp](#api-usage-time-zones--dates), recording when this
/// resource was created.
/// </summary>
[JsonProperty("created_at")]
public DateTimeOffset? CreatedAt { get; set; }
/// <summary>
/// A description of the item the customer is paying for. This will be
/// shown on the hosted payment pages.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
/// <summary>
/// Unique identifier, beginning with "RE".
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// Resources linked to this RedirectFlow.
/// </summary>
[JsonProperty("links")]
public RedirectFlowLinks Links { get; set; }
/// <summary>
/// Mandate reference generated by GoCardless or submitted by an
/// integrator.
/// </summary>
[JsonProperty("mandate_reference")]
public string MandateReference { get; set; }
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<string, string> Metadata { get; set; }
/// <summary>
/// The URL of the hosted payment pages for this redirect flow. This is
/// the URL you should redirect your customer to.
/// </summary>
[JsonProperty("redirect_url")]
public string RedirectUrl { get; set; }
/// <summary>
/// The Direct Debit scheme of the mandate. If specified, the payment
/// pages will only allow the set-up of a mandate for the specified
/// scheme. It is recommended that you leave this blank so the most
/// appropriate scheme is picked based on the customer's bank account.
/// </summary>
[JsonProperty("scheme")]
public RedirectFlowScheme? Scheme { get; set; }
/// <summary>
/// The customer's session ID must be provided when the redirect flow is
/// set up and again when it is completed. This allows integrators to
/// ensure that the user who was originally sent to the GoCardless
/// payment pages is the one who has completed them.
/// </summary>
[JsonProperty("session_token")]
public string SessionToken { get; set; }
/// <summary>
/// The URL to redirect to upon successful mandate setup. You must use a
/// URL beginning `https` in the live environment.
/// </summary>
[JsonProperty("success_redirect_url")]
public string SuccessRedirectUrl { get; set; }
}
/// <summary>
/// Resources linked to this RedirectFlow
/// </summary>
public class RedirectFlowLinks
{
/// <summary>
/// The [creditor](#core-endpoints-creditors) for whom the mandate will
/// be created. The `name` of the creditor will be displayed on the
/// payment page.
/// </summary>
[JsonProperty("creditor")]
public string Creditor { get; set; }
/// <summary>
/// ID of [customer](#core-endpoints-customers) created by this redirect
/// flow.<br/>**Note**: this property will not be present until the
/// redirect flow has been successfully completed.
/// </summary>
[JsonProperty("customer")]
public string Customer { get; set; }
/// <summary>
/// ID of [customer bank
/// account](#core-endpoints-customer-bank-accounts) created by this
/// redirect flow.<br/>**Note**: this property will not be present until
/// the redirect flow has been successfully completed.
/// </summary>
[JsonProperty("customer_bank_account")]
public string CustomerBankAccount { get; set; }
/// <summary>
/// ID of [mandate](#core-endpoints-mandates) created by this redirect
/// flow.<br/>**Note**: this property will not be present until the
/// redirect flow has been successfully completed.
/// </summary>
[JsonProperty("mandate")]
public string Mandate { get; set; }
}
/// <summary>
/// The Direct Debit scheme of the mandate. If specified, the payment pages will only allow the
/// set-up of a mandate for the specified scheme. It is recommended that you leave this blank so
/// the most appropriate scheme is picked based on the customer's bank account.
/// </summary>
[JsonConverter(typeof(GcStringEnumConverter), (int)Unknown)]
public enum RedirectFlowScheme {
/// <summary>Unknown status</summary>
[EnumMember(Value = "unknown")]
Unknown = 0,
/// <summary>`scheme` with a value of "ach"</summary>
[EnumMember(Value = "ach")]
Ach,
/// <summary>`scheme` with a value of "autogiro"</summary>
[EnumMember(Value = "autogiro")]
Autogiro,
/// <summary>`scheme` with a value of "bacs"</summary>
[EnumMember(Value = "bacs")]
Bacs,
/// <summary>`scheme` with a value of "becs"</summary>
[EnumMember(Value = "becs")]
Becs,
/// <summary>`scheme` with a value of "becs_nz"</summary>
[EnumMember(Value = "becs_nz")]
BecsNz,
/// <summary>`scheme` with a value of "betalingsservice"</summary>
[EnumMember(Value = "betalingsservice")]
Betalingsservice,
/// <summary>`scheme` with a value of "pad"</summary>
[EnumMember(Value = "pad")]
Pad,
/// <summary>`scheme` with a value of "sepa_core"</summary>
[EnumMember(Value = "sepa_core")]
SepaCore,
}
}
| |
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
using ZXing.Common.ReedSolomon;
namespace ZXing.Aztec.Internal
{
/// <summary>
/// The main class which implements Aztec Code decoding -- as opposed to locating and extracting
/// the Aztec Code from an image.
/// </summary>
/// <author>David Olivier</author>
public sealed class Decoder
{
private enum Table
{
UPPER,
LOWER,
MIXED,
DIGIT,
PUNCT,
BINARY
}
private static readonly String[] UPPER_TABLE =
{
"CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS"
};
private static readonly String[] LOWER_TABLE =
{
"CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS"
};
private static readonly String[] MIXED_TABLE =
{
"CTRL_PS", " ", "\x1", "\x2", "\x3", "\x4", "\x5", "\x6", "\x7", "\b", "\t", "\n",
"\xB", "\f", "\r", "\x1B", "\x1C", "\x1D", "\x1E", "\x1F", "@", "\\", "^", "_",
"`", "|", "~", "\x7F", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS"
};
private static readonly String[] PUNCT_TABLE =
{
"FLG(n)", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")",
"*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL"
};
private static readonly String[] DIGIT_TABLE =
{
"CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US"
};
private static Encoding DEFAULT_ENCODING = AztecWriter.DEFAULT_CHARSET;
private static readonly IDictionary<Table, String[]> codeTables = new Dictionary<Table, String[]>
{
{Table.UPPER, UPPER_TABLE},
{Table.LOWER, LOWER_TABLE},
{Table.MIXED, MIXED_TABLE},
{Table.PUNCT, PUNCT_TABLE},
{Table.DIGIT, DIGIT_TABLE},
{Table.BINARY, null}
};
private static readonly IDictionary<char, Table> codeTableMap = new Dictionary<char, Table>
{
{'U', Table.UPPER},
{'L', Table.LOWER},
{'M', Table.MIXED},
{'P', Table.PUNCT},
{'D', Table.DIGIT},
{'B', Table.BINARY}
};
private AztecDetectorResult ddata;
/// <summary>
/// Decodes the specified detector result.
/// </summary>
/// <param name="detectorResult">The detector result.</param>
/// <returns></returns>
public DecoderResult decode(AztecDetectorResult detectorResult)
{
ddata = detectorResult;
var matrix = detectorResult.Bits;
var rawbits = extractBits(matrix);
if (rawbits == null)
return null;
var correctedBits = correctBits(rawbits);
if (correctedBits == null)
return null;
var result = getEncodedData(correctedBits.correctBits);
if (result == null)
return null;
var rawBytes = convertBoolArrayToByteArray(correctedBits.correctBits);
var decoderResult = new DecoderResult(rawBytes, correctedBits.correctBits.Length, result, null, String.Format("{0}", correctedBits.ecLevel));
return decoderResult;
}
/// <summary>
/// This method is used for testing the high-level encoder
/// </summary>
/// <param name="correctedBits"></param>
/// <returns></returns>
public static String highLevelDecode(bool[] correctedBits)
{
return getEncodedData(correctedBits);
}
/// <summary>
/// Gets the string encoded in the aztec code bits
/// </summary>
/// <param name="correctedBits">The corrected bits.</param>
/// <returns>the decoded string</returns>
private static String getEncodedData(bool[] correctedBits)
{
var endIndex = correctedBits.Length;
var latchTable = Table.UPPER; // table most recently latched to
var shiftTable = Table.UPPER; // table to use for the next read
var strTable = UPPER_TABLE;
var index = 0;
// Final decoded string result
// (correctedBits-5) / 4 is an upper bound on the size (all-digit result)
var result = new StringBuilder((correctedBits.Length - 5) / 4);
// Intermediary buffer of decoded bytes, which is decoded into a string and flushed
// when character encoding changes (ECI) or input ends.
using (var decodedBytes = new System.IO.MemoryStream())
{
var encoding = DEFAULT_ENCODING;
while (index < endIndex)
{
if (shiftTable == Table.BINARY)
{
if (endIndex - index < 5)
{
break;
}
int length = readCode(correctedBits, index, 5);
index += 5;
if (length == 0)
{
if (endIndex - index < 11)
{
break;
}
length = readCode(correctedBits, index, 11) + 31;
index += 11;
}
for (int charCount = 0; charCount < length; charCount++)
{
if (endIndex - index < 8)
{
index = endIndex; // Force outer loop to exit
break;
}
int code = readCode(correctedBits, index, 8);
decodedBytes.WriteByte((byte)code);
index += 8;
}
// Go back to whatever mode we had been in
shiftTable = latchTable;
strTable = codeTables[shiftTable];
}
else
{
int size = shiftTable == Table.DIGIT ? 4 : 5;
if (endIndex - index < size)
{
break;
}
int code = readCode(correctedBits, index, size);
index += size;
String str = getCharacter(strTable, code);
if ("FLG(n)".Equals(str))
{
if (endIndex - index < 3)
{
break;
}
int n = readCode(correctedBits, index, 3);
index += 3;
// flush bytes, FLG changes state
if (decodedBytes.Length > 0)
{
var byteArray = decodedBytes.ToArray();
result.Append(encoding.GetString(byteArray, 0, byteArray.Length));
decodedBytes.SetLength(0);
}
switch (n)
{
case 0:
result.Append((char)29); // translate FNC1 as ASCII 29
break;
case 7:
throw new FormatException("FLG(7) is reserved and illegal");
default:
// ECI is decimal integer encoded as 1-6 codes in DIGIT mode
int eci = 0;
if (endIndex - index < 4 * n)
{
break;
}
while (n-- > 0)
{
int nextDigit = readCode(correctedBits, index, 4);
index += 4;
if (nextDigit < 2 || nextDigit > 11)
{
throw new FormatException("Not a decimal digit");
}
eci = eci * 10 + (nextDigit - 2);
}
CharacterSetECI charsetECI = CharacterSetECI.getCharacterSetECIByValue(eci);
encoding = CharacterSetECI.getEncoding(charsetECI);
if (encoding == null)
{
throw new FormatException("Encoding for ECI " + eci + " can't be resolved");
}
break;
}
// Go back to whatever mode we had been in
shiftTable = latchTable;
strTable = codeTables[shiftTable];
}
else if (str.StartsWith("CTRL_"))
{
// Table changes
// ISO/IEC 24778:2008 prescribes ending a shift sequence in the mode from which it was invoked.
// That's including when that mode is a shift.
// Our test case dlusbs.png for issue #642 exercises that.
latchTable = shiftTable; // Latch the current mode, so as to return to Upper after U/S B/S
shiftTable = getTable(str[5]);
strTable = codeTables[shiftTable];
if (str[6] == 'L')
{
latchTable = shiftTable;
}
}
else
{
// Though stored as a table of strings for convenience, codes actually represent 1 or 2 *bytes*.
#if (PORTABLE || NETSTANDARD1_0 || NETSTANDARD1_1 || NETFX_CORE)
var b = StringUtils.PLATFORM_DEFAULT_ENCODING_T.GetBytes(str);
#else
var b = Encoding.ASCII.GetBytes(str);
#endif
decodedBytes.Write(b, 0, b.Length);
// Go back to whatever mode we had been in
shiftTable = latchTable;
strTable = codeTables[shiftTable];
}
}
}
if (decodedBytes.Length > 0)
{
var byteArray = decodedBytes.ToArray();
result.Append(encoding.GetString(byteArray, 0, byteArray.Length));
}
}
return result.ToString();
}
/// <summary>
/// gets the table corresponding to the char passed
/// </summary>
/// <param name="t">The t.</param>
/// <returns></returns>
private static Table getTable(char t)
{
if (!codeTableMap.ContainsKey(t))
return codeTableMap['U'];
return codeTableMap[t];
}
/// <summary>
/// Gets the character (or string) corresponding to the passed code in the given table
/// </summary>
/// <param name="table">the table used</param>
/// <param name="code">the code of the character</param>
/// <returns></returns>
private static String getCharacter(String[] table, int code)
{
return table[code];
}
internal sealed class CorrectedBitsResult
{
public bool[] correctBits;
public int ecLevel;
public CorrectedBitsResult(bool[] correctBits, int ecLevel)
{
this.correctBits = correctBits;
this.ecLevel = ecLevel;
}
}
/// <summary>
///Performs RS error correction on an array of bits.
/// </summary>
/// <param name="rawbits">The rawbits.</param>
/// <returns>the corrected array</returns>
private CorrectedBitsResult correctBits(bool[] rawbits)
{
GenericGF gf;
int codewordSize;
if (ddata.NbLayers <= 2)
{
codewordSize = 6;
gf = GenericGF.AZTEC_DATA_6;
}
else if (ddata.NbLayers <= 8)
{
codewordSize = 8;
gf = GenericGF.AZTEC_DATA_8;
}
else if (ddata.NbLayers <= 22)
{
codewordSize = 10;
gf = GenericGF.AZTEC_DATA_10;
}
else
{
codewordSize = 12;
gf = GenericGF.AZTEC_DATA_12;
}
int numDataCodewords = ddata.NbDatablocks;
int numCodewords = rawbits.Length / codewordSize;
if (numCodewords < numDataCodewords)
return null;
int offset = rawbits.Length % codewordSize;
int numECCodewords = numCodewords - numDataCodewords;
int[] dataWords = new int[numCodewords];
for (int i = 0; i < numCodewords; i++, offset += codewordSize)
{
dataWords[i] = readCode(rawbits, offset, codewordSize);
}
var rsDecoder = new ReedSolomonDecoder(gf);
if (!rsDecoder.decode(dataWords, numECCodewords))
return null;
// Now perform the unstuffing operation.
// First, count how many bits are going to be thrown out as stuffing
int mask = (1 << codewordSize) - 1;
int stuffedBits = 0;
for (int i = 0; i < numDataCodewords; i++)
{
int dataWord = dataWords[i];
if (dataWord == 0 || dataWord == mask)
{
return null;
}
else if (dataWord == 1 || dataWord == mask - 1)
{
stuffedBits++;
}
}
// Now, actually unpack the bits and remove the stuffing
bool[] correctedBits = new bool[numDataCodewords * codewordSize - stuffedBits];
int index = 0;
for (int i = 0; i < numDataCodewords; i++)
{
int dataWord = dataWords[i];
if (dataWord == 1 || dataWord == mask - 1)
{
// next codewordSize-1 bits are all zeros or all ones
SupportClass.Fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);
index += codewordSize - 1;
}
else
{
for (int bit = codewordSize - 1; bit >= 0; --bit)
{
correctedBits[index++] = (dataWord & (1 << bit)) != 0;
}
}
}
if (index != correctedBits.Length)
return null;
return new CorrectedBitsResult(correctedBits, 100 * (numCodewords - numDataCodewords) / numCodewords);
}
/// <summary>
/// Gets the array of bits from an Aztec Code matrix
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns>the array of bits</returns>
private bool[] extractBits(BitMatrix matrix)
{
bool compact = ddata.Compact;
int layers = ddata.NbLayers;
int baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines
int[] alignmentMap = new int[baseMatrixSize];
bool[] rawbits = new bool[totalBitsInLayer(layers, compact)];
if (compact)
{
for (int i = 0; i < alignmentMap.Length; i++)
{
alignmentMap[i] = i;
}
}
else
{
int matrixSize = baseMatrixSize + 1 + 2 * ((baseMatrixSize / 2 - 1) / 15);
int origCenter = baseMatrixSize / 2;
int center = matrixSize / 2;
for (int i = 0; i < origCenter; i++)
{
int newOffset = i + i / 15;
alignmentMap[origCenter - i - 1] = center - newOffset - 1;
alignmentMap[origCenter + i] = center + newOffset + 1;
}
}
for (int i = 0, rowOffset = 0; i < layers; i++)
{
int rowSize = (layers - i) * 4 + (compact ? 9 : 12);
// The top-left most point of this layer is <low, low> (not including alignment lines)
int low = i * 2;
// The bottom-right most point of this layer is <high, high> (not including alignment lines)
int high = baseMatrixSize - 1 - low;
// We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows
for (int j = 0; j < rowSize; j++)
{
int columnOffset = j * 2;
for (int k = 0; k < 2; k++)
{
// left column
rawbits[rowOffset + columnOffset + k] =
matrix[alignmentMap[low + k], alignmentMap[low + j]];
// bottom row
rawbits[rowOffset + 2 * rowSize + columnOffset + k] =
matrix[alignmentMap[low + j], alignmentMap[high - k]];
// right column
rawbits[rowOffset + 4 * rowSize + columnOffset + k] =
matrix[alignmentMap[high - k], alignmentMap[high - j]];
// top row
rawbits[rowOffset + 6 * rowSize + columnOffset + k] =
matrix[alignmentMap[high - j], alignmentMap[low + k]];
}
}
rowOffset += rowSize * 8;
}
return rawbits;
}
/// <summary>
/// Reads a code of given length and at given index in an array of bits
/// </summary>
/// <param name="rawbits">The rawbits.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <returns></returns>
private static int readCode(bool[] rawbits, int startIndex, int length)
{
int res = 0;
for (int i = startIndex; i < startIndex + length; i++)
{
res <<= 1;
if (rawbits[i])
{
res |= 1;
}
}
return res;
}
/// <summary>
/// Reads a code of length 8 in an array of bits, padding with zeros
/// </summary>
/// <param name="rawbits"></param>
/// <param name="startIndex"></param>
/// <returns></returns>
private static byte readByte(bool[] rawbits, int startIndex)
{
int n = rawbits.Length - startIndex;
if (n >= 8)
{
return (byte)readCode(rawbits, startIndex, 8);
}
return (byte)(readCode(rawbits, startIndex, n) << (8 - n));
}
/// <summary>
/// Packs a bit array into bytes, most significant bit first
/// </summary>
/// <param name="boolArr"></param>
/// <returns></returns>
internal static byte[] convertBoolArrayToByteArray(bool[] boolArr)
{
byte[] byteArr = new byte[(boolArr.Length + 7) / 8];
for (int i = 0; i < byteArr.Length; i++)
{
byteArr[i] = readByte(boolArr, 8 * i);
}
return byteArr;
}
private static int totalBitsInLayer(int layers, bool compact)
{
return ((compact ? 88 : 112) + 16 * layers) * layers;
}
}
}
| |
/*
* Unity VSCode Support
*
* Seamless support for Microsoft Visual Studio Code in Unity
*
* Version:
* 2.9
*
* Authors:
* Matthew Davey <matthew.davey@dotbunny.com>
*/
namespace dotBunny.Unity
{
using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public static class VSCode
{
/// <summary>
/// Current Version Number
/// </summary>
public const float Version = 2.9f;
/// <summary>
/// Current Version Code
/// </summary>
public const string VersionCode = "-RELEASE";
/// <summary>
/// Additional File Extensions
/// </summary>
public const string FileExtensions = ".ts, .bjs, .javascript, .json, .html, .shader, .template";
/// <summary>
/// Download URL for Unity Debbuger
/// </summary>
public const string UnityDebuggerURL = "https://unity.gallery.vsassets.io/_apis/public/gallery/publisher/unity/extension/unity-debug/latest/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage";
// Used to keep Unity from crashing when the editor is quit
static bool alreadyFixedPreferences;
#region Properties
/// <summary>
/// Path to VSCode executable
public static string CodePath
{
get
{
string current = EditorPrefs.GetString("VSCode_CodePath", "");
if(current == "" || !VSCodeExists(current))
{
//Value not set, set to "" or current path is invalid, try to autodetect it
//If autodetect fails, a error will be printed and the default value set
EditorPrefs.SetString("VSCode_CodePath", AutodetectCodePath());
//If its not installed or the install folder isn't a "normal" one,
//AutodetectCodePath will print a error message to the Unity Console
}
return EditorPrefs.GetString("VSCode_CodePath", current);
}
set
{
EditorPrefs.SetString("VSCode_CodePath", value);
}
}
/// <summary>
/// Get Program Files Path
/// </summary>
/// <returns>The platforms "Program Files" path.</returns>
static string ProgramFilesx86()
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
/// <summary>
/// Get Program Files Path
/// </summary>
/// <returns>The platforms "Program Files" path.</returns>
static string ProgramFiles()
{
return Environment.GetEnvironmentVariable("ProgramFiles");
}
/// <summary>
/// Should debug information be displayed in the Unity terminal?
/// </summary>
public static bool Debug
{
get
{
return EditorPrefs.GetBool("VSCode_Debug", false);
}
set
{
EditorPrefs.SetBool("VSCode_Debug", value);
}
}
/// <summary>
/// Is the Visual Studio Code Integration Enabled?
/// </summary>
/// <remarks>
/// We do not want to automatically turn it on, for in larger projects not everyone is using VSCode
/// </remarks>
public static bool Enabled
{
get
{
return EditorPrefs.GetBool("VSCode_Enabled", false);
}
set
{
// When turning the plugin on, we should remove all the previous project files
if (!Enabled && value)
{
ClearProjectFiles();
}
EditorPrefs.SetBool("VSCode_Enabled", value);
}
}
public static bool UseUnityDebugger
{
get
{
return EditorPrefs.GetBool("VSCode_UseUnityDebugger", false);
}
set
{
if ( value != UseUnityDebugger ) {
// Set value
EditorPrefs.SetBool("VSCode_UseUnityDebugger", value);
// Do not write the launch JSON file because the debugger uses its own
if ( value ) {
WriteLaunchFile = false;
}
// Update launch file
UpdateLaunchFile();
}
}
}
/// <summary>
/// When opening a project in Unity, should it automatically open in VS Code.
/// </summary>
public static bool AutoOpenEnabled
{
get
{
return EditorPrefs.GetBool("VSCode_AutoOpenEnabled", false);
}
set
{
EditorPrefs.SetBool("VSCode_AutoOpenEnabled", value);
}
}
/// <summary>
/// Should the launch.json file be written?
/// </summary>
/// <remarks>
/// Useful to disable if someone has their own custom one rigged up
/// </remarks>
public static bool WriteLaunchFile
{
get
{
return EditorPrefs.GetBool("VSCode_WriteLaunchFile", true);
}
set
{
EditorPrefs.SetBool("VSCode_WriteLaunchFile", value);
}
}
/// <summary>
/// Should the plugin automatically update itself.
/// </summary>
static bool AutomaticUpdates
{
get
{
return EditorPrefs.GetBool("VSCode_AutomaticUpdates", false);
}
set
{
EditorPrefs.SetBool("VSCode_AutomaticUpdates", value);
}
}
static float GitHubVersion
{
get
{
return EditorPrefs.GetFloat("VSCode_GitHubVersion", Version);
}
set
{
EditorPrefs.SetFloat("VSCode_GitHubVersion", value);
}
}
/// <summary>
/// When was the last time that the plugin was updated?
/// </summary>
static DateTime LastUpdate
{
get
{
// Feature creation date.
DateTime lastTime = new DateTime(2015, 10, 8);
if (EditorPrefs.HasKey("VSCode_LastUpdate"))
{
DateTime.TryParse(EditorPrefs.GetString("VSCode_LastUpdate"), out lastTime);
}
return lastTime;
}
set
{
EditorPrefs.SetString("VSCode_LastUpdate", value.ToString());
}
}
/// <summary>
/// Quick reference to the VSCode launch settings file
/// </summary>
static string LaunchPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "launch.json";
}
}
/// <summary>
/// Should the parent of the unity project be used as the workspace directory.
/// </summary>
/// <remarks>
/// Usefull if you have your unity project as a sub-directory.
/// </remarks>
static bool UseParentWorkspace
{
get
{
return EditorPrefs.GetBool("VSCode_UseParentWorkspace", false);
}
set
{
EditorPrefs.SetBool("VSCode_UseParentWorkspace", value);
}
}
/// <summary>
/// The full path to the Unity project.
/// </summary>
static string UnityProjectPath
{
get
{
return System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath);
}
}
/// <summary>
/// The full path to the workspace.
/// </summary>
static string WorkspacePath
{
get
{
return UseParentWorkspace ?
Directory.GetParent(UnityProjectPath).FullName :
UnityProjectPath;
}
}
/// <summary>
/// Should the script editor be reverted when quiting Unity.
/// </summary>
/// <remarks>
/// Useful for environments where you do not use VSCode for everything.
/// </remarks>
static bool RevertExternalScriptEditorOnExit
{
get
{
return EditorPrefs.GetBool("VSCode_RevertScriptEditorOnExit", true);
}
set
{
EditorPrefs.SetBool("VSCode_RevertScriptEditorOnExit", value);
}
}
/// <summary>
/// Quick reference to the VSCode settings folder
/// </summary>
static string SettingsFolder
{
get
{
return WorkspacePath + System.IO.Path.DirectorySeparatorChar + ".vscode";
}
}
static string SettingsPath
{
get
{
return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "settings.json";
}
}
static int UpdateTime
{
get
{
return EditorPrefs.GetInt("VSCode_UpdateTime", 7);
}
set
{
EditorPrefs.SetInt("VSCode_UpdateTime", value);
}
}
#endregion
/// <summary>
/// Integration Constructor
/// </summary>
static VSCode()
{
if (Enabled)
{
UpdateUnityPreferences(true);
UpdateLaunchFile();
// Add Update Check
DateTime targetDate = LastUpdate.AddDays(UpdateTime);
if (DateTime.Now >= targetDate && AutomaticUpdates)
{
CheckForUpdate();
}
// Open VS Code automatically when project is loaded
if (AutoOpenEnabled)
{
CheckForAutoOpen();
}
}
// Event for when script is reloaded
System.AppDomain.CurrentDomain.DomainUnload += System_AppDomain_CurrentDomain_DomainUnload;
}
static void System_AppDomain_CurrentDomain_DomainUnload(object sender, System.EventArgs e)
{
if (Enabled && RevertExternalScriptEditorOnExit)
{
UpdateUnityPreferences(false);
}
}
#region Public Members
/// <summary>
/// Force Unity To Write Project File
/// </summary>
/// <remarks>
/// Reflection!
/// </remarks>
public static void SyncSolution()
{
System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
SyncSolution.Invoke(null, null);
}
/// <summary>
/// Update the solution files so that they work with VS Code
/// </summary>
public static void UpdateSolution()
{
// No need to process if we are not enabled
if (!VSCode.Enabled)
{
return;
}
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Updating Solution & Project Files");
}
var currentDirectory = Directory.GetCurrentDirectory();
var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln");
var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
foreach (var filePath in solutionFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubSolutionContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
foreach (var filePath in projectFiles)
{
string content = File.ReadAllText(filePath);
content = ScrubProjectContent(content);
File.WriteAllText(filePath, content);
ScrubFile(filePath);
}
}
#endregion
#region Private Members
/// <summary>
/// Try to find automatically the installation of VSCode
/// </summary>
static string AutodetectCodePath()
{
string[] possiblePaths =
#if UNITY_EDITOR_OSX
{
"/Applications/Visual Studio Code.app",
"/Applications/Visual Studio Code - Insiders.app"
};
#elif UNITY_EDITOR_WIN
{
ProgramFiles() + Path.DirectorySeparatorChar + "Microsoft VS Code"
+ Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd",
ProgramFiles() + Path.DirectorySeparatorChar + "Microsoft VS Code Insiders"
+ Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code-insiders.cmd",
ProgramFilesx86() + Path.DirectorySeparatorChar + "Microsoft VS Code"
+ Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd",
ProgramFilesx86() + Path.DirectorySeparatorChar + "Microsoft VS Code Insiders"
+ Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code-insiders.cmd"
};
#else
{
"/usr/bin/code",
"/usr/bin/code-insiders",
"/bin/code",
"/usr/local/bin/code",
"/var/lib/flatpak/exports/bin/com.visualstudio.code",
"/snap/bin/code",
"/snap/bin/code-insiders"
};
#endif
for(int i = 0; i < possiblePaths.Length; i++)
{
if(VSCodeExists(possiblePaths[i]))
{
return possiblePaths[i];
}
}
PrintNotFound(possiblePaths[0]);
return possiblePaths[0]; //returns the default one, printing a warning message 'executable not found'
}
/// <summary>
/// Call VSCode with arguments
/// </summary>
static void CallVSCode(string args)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
if(!VSCodeExists(CodePath))
{
PrintNotFound(CodePath);
return;
}
#if UNITY_EDITOR_OSX
proc.StartInfo.FileName = "open";
// Check the path to see if there is "Insiders"
if (CodePath.Contains("Insiders"))
{
proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCodeInsiders\" --args " + args.Replace(@"\", @"\\");
}
else
{
proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCode\" --args " + args.Replace(@"\", @"\\");
}
proc.StartInfo.UseShellExecute = false;
#elif UNITY_EDITOR_WIN
proc.StartInfo.FileName = CodePath;
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
#else
proc.StartInfo.FileName = CodePath;
proc.StartInfo.Arguments = args.Replace(@"\", @"\\");
proc.StartInfo.UseShellExecute = false;
#endif
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
}
/// <summary>
/// Check for Updates with GitHub
/// </summary>
static void CheckForUpdate()
{
var fileContent = string.Empty;
EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f);
// Because were not a runtime framework, lets just use the simplest way of doing this
try
{
using (var webClient = new System.Net.WebClient())
{
fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs");
}
}
catch (Exception e)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] " + e.Message);
}
// Don't go any further if there is an error
return;
}
finally
{
EditorUtility.ClearProgressBar();
}
// Set the last update time
LastUpdate = DateTime.Now;
// Fix for oddity in downlo
if (fileContent.Substring(0, 2) != "/*")
{
int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase);
// Jump over junk characters
fileContent = fileContent.Substring(startPosition);
}
string[] fileExploded = fileContent.Split('\n');
if (fileExploded.Length > 7)
{
float github = Version;
if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github))
{
GitHubVersion = github;
}
if (github > Version)
{
var GUIDs = AssetDatabase.FindAssets("t:Script VSCode");
var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar +
AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar);
if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No"))
{
// Always make sure the file is writable
System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
fileInfo.IsReadOnly = false;
// Write update file
File.WriteAllText(path, fileContent);
// Force update on text file
AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate);
}
}
}
}
/// <summary>
/// Checks whether it should auto-open VSCode
/// </summary>
/// <remarks>
/// VSCode() gets called on Launch and Run, through IntializeOnLoad
/// https://docs.unity3d.com/ScriptReference/InitializeOnLoadAttribute.html
/// To make sure it only opens VSCode when Unity (re)launches (i.e. opens a project),
/// we compare the launch time, which we calculate using EditorApplication.timeSinceStartup.
/// </remarks>
static void CheckForAutoOpen()
{
double timeInSeconds = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
int unityLaunchTimeInSeconds = (int)(timeInSeconds - EditorApplication.timeSinceStartup);
int prevUnityLaunchTime = EditorPrefs.GetInt("VSCode_UnityLaunchTime", 0);
// If launch time has changed, then Unity was re-opened
if (unityLaunchTimeInSeconds > prevUnityLaunchTime) {
// Launch VSCode
VSCode.MenuOpenProject();
// Save new launch time
EditorPrefs.SetInt("VSCode_UnityLaunchTime", unityLaunchTimeInSeconds);
}
}
/// <summary>
/// Clear out any existing project files and lingering stuff that might cause problems
/// </summary>
static void ClearProjectFiles()
{
var currentDirectory = Directory.GetCurrentDirectory();
var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln");
var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
var unityProjectFiles = Directory.GetFiles(currentDirectory, "*.unityproj");
foreach (string solutionFile in solutionFiles)
{
File.Delete(solutionFile);
}
foreach (string projectFile in projectFiles)
{
File.Delete(projectFile);
}
foreach (string unityProjectFile in unityProjectFiles)
{
File.Delete(unityProjectFile);
}
// Replace with our clean files (only in Unity 5)
#if !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 && !UNITY_4_7
SyncSolution();
#endif
}
/// <summary>
/// Force Unity Preferences Window To Read From Settings
/// </summary>
static void FixUnityPreferences()
{
// I want that window, please and thank you
System.Type T = System.Type.GetType("UnityEditor.PreferencesWindow,UnityEditor");
if (EditorWindow.focusedWindow == null)
return;
// Only run this when the editor window is visible (cause its what screwed us up)
if (EditorWindow.focusedWindow.GetType() == T)
{
var window = EditorWindow.GetWindow(T, true, "Unity Preferences");
if (window == null)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] No Preferences Window Found (really?)");
}
return;
}
var invokerType = window.GetType();
var invokerMethod = invokerType.GetMethod("ReadPreferences",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (invokerMethod != null)
{
invokerMethod.Invoke(window, null);
}
else if (Debug)
{
UnityEngine.Debug.Log("[VSCode] No Reflection Method Found For Preferences");
}
}
}
/// <summary>
/// Determine what port Unity is listening for on Windows
/// </summary>
static int GetDebugPort()
{
#if UNITY_EDITOR_WIN
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "netstat";
process.StartInfo.Arguments = "-a -n -o -p TCP";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
foreach (string line in lines)
{
string[] tokens = Regex.Split(line, "\\s+");
if (tokens.Length > 4)
{
int test = -1;
int.TryParse(tokens[5], out test);
if (test > 1023)
{
try
{
var p = System.Diagnostics.Process.GetProcessById(test);
if (p.ProcessName == "Unity")
{
return test;
}
}
catch
{
}
}
}
}
#else
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "lsof";
process.StartInfo.Arguments = "-c /^Unity$/ -i 4tcp -a";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
// Not thread safe (yet!)
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
foreach (string line in lines)
{
int port = -1;
if (line.StartsWith("Unity"))
{
string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None);
if (portions.Length >= 2)
{
Regex digitsOnly = new Regex(@"[^\d]");
string cleanPort = digitsOnly.Replace(portions[1], "");
if (int.TryParse(cleanPort, out port))
{
if (port > -1)
{
return port;
}
}
}
}
}
#endif
return -1;
}
/// <summary>
/// Manually install the original Unity Debuger
/// </summary>
/// <remarks>
/// This should auto update to the latest.
/// </remarks>
static void InstallUnityDebugger()
{
EditorUtility.DisplayProgressBar("VSCode", "Downloading Unity Debugger ...", 0.1f);
byte[] fileContent;
try
{
using (var webClient = new System.Net.WebClient())
{
fileContent = webClient.DownloadData(UnityDebuggerURL);
}
}
catch (Exception e)
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] " + e.Message);
}
// Don't go any further if there is an error
return;
}
finally
{
EditorUtility.ClearProgressBar();
}
// Do we have a file to install?
if ( fileContent != null ) {
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".vsix";
File.WriteAllBytes(fileName, fileContent);
CallVSCode(fileName);
}
}
// HACK: This is in until Unity can figure out why MD keeps opening even though a different program is selected.
[MenuItem("Assets/Open C# Project In Code", false, 1000)]
static void MenuOpenProject()
{
// Force the project files to be sync
SyncSolution();
// Load Project
CallVSCode("\"" + WorkspacePath + "\"");
}
/// <summary>
/// Print a error message to the Unity Console about not finding the code executable
/// </summary>
static void PrintNotFound(string path)
{
UnityEngine.Debug.LogError("[VSCode] Code executable in '" + path + "' not found. Check your" +
"Visual Studio Code installation and insert the correct path in the Preferences menu.");
}
[MenuItem("Assets/Open C# Project In Code", true, 1000)]
static bool ValidateMenuOpenProject()
{
return Enabled;
}
/// <summary>
/// VS Code Integration Preferences Item
/// </summary>
/// <remarks>
/// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
/// </remarks>
[PreferenceItem("VSCode")]
static void VSCodePreferencesItem()
{
if (EditorApplication.isCompiling)
{
EditorGUILayout.HelpBox("Please wait for Unity to finish compiling. \nIf the window doesn't refresh, simply click on the window or move it around to cause a repaint to happen.", MessageType.Warning);
return;
}
EditorGUILayout.BeginVertical();
var developmentInfo = "Support development of this plugin, follow @reapazor and @dotbunny on Twitter.";
var versionInfo = string.Format("{0:0.00}", Version) + VersionCode + ", GitHub version @ " + string.Format("{0:0.00}", GitHubVersion);
EditorGUILayout.HelpBox(developmentInfo + " --- [ " + versionInfo + " ]", MessageType.None);
EditorGUI.BeginChangeCheck();
// Need the VS Code executable
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("VS Code Path", GUILayout.Width(75));
#if UNITY_5_3_OR_NEWER
CodePath = EditorGUILayout.DelayedTextField(CodePath, GUILayout.ExpandWidth(true));
#else
CodePath = EditorGUILayout.TextField(CodePath, GUILayout.ExpandWidth(true));
#endif
GUI.SetNextControlName("PathSetButton");
if(GUILayout.Button("...", GUILayout.Height(14), GUILayout.Width(20)))
{
GUI.FocusControl("PathSetButton");
string path = EditorUtility.OpenFilePanel( "Visual Studio Code Executable", "", "" );
if( path.Length != 0 && File.Exists(path) || Directory.Exists(path))
{
CodePath = path;
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
Enabled = EditorGUILayout.Toggle(new GUIContent("Enable Integration", "Should the integration work its magic for you?"), Enabled);
UseUnityDebugger = EditorGUILayout.Toggle(new GUIContent("Use Unity Debugger", "Should the integration integrate with Unity's VSCode Extension (must be installed)."), UseUnityDebugger);
AutoOpenEnabled = EditorGUILayout.Toggle(new GUIContent("Enable Auto Open", "When opening a project in Unity, should it automatically open in VS Code?"), AutoOpenEnabled);
EditorGUILayout.Space();
RevertExternalScriptEditorOnExit = EditorGUILayout.Toggle(new GUIContent("Revert Script Editor On Unload", "Should the external script editor setting be reverted to its previous setting on project unload? This is useful if you do not use Code with all your projects."),RevertExternalScriptEditorOnExit);
EditorGUILayout.Space();
UseParentWorkspace = EditorGUILayout.Toggle(new GUIContent("Parent as workspace", "Should the parent of the project be used as the workspace directory? Usefull if you have the Unity project in a subdirectory."),UseParentWorkspace);
Debug = EditorGUILayout.Toggle(new GUIContent("Output Messages To Console", "Should informational messages be sent to Unity's Console?"), Debug);
WriteLaunchFile = EditorGUILayout.Toggle(new GUIContent("Always Write Launch File", "Always write the launch.json settings when entering play mode?"), WriteLaunchFile);
EditorGUILayout.Space();
AutomaticUpdates = EditorGUILayout.Toggle(new GUIContent("Automatic Updates", "Should the plugin automatically update itself?"), AutomaticUpdates);
UpdateTime = EditorGUILayout.IntSlider(new GUIContent("Update Timer (Days)", "After how many days should updates be checked for?"), UpdateTime, 1, 31);
EditorGUILayout.Space();
EditorGUILayout.Space();
if (EditorGUI.EndChangeCheck())
{
UpdateUnityPreferences(Enabled);
// TODO: Force Unity To Reload Preferences
// This seems to be a hick up / issue
if (VSCode.Debug)
{
if (Enabled)
{
UnityEngine.Debug.Log("[VSCode] Integration Enabled");
}
else
{
UnityEngine.Debug.Log("[VSCode] Integration Disabled");
}
}
}
if (GUILayout.Button(new GUIContent("Force Update", "Check for updates to the plugin, right NOW!")))
{
CheckForUpdate();
EditorGUILayout.EndVertical();
return;
}
if (GUILayout.Button(new GUIContent("Write Workspace Settings", "Output a default set of workspace settings for VSCode to use, ignoring many different types of files.")))
{
WriteWorkspaceSettings();
EditorGUILayout.EndVertical();
return;
}
EditorGUILayout.Space();
if (UseUnityDebugger)
{
EditorGUILayout.HelpBox("In order for the \"Use Unity Debuggger\" option to function above, you need to have installed the Unity Debugger Extension for Visual Studio Code.", MessageType.Warning);
if (GUILayout.Button(new GUIContent("Install Unity Debugger", "Install the Unity Debugger Extension into Code")))
{
InstallUnityDebugger();
EditorGUILayout.EndVertical();
return;
}
}
EditorGUILayout.EndVertical();
}
/// <summary>
/// Asset Open Callback (from Unity)
/// </summary>
/// <remarks>
/// Called when Unity is about to open an asset.
/// </remarks>
[UnityEditor.Callbacks.OnOpenAssetAttribute()]
static bool OnOpenedAsset(int instanceID, int line)
{
// bail out if we are not using VSCode
if (!Enabled)
{
return false;
}
// current path without the asset folder
string appPath = UnityProjectPath;
// determine asset that has been double clicked in the project view
UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID);
// additional file extensions
string selectedFilePath = AssetDatabase.GetAssetPath(selected);
string selectedFileExt = Path.GetExtension(selectedFilePath);
if (selectedFileExt == null) {
selectedFileExt = String.Empty;
}
if (!String.IsNullOrEmpty(selectedFileExt)) {
selectedFileExt = selectedFileExt.ToLower();
}
// open supported object types
if (selected.GetType().ToString() == "UnityEditor.MonoScript" ||
selected.GetType().ToString() == "UnityEngine.Shader" ||
VSCode.FileExtensions.IndexOf(selectedFileExt, StringComparison.OrdinalIgnoreCase) >= 0)
{
string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected);
string args = null;
if (line == -1)
{
args = "\"" + WorkspacePath + "\" \"" + completeFilepath + "\" -r";
}
else
{
args = "\"" + WorkspacePath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r";
}
// call 'open'
CallVSCode(args);
return true;
}
// Didnt find a code file? let Unity figure it out
return false;
}
/// <summary>
/// Executed when the Editor's playmode changes allowing for capture of required data
/// </summary>
#if UNITY_2017_2_OR_NEWER
static void OnPlaymodeStateChanged(UnityEditor.PlayModeStateChange state)
#else
static void OnPlaymodeStateChanged()
#endif
{
if (UnityEngine.Application.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
{
UpdateLaunchFile();
}
}
/// <summary>
/// Detect when scripts are reloaded and relink playmode detection
/// </summary>
[UnityEditor.Callbacks.DidReloadScripts()]
static void OnScriptReload()
{
#if UNITY_2017_2_OR_NEWER
EditorApplication.playModeStateChanged -= OnPlaymodeStateChanged;
EditorApplication.playModeStateChanged += OnPlaymodeStateChanged;
#else
EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged;
EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged;
#endif
}
/// <summary>
/// Remove extra/erroneous lines from a file.
static void ScrubFile(string path)
{
string[] lines = File.ReadAllLines(path);
System.Collections.Generic.List<string> newLines = new System.Collections.Generic.List<string>();
for (int i = 0; i < lines.Length; i++)
{
// Check Empty
if (string.IsNullOrEmpty(lines[i].Trim()) || lines[i].Trim() == "\t" || lines[i].Trim() == "\t\t")
{
}
else
{
newLines.Add(lines[i]);
}
}
File.WriteAllLines(path, newLines.ToArray());
}
/// <summary>
/// Remove extra/erroneous data from project file (content).
/// </summary>
static string ScrubProjectContent(string content)
{
if (content.Length == 0)
return "";
#if !UNITY_EDITOR_WIN
// Moved to 3.5, 2.0 is legacy.
if (content.IndexOf("<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>") != -1)
{
content = Regex.Replace(content, "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>");
}
#endif
string targetPath = "";// "<TargetPath>Temp" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "</TargetPath>"; //OutputPath
string langVersion = "<LangVersion>default</LangVersion>";
bool found = true;
int location = 0;
string addedOptions = "";
int startLocation = -1;
int endLocation = -1;
int endLength = 0;
while (found)
{
startLocation = -1;
endLocation = -1;
endLength = 0;
addedOptions = "";
startLocation = content.IndexOf("<PropertyGroup", location);
if (startLocation != -1)
{
endLocation = content.IndexOf("</PropertyGroup>", startLocation);
endLength = (endLocation - startLocation);
if (endLocation == -1)
{
found = false;
continue;
}
else
{
found = true;
location = endLocation;
}
if (content.Substring(startLocation, endLength).IndexOf("<TargetPath>") == -1)
{
addedOptions += "\n\r\t" + targetPath + "\n\r";
}
if (content.Substring(startLocation, endLength).IndexOf("<LangVersion>") == -1)
{
addedOptions += "\n\r\t" + langVersion + "\n\r";
}
if (!string.IsNullOrEmpty(addedOptions))
{
content = content.Substring(0, endLocation) + addedOptions + content.Substring(endLocation);
}
}
else
{
found = false;
}
}
return content;
}
/// <summary>
/// Remove extra/erroneous data from solution file (content).
/// </summary>
static string ScrubSolutionContent(string content)
{
// Replace Solution Version
content = content.Replace(
"Microsoft Visual Studio Solution File, Format Version 11.00\r\n# Visual Studio 2008\r\n",
"\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 2012");
// Remove Solution Properties (Unity Junk)
int startIndex = content.IndexOf("GlobalSection(SolutionProperties) = preSolution");
if (startIndex != -1)
{
int endIndex = content.IndexOf("EndGlobalSection", startIndex);
content = content.Substring(0, startIndex) + content.Substring(endIndex + 16);
}
return content;
}
/// <summary>
/// Update Visual Studio Code Launch file
/// </summary>
static void UpdateLaunchFile()
{
if (!VSCode.Enabled)
{
return;
}
else if (VSCode.UseUnityDebugger)
{
if (!Directory.Exists(VSCode.SettingsFolder))
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
// Write out proper formatted JSON (hence no more SimpleJSON here)
string fileContent = "{\n\t\"version\": \"0.2.0\",\n\t\"configurations\": [\n\t\t{\n\t\t\t\"name\": \"Unity Editor\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Windows Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"OSX Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Linux Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"iOS Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Android Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\n\t\t}\n\t]\n}";
File.WriteAllText(VSCode.LaunchPath, fileContent);
}
else if (VSCode.WriteLaunchFile)
{
int port = GetDebugPort();
if (port > -1)
{
if (!Directory.Exists(VSCode.SettingsFolder))
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
// Write out proper formatted JSON (hence no more SimpleJSON here)
string fileContent = "{\n\t\"version\":\"0.2.0\",\n\t\"configurations\":[ \n\t\t{\n\t\t\t\"name\":\"Unity\",\n\t\t\t\"type\":\"mono\",\n\t\t\t\"request\":\"attach\",\n\t\t\t\"address\":\"localhost\",\n\t\t\t\"port\":" + port + "\n\t\t}\n\t]\n}";
File.WriteAllText(VSCode.LaunchPath, fileContent);
if (VSCode.Debug)
{
UnityEngine.Debug.Log("[VSCode] Debug Port Found (" + port + ")");
}
}
else
{
if (VSCode.Debug)
{
UnityEngine.Debug.LogWarning("[VSCode] Unable to determine debug port.");
}
}
}
}
/// <summary>
/// Update Unity Editor Preferences
/// </summary>
/// <param name="enabled">Should we turn on this party!</param>
static void UpdateUnityPreferences(bool enabled)
{
if (enabled)
{
// App
if (EditorPrefs.GetString("kScriptsDefaultApp") != CodePath)
{
EditorPrefs.SetString("VSCode_PreviousApp", EditorPrefs.GetString("kScriptsDefaultApp"));
}
EditorPrefs.SetString("kScriptsDefaultApp", CodePath);
// Arguments
if (EditorPrefs.GetString("kScriptEditorArgs") != "-r -g `$(File):$(Line)`")
{
EditorPrefs.SetString("VSCode_PreviousArgs", EditorPrefs.GetString("kScriptEditorArgs"));
}
EditorPrefs.SetString("kScriptEditorArgs", "-r -g `$(File):$(Line)`");
EditorPrefs.SetString("kScriptEditorArgs" + CodePath, "-r -g `$(File):$(Line)`");
// MonoDevelop Solution
if (EditorPrefs.GetBool("kMonoDevelopSolutionProperties", false))
{
EditorPrefs.SetBool("VSCode_PreviousMD", true);
}
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", false);
// Support Unity Proj (JS)
if (EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false))
{
EditorPrefs.SetBool("VSCode_PreviousUnityProj", true);
}
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", false);
if (!EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", false))
{
EditorPrefs.SetBool("VSCode_PreviousAttach", false);
}
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true);
}
else
{
// Restore previous app
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousApp")))
{
EditorPrefs.SetString("kScriptsDefaultApp", EditorPrefs.GetString("VSCode_PreviousApp"));
}
// Restore previous args
if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousArgs")))
{
EditorPrefs.SetString("kScriptEditorArgs", EditorPrefs.GetString("VSCode_PreviousArgs"));
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousMD", false))
{
EditorPrefs.SetBool("kMonoDevelopSolutionProperties", true);
}
// Restore MD setting
if (EditorPrefs.GetBool("VSCode_PreviousUnityProj", false))
{
EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", true);
}
// Always leave editor attaching on, I know, it solves the problem of needing to restart for this
// to actually work
EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true);
}
if (!alreadyFixedPreferences)
{
alreadyFixedPreferences = true;
FixUnityPreferences();
}
}
/// <summary>
/// Determines if the current path to the code executable is valid or not (exists)
/// </summary>
static bool VSCodeExists(string curPath)
{
#if UNITY_EDITOR_OSX
return System.IO.Directory.Exists(curPath);
#else
System.IO.FileInfo code = new System.IO.FileInfo(curPath);
return code.Exists;
#endif
}
/// <summary>
/// Write Default Workspace Settings
/// </summary>
static void WriteWorkspaceSettings()
{
if (Debug)
{
UnityEngine.Debug.Log("[VSCode] Workspace Settings Written");
}
if (!Directory.Exists(VSCode.SettingsFolder))
{
System.IO.Directory.CreateDirectory(VSCode.SettingsFolder);
}
string exclusions =
// Associations
"{\n" +
"\t\"files.associations\":\n" +
"\t{\n" +
"\t\t\"*.bjs\":\"javascript\",\n" +
"\t\t\"*.javascript\":\"javascript\"\n" +
"\t},\n" +
"\t\"files.exclude\":\n" +
"\t{\n" +
// Hidden Files
"\t\t\"**/.DS_Store\":true,\n" +
"\t\t\"**/.git\":true,\n" +
"\t\t\"**/.gitignore\":true,\n" +
"\t\t\"**/.gitattributes\":true,\n" +
"\t\t\"**/.gitmodules\":true,\n" +
"\t\t\"**/.svn\":true,\n" +
// Compressed Files
"\t\t\"**/*.zip\":true,\n" +
"\t\t\"**/*.gz\":true,\n" +
"\t\t\"**/*.7z\":true,\n" +
// Project Files
"\t\t\"**/*.booproj\":true,\n" +
"\t\t\"**/*.pidb\":true,\n" +
"\t\t\"**/*.suo\":true,\n" +
"\t\t\"**/*.user\":true,\n" +
"\t\t\"**/*.userprefs\":true,\n" +
"\t\t\"**/*.unityproj\":true,\n" +
"\t\t\"**/*.dll\":true,\n" +
"\t\t\"**/*.exe\":true,\n" +
// Media Files
"\t\t\"**/*.pdf\":true,\n" +
// Video
"\t\t\"**/*.mp4\":true,\n" +
// Audio
"\t\t\"**/*.mid\":true,\n" +
"\t\t\"**/*.midi\":true,\n" +
"\t\t\"**/*.wav\":true,\n" +
"\t\t\"**/*.mp3\":true,\n" +
"\t\t\"**/*.ogg\":true,\n" +
// Textures
"\t\t\"**/*.gif\":true,\n" +
"\t\t\"**/*.ico\":true,\n" +
"\t\t\"**/*.jpg\":true,\n" +
"\t\t\"**/*.jpeg\":true,\n" +
"\t\t\"**/*.png\":true,\n" +
"\t\t\"**/*.psd\":true,\n" +
"\t\t\"**/*.tga\":true,\n" +
"\t\t\"**/*.tif\":true,\n" +
"\t\t\"**/*.tiff\":true,\n" +
"\t\t\"**/*.hdr\":true,\n" +
"\t\t\"**/*.exr\":true,\n" +
// Models
"\t\t\"**/*.3ds\":true,\n" +
"\t\t\"**/*.3DS\":true,\n" +
"\t\t\"**/*.fbx\":true,\n" +
"\t\t\"**/*.FBX\":true,\n" +
"\t\t\"**/*.lxo\":true,\n" +
"\t\t\"**/*.LXO\":true,\n" +
"\t\t\"**/*.ma\":true,\n" +
"\t\t\"**/*.MA\":true,\n" +
"\t\t\"**/*.obj\":true,\n" +
"\t\t\"**/*.OBJ\":true,\n" +
// Unity File Types
"\t\t\"**/*.asset\":true,\n" +
"\t\t\"**/*.cubemap\":true,\n" +
"\t\t\"**/*.flare\":true,\n" +
"\t\t\"**/*.mat\":true,\n" +
"\t\t\"**/*.meta\":true,\n" +
"\t\t\"**/*.prefab\":true,\n" +
"\t\t\"**/*.unity\":true,\n" +
"\t\t\"**/*.anim\":true,\n" +
"\t\t\"**/*.controller\":true,\n" +
// Folders
"\t\t\"build/\":true,\n" +
"\t\t\"Build/\":true,\n" +
"\t\t\"Library/\":true,\n" +
"\t\t\"library/\":true,\n" +
"\t\t\"obj/\":true,\n" +
"\t\t\"Obj/\":true,\n" +
"\t\t\"ProjectSettings/\":true,\r" +
"\t\t\"temp/\":true,\n" +
"\t\t\"Temp/\":true\n" +
"\t}\n" +
"}";
// Dont like the replace but it fixes the issue with the JSON
File.WriteAllText(VSCode.SettingsPath, exclusions);
}
#endregion
}
/// <summary>
/// VSCode Asset AssetPostprocessor
/// <para>This will ensure any time that the project files are generated the VSCode versions will be made</para>
/// </summary>
/// <remarks>Undocumented Event</remarks>
public class VSCodeAssetPostprocessor : AssetPostprocessor
{
/// <summary>
/// On documented, project generation event callback
/// </summary>
private static void OnGeneratedCSProjectFiles()
{
// Force execution of VSCode update
VSCode.UpdateSolution();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WindowsAuthorizationService.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net;
using System.Security.Principal;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Security.Permissions;
using System.IO;
namespace System.DirectoryServices.ActiveDirectory
{
public enum DirectoryContextType
{
Domain = 0,
Forest = 1,
DirectoryServer = 2,
ConfigurationSet = 3,
ApplicationPartition = 4
}
public class DirectoryContext
{
private string _name = null;
private DirectoryContextType _contextType;
private NetworkCredential _credential = null;
internal string serverName = null;
internal bool usernameIsNull = false;
internal bool passwordIsNull = false;
private bool _validated = false;
private bool _contextIsValid = false;
internal static LoadLibrarySafeHandle ADHandle;
internal static LoadLibrarySafeHandle ADAMHandle;
#region constructors
static DirectoryContext()
{
// load ntdsapi.dll for AD and ADAM
GetLibraryHandle();
}
// Internal Constructors
internal void InitializeDirectoryContext(DirectoryContextType contextType, string name, string username, string password)
{
_name = name;
_contextType = contextType;
_credential = new NetworkCredential(username, password);
if (username == null)
{
usernameIsNull = true;
}
if (password == null)
{
passwordIsNull = true;
}
}
internal DirectoryContext(DirectoryContextType contextType, string name, DirectoryContext context)
{
_name = name;
_contextType = contextType;
if (context != null)
{
_credential = context.Credential;
this.usernameIsNull = context.usernameIsNull;
this.passwordIsNull = context.passwordIsNull;
}
else
{
_credential = new NetworkCredential(null, "", null);
this.usernameIsNull = true;
this.passwordIsNull = true;
}
}
internal DirectoryContext(DirectoryContext context)
{
_name = context.Name;
_contextType = context.ContextType;
_credential = context.Credential;
this.usernameIsNull = context.usernameIsNull;
this.passwordIsNull = context.passwordIsNull;
if (context.ContextType != DirectoryContextType.ConfigurationSet)
{
//
// only for configurationset, we select a server, so we should not copy over that
// information, for all other types, this is either the same as name of the target or if the target is netbios name
// (for domain and forest) it could be the dns name. We should copy over this information.
//
this.serverName = context.serverName;
}
}
#endregion constructors
#region public constructors
public DirectoryContext(DirectoryContextType contextType)
{
//
// this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain
// since all other types require the name to be specified
//
if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.OnlyDomainOrForest, nameof(contextType));
}
InitializeDirectoryContext(contextType, null, null, null);
}
public DirectoryContext(DirectoryContextType contextType, string name)
{
if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition)
{
throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(name));
}
InitializeDirectoryContext(contextType, name, null, null);
}
public DirectoryContext(DirectoryContextType contextType, string username, string password)
{
//
// this constructor can only be called for DirectoryContextType.Forest or DirectoryContextType.Domain
// since all other types require the name to be specified
//
if (contextType != DirectoryContextType.Domain && contextType != DirectoryContextType.Forest)
{
throw new ArgumentException(SR.OnlyDomainOrForest, nameof(contextType));
}
InitializeDirectoryContext(contextType, null, username, password);
}
public DirectoryContext(DirectoryContextType contextType, string name, string username, string password)
{
if (contextType < DirectoryContextType.Domain || contextType > DirectoryContextType.ApplicationPartition)
{
throw new InvalidEnumArgumentException(nameof(contextType), (int)contextType, typeof(DirectoryContextType));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (name.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(name));
}
InitializeDirectoryContext(contextType, name, username, password);
}
#endregion public methods
#region public properties
public string Name => _name;
public string UserName => usernameIsNull ? null : _credential.UserName;
internal string Password
{
get => passwordIsNull ? null : _credential.Password;
}
public DirectoryContextType ContextType => _contextType;
internal NetworkCredential Credential => _credential;
#endregion public properties
#region private methods
internal static bool IsContextValid(DirectoryContext context, DirectoryContextType contextType)
{
bool contextIsValid = false;
if ((contextType == DirectoryContextType.Domain) || ((contextType == DirectoryContextType.Forest) && (context.Name == null)))
{
string tmpTarget = context.Name;
if (tmpTarget == null)
{
// GetLoggedOnDomain returns the dns name of the logged on user's domain
context.serverName = GetLoggedOnDomain();
contextIsValid = true;
}
else
{
// check for domain
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, tmpTarget, null, (long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
context.serverName = domainControllerInfo.DomainName;
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid domain)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
context.serverName = domainControllerInfo.DomainName;
contextIsValid = true;
}
}
}
else if (contextType == DirectoryContextType.Forest)
{
Debug.Assert(context.Name != null);
// check for forest
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)(PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)((PrivateLocatorFlags.GCRequired | PrivateLocatorFlags.DirectoryServicesRequired)) | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DnsForestName != null);
context.serverName = domainControllerInfo.DnsForestName;
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid forest)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DnsForestName != null);
context.serverName = domainControllerInfo.DnsForestName;
contextIsValid = true;
}
}
else if (contextType == DirectoryContextType.ApplicationPartition)
{
Debug.Assert(context.Name != null);
// check for application partition
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, context.Name, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded | (long)LocatorOptions.ForceRediscovery, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
contextIsValid = true;
}
}
else if (errorCode == NativeMethods.ERROR_INVALID_DOMAIN_NAME_FORMAT)
{
// we can get this error if the target it server:port (not a valid application partition)
contextIsValid = false;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
else
{
contextIsValid = true;
}
}
else if (contextType == DirectoryContextType.DirectoryServer)
{
//
// if the servername contains a port number, then remove that
//
string tempServerName = null;
string portNumber;
tempServerName = Utils.SplitServerNameAndPortNumber(context.Name, out portNumber);
//
// this will validate that the name specified in the context is truely the name of a machine (and not of a domain)
//
DirectoryEntry de = new DirectoryEntry("WinNT://" + tempServerName + ",computer", context.UserName, context.Password, Utils.DefaultAuthType);
try
{
de.Bind(true);
contextIsValid = true;
}
catch (COMException e)
{
if ((e.ErrorCode == unchecked((int)0x80070035)) || (e.ErrorCode == unchecked((int)0x80070033)) || (e.ErrorCode == unchecked((int)0x80005000)))
{
// if this returns bad network path
contextIsValid = false;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
de.Dispose();
}
}
else
{
// no special validation for ConfigurationSet
contextIsValid = true;
}
return contextIsValid;
}
internal bool isRootDomain()
{
if (_contextType != DirectoryContextType.Forest)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.Forest);
_validated = true;
}
return _contextIsValid;
}
internal bool isDomain()
{
if (_contextType != DirectoryContextType.Domain)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.Domain);
_validated = true;
}
return _contextIsValid;
}
internal bool isNdnc()
{
if (_contextType != DirectoryContextType.ApplicationPartition)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.ApplicationPartition);
_validated = true;
}
return _contextIsValid;
}
internal bool isServer()
{
if (_contextType != DirectoryContextType.DirectoryServer)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.DirectoryServer);
_validated = true;
}
return _contextIsValid;
}
internal bool isADAMConfigSet()
{
if (_contextType != DirectoryContextType.ConfigurationSet)
return false;
if (!_validated)
{
_contextIsValid = IsContextValid(this, DirectoryContextType.ConfigurationSet);
_validated = true;
}
return _contextIsValid;
}
//
// this method is called when the forest name is explicitly specified
// and we want to check if that matches the current logged on forest
//
internal bool isCurrentForest()
{
bool result = false;
Debug.Assert(_name != null);
DomainControllerInfo domainControllerInfo = Locator.GetDomainControllerInfo(null, _name, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName));
DomainControllerInfo currentDomainControllerInfo;
string loggedOnDomain = GetLoggedOnDomain();
int errorCode = Locator.DsGetDcNameWrapper(null, loggedOnDomain, null, (long)(PrivateLocatorFlags.DirectoryServicesRequired | PrivateLocatorFlags.ReturnDNSName), out currentDomainControllerInfo);
if (errorCode == 0)
{
Debug.Assert(domainControllerInfo.DnsForestName != null);
Debug.Assert(currentDomainControllerInfo.DnsForestName != null);
result = (Utils.Compare(domainControllerInfo.DnsForestName, currentDomainControllerInfo.DnsForestName) == 0);
}
//
// if there is no forest associated with the logged on domain, then we return false
//
else if (errorCode != NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
return result;
}
internal bool useServerBind()
{
return ((ContextType == DirectoryContextType.DirectoryServer) || (ContextType == DirectoryContextType.ConfigurationSet));
}
internal string GetServerName()
{
if (serverName == null)
{
switch (_contextType)
{
case DirectoryContextType.ConfigurationSet:
{
AdamInstance adamInst = ConfigurationSet.FindAnyAdamInstance(this);
try
{
serverName = adamInst.Name;
}
finally
{
adamInst.Dispose();
}
break;
}
case DirectoryContextType.Domain:
case DirectoryContextType.Forest:
{
//
// if the target is not specified OR
// if the forest name was explicitly specified and the forest is the same as the current forest
// we want to find a DC in the current domain
//
if ((_name == null) || ((_contextType == DirectoryContextType.Forest) && (isCurrentForest())))
{
serverName = GetLoggedOnDomain();
}
else
{
serverName = GetDnsDomainName(_name);
}
break;
}
case DirectoryContextType.ApplicationPartition:
{
// if this is an appNC the target should not be null
Debug.Assert(_name != null);
serverName = _name;
break;
}
case DirectoryContextType.DirectoryServer:
{
// this should not happen (We should have checks for this earlier itself)
Debug.Assert(_name != null);
serverName = _name;
break;
}
default:
{
Debug.Fail("DirectoryContext::GetServerName - Unknown contextType");
break;
}
}
}
return serverName;
}
internal static string GetLoggedOnDomain()
{
string domainName = null;
NegotiateCallerNameRequest requestBuffer = new NegotiateCallerNameRequest();
int requestBufferLength = (int)Marshal.SizeOf(requestBuffer);
IntPtr pResponseBuffer = IntPtr.Zero;
NegotiateCallerNameResponse responseBuffer = new NegotiateCallerNameResponse();
int responseBufferLength;
int protocolStatus;
int result;
LsaLogonProcessSafeHandle lsaHandle;
//
// since we are using safe handles, we don't need to explicitly call NativeMethods.LsaDeregisterLogonProcess(lsaHandle)
//
result = NativeMethods.LsaConnectUntrusted(out lsaHandle);
if (result == 0)
{
//
// initialize the request buffer
//
requestBuffer.messageType = NativeMethods.NegGetCallerName;
result = NativeMethods.LsaCallAuthenticationPackage(lsaHandle, 0, requestBuffer, requestBufferLength, out pResponseBuffer, out responseBufferLength, out protocolStatus);
try
{
if (result == 0 && protocolStatus == 0)
{
Marshal.PtrToStructure(pResponseBuffer, responseBuffer);
//
// callerName is of the form domain\username
//
Debug.Assert((responseBuffer.callerName != null), "NativeMethods.LsaCallAuthenticationPackage returned null callerName.");
int index = responseBuffer.callerName.IndexOf('\\');
Debug.Assert((index != -1), "NativeMethods.LsaCallAuthenticationPackage returned callerName not in domain\\username format.");
domainName = responseBuffer.callerName.Substring(0, index);
}
else
{
if (result == NativeMethods.STATUS_QUOTA_EXCEEDED)
{
throw new OutOfMemoryException();
}
else if ((result == 0) && (UnsafeNativeMethods.LsaNtStatusToWinError(protocolStatus) == NativeMethods.ERROR_NO_SUCH_LOGON_SESSION))
{
// If this is a directory user, extract domain info from username
if (!Utils.IsSamUser())
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
int index = identity.Name.IndexOf('\\');
Debug.Assert(index != -1);
domainName = identity.Name.Substring(0, index);
}
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError((result != 0) ? result : protocolStatus));
}
}
}
finally
{
if (pResponseBuffer != IntPtr.Zero)
{
NativeMethods.LsaFreeReturnBuffer(pResponseBuffer);
}
}
}
else if (result == NativeMethods.STATUS_QUOTA_EXCEEDED)
{
throw new OutOfMemoryException();
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(result));
}
// If we're running as a local user (i.e. NT AUTHORITY\LOCAL SYSTEM, IIS APPPOOL\APPPoolIdentity, etc.),
// domainName will be null and we fall back to the machine's domain
domainName = GetDnsDomainName(domainName);
if (domainName == null)
{
//
// we should never get to this point here since we should have already verified that the context is valid
// by the time we get to this point
//
throw new ActiveDirectoryOperationException(SR.ContextNotAssociatedWithDomain);
}
return domainName;
}
internal static string GetDnsDomainName(string domainName)
{
DomainControllerInfo domainControllerInfo;
int errorCode = 0;
//
// Locator.DsGetDcNameWrapper internally passes the ReturnDNSName flag when calling DsGetDcName
//
errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// try again with force rediscovery
errorCode = Locator.DsGetDcNameWrapper(null, domainName, null, (long)((long)PrivateLocatorFlags.DirectoryServicesRequired | (long)LocatorOptions.ForceRediscovery), out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
return null;
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(domainControllerInfo != null);
Debug.Assert(domainControllerInfo.DomainName != null);
return domainControllerInfo.DomainName;
}
private static void GetLibraryHandle()
{
// first get AD handle
string systemPath = Environment.SystemDirectory;
IntPtr tempHandle = UnsafeNativeMethods.LoadLibrary(systemPath + "\\ntdsapi.dll");
if (tempHandle == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
else
{
ADHandle = new LoadLibrarySafeHandle(tempHandle);
}
// not get the ADAM handle
// got to the windows\adam directory
DirectoryInfo windowsDirectory = Directory.GetParent(systemPath);
tempHandle = UnsafeNativeMethods.LoadLibrary(windowsDirectory.FullName + "\\ADAM\\ntdsapi.dll");
if (tempHandle == (IntPtr)0)
{
ADAMHandle = ADHandle;
}
else
{
ADAMHandle = new LoadLibrarySafeHandle(tempHandle);
}
}
#endregion private methods
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TdsParserSafeHandles.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.ConstrainedExecution;
internal sealed class SNILoadHandle : SafeHandle {
internal static readonly SNILoadHandle SingletonInstance = new SNILoadHandle();
internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate ReadAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(ReadDispatcher);
internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate WriteAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(WriteDispatcher);
private readonly UInt32 _sniStatus = TdsEnums.SNI_UNINITIALIZED;
private readonly EncryptionOptions _encryptionOption;
private SNILoadHandle() : base(IntPtr.Zero, true) {
// SQL BU DT 346588 - from security review - SafeHandle guarantees this is only called once.
// The reason for the safehandle is guaranteed initialization and termination of SNI to
// ensure SNI terminates and cleans up properly.
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
_sniStatus = SNINativeMethodWrapper.SNIInitialize();
UInt32 value = 0;
// VSDevDiv 479597: If initialize fails, don't call QueryInfo.
if (TdsEnums.SNI_SUCCESS == _sniStatus) {
// Query OS to find out whether encryption is supported.
SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value);
}
_encryptionOption = (value == 0) ? EncryptionOptions.NOT_SUP : EncryptionOptions.OFF;
base.handle = (IntPtr) 1; // Initialize to non-zero dummy variable.
}
}
public override bool IsInvalid {
get {
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle() {
if (base.handle != IntPtr.Zero) {
if (TdsEnums.SNI_SUCCESS == _sniStatus) {
LocalDBAPI.ReleaseDLLHandles();
SNINativeMethodWrapper.SNITerminate();
}
base.handle = IntPtr.Zero;
}
return true;
}
public UInt32 SNIStatus {
get {
return _sniStatus;
}
}
public EncryptionOptions Options {
get {
return _encryptionOption;
}
}
static private void ReadDispatcher(IntPtr key, IntPtr packet, UInt32 error) {
// This is the app-domain dispatcher for all async read callbacks, It
// simply gets the state object from the key that it is passed, and
// calls the state object's read callback.
Debug.Assert(IntPtr.Zero != key, "no key passed to read callback dispatcher?");
if (IntPtr.Zero != key) {
// NOTE: we will get a null ref here if we don't get a key that
// contains a GCHandle to TDSParserStateObject; that is
// very bad, and we want that to occur so we can catch it.
GCHandle gcHandle = (GCHandle)key;
TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
if (null != stateObj) {
stateObj.ReadAsyncCallback(IntPtr.Zero, packet, error);
}
}
}
static private void WriteDispatcher(IntPtr key, IntPtr packet, UInt32 error) {
// This is the app-domain dispatcher for all async write callbacks, It
// simply gets the state object from the key that it is passed, and
// calls the state object's write callback.
Debug.Assert(IntPtr.Zero != key, "no key passed to write callback dispatcher?");
if (IntPtr.Zero != key) {
// NOTE: we will get a null ref here if we don't get a key that
// contains a GCHandle to TDSParserStateObject; that is
// very bad, and we want that to occur so we can catch it.
GCHandle gcHandle = (GCHandle)key;
TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
if (null != stateObj) {
stateObj.WriteAsyncCallback(IntPtr.Zero, packet, error);
}
}
}
}
internal sealed class SNIHandle : SafeHandle {
private readonly UInt32 _status = TdsEnums.SNI_UNINITIALIZED;
private readonly bool _fSync = false;
// creates a physical connection
internal SNIHandle(
SNINativeMethodWrapper.ConsumerInfo myInfo,
string serverName,
byte[] spnBuffer,
bool ignoreSniOpenTimeout,
int timeout,
out byte[] instanceName,
bool flushCache,
bool fSync,
bool fParallel,
TransparentNetworkResolutionState transparentNetworkResolutionState,
int totalTimeout)
: base(IntPtr.Zero, true) {
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
_fSync = fSync;
instanceName = new byte[256]; // Size as specified by netlibs.
if (ignoreSniOpenTimeout) {
//
timeout = Timeout.Infinite; // -1 == native SNIOPEN_TIMEOUT_VALUE / INFINITE
}
int transparentNetworkResolutionStateNo = (int)transparentNetworkResolutionState;
_status = SNINativeMethodWrapper.SNIOpenSyncEx(myInfo, serverName, ref base.handle,
spnBuffer, instanceName, flushCache, fSync, timeout, fParallel, transparentNetworkResolutionStateNo, totalTimeout);
}
}
// constructs SNI Handle for MARS session
internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true) {
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
_status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync);
}
}
public override bool IsInvalid {
get {
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle() {
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
if (IntPtr.Zero != ptr) {
if (0 != SNINativeMethodWrapper.SNIClose(ptr)) {
return false; // SNIClose should never fail.
}
}
return true;
}
internal UInt32 Status {
get {
return _status;
}
}
}
internal sealed class SNIPacket : SafeHandle {
internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true) {
SNINativeMethodWrapper.SNIPacketAllocate(sniHandle, SNINativeMethodWrapper.IOType.WRITE, ref base.handle);
if (IntPtr.Zero == base.handle) {
throw SQL.SNIPacketAllocationFailure();
}
}
public override bool IsInvalid {
get {
return (IntPtr.Zero == base.handle);
}
}
override protected bool ReleaseHandle() {
// NOTE: The SafeHandle class guarantees this will be called exactly once.
IntPtr ptr = base.handle;
base.handle = IntPtr.Zero;
if (IntPtr.Zero != ptr) {
SNINativeMethodWrapper.SNIPacketRelease(ptr);
}
return true;
}
}
internal sealed class WritePacketCache : IDisposable {
private bool _disposed;
private Stack<SNIPacket> _packets;
public WritePacketCache() {
_disposed = false;
_packets = new Stack<SNIPacket>();
}
public SNIPacket Take(SNIHandle sniHandle) {
SNIPacket packet;
if (_packets.Count > 0) {
// Success - reset the packet
packet = _packets.Pop();
SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
}
else {
// Failed to take a packet - create a new one
packet = new SNIPacket(sniHandle);
}
return packet;
}
public void Add(SNIPacket packet) {
if (!_disposed) {
_packets.Push(packet);
}
else {
// If we're disposed, then get rid of any packets added to us
packet.Dispose();
}
}
public void Clear() {
while (_packets.Count > 0) {
_packets.Pop().Dispose();
}
}
public void Dispose() {
if (!_disposed) {
_disposed = true;
Clear();
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EventLogSession
**
** Purpose:
** Defines a session for Event Log operations. The session can
** be configured for a remote machine and can use specfic
** user credentials.
============================================================*/
using System;
using System.Security;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Globalization;
namespace System.Diagnostics.Eventing.Reader {
/// <summary>
/// Session Login Type
/// </summary>
public enum SessionAuthentication {
Default = 0,
Negotiate = 1,
Kerberos = 2,
Ntlm = 3
}
/// <summary>
/// The type: log / external log file to query
/// </summary>
public enum PathType
{
LogName = 1,
FilePath = 2
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public class EventLogSession : IDisposable {
//
//the two context handles for rendering (for EventLogRecord).
//the system and user context handles. They are both common for all the event instances and can be created only once.
//access to the data member references is safe, while
//invoking methods on it is marked SecurityCritical as appropriate.
//
internal EventLogHandle renderContextHandleSystem = EventLogHandle.Zero;
internal EventLogHandle renderContextHandleUser = EventLogHandle.Zero;
//the dummy [....] object for the two contextes.
private object syncObject = null;
private string server;
private string user;
private string domain;
private SessionAuthentication logOnType;
//we do not maintain the password here.
//
//access to the data member references is safe, while
//invoking methods on it is marked SecurityCritical as appropriate.
//
private EventLogHandle handle = EventLogHandle.Zero;
//setup the System Context, once for all the EventRecords.
[System.Security.SecuritySafeCritical]
internal void SetupSystemContext() {
EventLogPermissionHolder.GetEventLogPermission().Demand();
if (!this.renderContextHandleSystem.IsInvalid)
return;
lock (this.syncObject) {
if (this.renderContextHandleSystem.IsInvalid) {
//create the SYSTEM render context
//call the EvtCreateRenderContext to get the renderContextHandleSystem, so that we can get the system/values/user properties.
this.renderContextHandleSystem = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextSystem);
}
}
}
[System.Security.SecuritySafeCritical]
internal void SetupUserContext() {
EventLogPermissionHolder.GetEventLogPermission().Demand();
lock (this.syncObject) {
if (this.renderContextHandleUser.IsInvalid) {
//create the USER render context
this.renderContextHandleUser = NativeWrapper.EvtCreateRenderContext(0, null, UnsafeNativeMethods.EvtRenderContextFlags.EvtRenderContextUser);
}
}
}
// marked as SecurityCritical because allocates SafeHandle.
// marked as TreatAsSafe because performs Demand().
[System.Security.SecurityCritical]
public EventLogSession() {
EventLogPermissionHolder.GetEventLogPermission().Demand();
//handle = EventLogHandle.Zero;
syncObject = new object();
}
public EventLogSession(string server)
:
this(server, null, null, (SecureString)null, SessionAuthentication.Default) {
}
// marked as TreatAsSafe because performs Demand().
[System.Security.SecurityCritical]
public EventLogSession(string server, string domain, string user, SecureString password, SessionAuthentication logOnType) {
EventLogPermissionHolder.GetEventLogPermission().Demand();
if (server == null)
server = "localhost";
syncObject = new object();
this.server = server;
this.domain = domain;
this.user = user;
this.logOnType = logOnType;
UnsafeNativeMethods.EvtRpcLogin erLogin = new UnsafeNativeMethods.EvtRpcLogin();
erLogin.Server = this.server;
erLogin.User = this.user;
erLogin.Domain = this.domain;
erLogin.Flags = (int)this.logOnType;
erLogin.Password = CoTaskMemUnicodeSafeHandle.Zero;
try {
if (password != null)
erLogin.Password.SetMemory(Marshal.SecureStringToCoTaskMemUnicode(password));
//open a session using the erLogin structure.
handle = NativeWrapper.EvtOpenSession(UnsafeNativeMethods.EvtLoginClass.EvtRpcLogin, ref erLogin, 0, 0);
}
finally {
erLogin.Password.Close();
}
}
internal EventLogHandle Handle {
get {
return handle;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing) {
if (disposing) {
if ( this == globalSession )
throw new InvalidOperationException();
EventLogPermissionHolder.GetEventLogPermission().Demand();
}
if (this.renderContextHandleSystem != null &&
!this.renderContextHandleSystem.IsInvalid)
this.renderContextHandleSystem.Dispose();
if (this.renderContextHandleUser != null &&
!this.renderContextHandleUser.IsInvalid)
this.renderContextHandleUser.Dispose();
if (handle != null && !handle.IsInvalid)
handle.Dispose();
}
public void CancelCurrentOperations() {
NativeWrapper.EvtCancel(handle);
}
static EventLogSession globalSession = new EventLogSession();
public static EventLogSession GlobalSession {
get { return globalSession; }
}
[System.Security.SecurityCritical]
public IEnumerable<string> GetProviderNames()
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
List<string> namesList = new List<string>(100);
using (EventLogHandle ProviderEnum = NativeWrapper.EvtOpenProviderEnum(this.Handle, 0))
{
bool finish = false;
do
{
string s = NativeWrapper.EvtNextPublisherId(ProviderEnum, ref finish);
if (finish == false) namesList.Add(s);
}
while (finish == false);
return namesList;
}
}
[System.Security.SecurityCritical]
public IEnumerable<string> GetLogNames()
{
EventLogPermissionHolder.GetEventLogPermission().Demand();
List<string> namesList = new List<string>(100);
using (EventLogHandle channelEnum = NativeWrapper.EvtOpenChannelEnum(this.Handle, 0))
{
bool finish = false;
do
{
string s = NativeWrapper.EvtNextChannelPath(channelEnum, ref finish);
if (finish == false) namesList.Add(s);
}
while (finish == false);
return namesList;
}
}
public EventLogInformation GetLogInformation(string logName, PathType pathType) {
if (logName == null)
throw new ArgumentNullException("logName");
return new EventLogInformation(this, logName, pathType);
}
public void ExportLog(string path, PathType pathType, string query, string targetFilePath) {
this.ExportLog(path, pathType, query, targetFilePath, false);
}
public void ExportLog(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors)
{
if (path == null)
throw new ArgumentNullException("path");
if (targetFilePath == null)
throw new ArgumentNullException("targetFilePath");
UnsafeNativeMethods.EvtExportLogFlags flag;
switch (pathType)
{
case PathType.LogName:
flag = UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogChannelPath;
break;
case PathType.FilePath:
flag = UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogFilePath;
break;
default:
throw new ArgumentOutOfRangeException("pathType");
}
if (tolerateQueryErrors == false)
NativeWrapper.EvtExportLog(this.Handle, path, query, targetFilePath, (int)flag);
else
NativeWrapper.EvtExportLog(this.Handle, path, query, targetFilePath, (int)flag | (int)UnsafeNativeMethods.EvtExportLogFlags.EvtExportLogTolerateQueryErrors);
}
public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath)
{
this.ExportLogAndMessages(path, pathType, query, targetFilePath, false, CultureInfo.CurrentCulture );
}
public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors, CultureInfo targetCultureInfo ) {
if (targetCultureInfo == null)
targetCultureInfo = CultureInfo.CurrentCulture;
ExportLog(path, pathType, query, targetFilePath, tolerateQueryErrors);
NativeWrapper.EvtArchiveExportedLog(this.Handle, targetFilePath, targetCultureInfo.LCID, 0);
}
public void ClearLog(string logName)
{
this.ClearLog(logName, null);
}
public void ClearLog(string logName, string backupPath)
{
if (logName == null)
throw new ArgumentNullException("logName");
NativeWrapper.EvtClearLog(this.Handle, logName, backupPath, 0);
}
}
}
| |
// Copyright (c) .NET Foundation and Contributors
// All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You may
// obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing permissions
// and limitations under the License.
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace System.Reactive
{
// String resources copied verbatim from:
// https://github.com/dotnet/reactive/blob/9ed62628561ed20a83dc063411a193bf82184693/Rx.NET/Source/src/System.Reactive/Strings_Core.resx
static class Strings_Core
{
public const string DISPOSABLES_CANT_CONTAIN_NULL = "Disposables collection can not contain null values.";
}
}
namespace System.Reactive.Disposables
{
// Source: https://github.com/dotnet/reactive/blob/9ed62628561ed20a83dc063411a193bf82184693/Rx.NET/Source/src/System.Reactive/Disposables/ICancelable.cs
/// <summary>
/// Disposable resource with disposal state tracking.
/// </summary>
public interface ICancelable : IDisposable
{
/// <summary>
/// Gets a value that indicates whether the object is disposed.
/// </summary>
bool IsDisposed { get; }
}
// Source: https://github.com/dotnet/reactive/blob/9ed62628561ed20a83dc063411a193bf82184693/Rx.NET/Source/src/System.Reactive/Disposables/CompositeDisposable.cs
/// <summary>
/// Represents a group of disposable resources that are disposed together.
/// </summary>
[Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Backward compat + ideally want to get rid of the ICollection nature of the type.")]
public sealed class CompositeDisposable : ICollection<IDisposable>, ICancelable
{
private readonly object _gate = new object();
private bool _disposed;
private List<IDisposable> _disposables;
private int _count;
private const int ShrinkThreshold = 64;
// Default initial capacity of the _disposables list in case
// The number of items is not known upfront
private const int DefaultCapacity = 16;
/// <summary>
/// Initializes a new instance of the <see cref="CompositeDisposable"/> class with no disposables contained by it initially.
/// </summary>
public CompositeDisposable()
{
_disposables = new List<IDisposable>();
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositeDisposable"/> class with the specified number of disposables.
/// </summary>
/// <param name="capacity">The number of disposables that the new CompositeDisposable can initially store.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than zero.</exception>
public CompositeDisposable(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity));
}
_disposables = new List<IDisposable>(capacity);
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositeDisposable"/> class from a group of disposables.
/// </summary>
/// <param name="disposables">Disposables that will be disposed together.</param>
/// <exception cref="ArgumentNullException"><paramref name="disposables"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">Any of the disposables in the <paramref name="disposables"/> collection is <c>null</c>.</exception>
public CompositeDisposable(params IDisposable[] disposables)
{
if (disposables == null)
{
throw new ArgumentNullException(nameof(disposables));
}
Init(disposables, disposables.Length);
}
/// <summary>
/// Initializes a new instance of the <see cref="CompositeDisposable"/> class from a group of disposables.
/// </summary>
/// <param name="disposables">Disposables that will be disposed together.</param>
/// <exception cref="ArgumentNullException"><paramref name="disposables"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">Any of the disposables in the <paramref name="disposables"/> collection is <c>null</c>.</exception>
public CompositeDisposable(IEnumerable<IDisposable> disposables)
{
if (disposables == null)
{
throw new ArgumentNullException(nameof(disposables));
}
// If the disposables is a collection, get its size
// and use it as a capacity hint for the copy.
if (disposables is ICollection<IDisposable> c)
{
Init(disposables, c.Count);
}
else
{
// Unknown sized disposables, use the default capacity hint
Init(disposables, DefaultCapacity);
}
}
/// <summary>
/// Initialize the inner disposable list and count fields.
/// </summary>
/// <param name="disposables">The enumerable sequence of disposables.</param>
/// <param name="capacityHint">The number of items expected from <paramref name="disposables"/></param>
private void Init(IEnumerable<IDisposable> disposables, int capacityHint)
{
var list = new List<IDisposable>(capacityHint);
// do the copy and null-check in one step to avoid a
// second loop for just checking for null items
foreach (var d in disposables)
{
if (d == null)
{
throw new ArgumentException(Strings_Core.DISPOSABLES_CANT_CONTAIN_NULL, nameof(disposables));
}
list.Add(d);
}
_disposables = list;
// _count can be read by other threads and thus should be properly visible
// also releases the _disposables contents so it becomes thread-safe
Volatile.Write(ref _count, _disposables.Count);
}
/// <summary>
/// Gets the number of disposables contained in the <see cref="CompositeDisposable"/>.
/// </summary>
public int Count => Volatile.Read(ref _count);
/// <summary>
/// Adds a disposable to the <see cref="CompositeDisposable"/> or disposes the disposable if the <see cref="CompositeDisposable"/> is disposed.
/// </summary>
/// <param name="item">Disposable to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public void Add(IDisposable item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
lock (_gate)
{
if (!_disposed)
{
_disposables.Add(item);
// If read atomically outside the lock, it should be written atomically inside
// the plain read on _count is fine here because manipulation always happens
// from inside a lock.
Volatile.Write(ref _count, _count + 1);
return;
}
}
item.Dispose();
}
/// <summary>
/// Removes and disposes the first occurrence of a disposable from the <see cref="CompositeDisposable"/>.
/// </summary>
/// <param name="item">Disposable to remove.</param>
/// <returns>true if found; false otherwise.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public bool Remove(IDisposable item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
lock (_gate)
{
// this composite was already disposed and if the item was in there
// it has been already removed/disposed
if (_disposed)
{
return false;
}
//
// List<T> doesn't shrink the size of the underlying array but does collapse the array
// by copying the tail one position to the left of the removal index. We don't need
// index-based lookup but only ordering for sequential disposal. So, instead of spending
// cycles on the Array.Copy imposed by Remove, we use a null sentinel value. We also
// do manual Swiss cheese detection to shrink the list if there's a lot of holes in it.
//
// read fields as infrequently as possible
var current = _disposables;
var i = current.IndexOf(item);
if (i < 0)
{
// not found, just return
return false;
}
current[i] = null;
if (current.Capacity > ShrinkThreshold && _count < current.Capacity / 2)
{
var fresh = new List<IDisposable>(current.Capacity / 2);
foreach (var d in current)
{
if (d != null)
{
fresh.Add(d);
}
}
_disposables = fresh;
}
// make sure the Count property sees an atomic update
Volatile.Write(ref _count, _count - 1);
}
// if we get here, the item was found and removed from the list
// just dispose it and report success
item.Dispose();
return true;
}
/// <summary>
/// Disposes all disposables in the group and removes them from the group.
/// </summary>
public void Dispose()
{
var currentDisposables = default(List<IDisposable>);
lock (_gate)
{
if (!_disposed)
{
currentDisposables = _disposables;
// nulling out the reference is faster no risk to
// future Add/Remove because _disposed will be true
// and thus _disposables won't be touched again.
_disposables = null;
Volatile.Write(ref _count, 0);
Volatile.Write(ref _disposed, true);
}
}
if (currentDisposables != null)
{
foreach (var d in currentDisposables)
{
d?.Dispose();
}
}
}
/// <summary>
/// Removes and disposes all disposables from the <see cref="CompositeDisposable"/>, but does not dispose the <see cref="CompositeDisposable"/>.
/// </summary>
public void Clear()
{
var previousDisposables = default(IDisposable[]);
lock (_gate)
{
// disposed composites are always clear
if (_disposed)
{
return;
}
var current = _disposables;
previousDisposables = current.ToArray();
current.Clear();
Volatile.Write(ref _count, 0);
}
foreach (var d in previousDisposables)
{
d?.Dispose();
}
}
/// <summary>
/// Determines whether the <see cref="CompositeDisposable"/> contains a specific disposable.
/// </summary>
/// <param name="item">Disposable to search for.</param>
/// <returns>true if the disposable was found; otherwise, false.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public bool Contains(IDisposable item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
lock (_gate)
{
if (_disposed)
{
return false;
}
return _disposables.Contains(item);
}
}
/// <summary>
/// Copies the disposables contained in the <see cref="CompositeDisposable"/> to an array, starting at a particular array index.
/// </summary>
/// <param name="array">Array to copy the contained disposables to.</param>
/// <param name="arrayIndex">Target index at which to copy the first disposable of the group.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than zero. -or - <paramref name="arrayIndex"/> is larger than or equal to the array length.</exception>
public void CopyTo(IDisposable[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex >= array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
lock (_gate)
{
// disposed composites are always empty
if (_disposed)
{
return;
}
if (arrayIndex + _count > array.Length)
{
// there is not enough space beyond arrayIndex
// to accommodate all _count disposables in this composite
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
}
var i = arrayIndex;
foreach (var d in _disposables)
{
if (d != null)
{
array[i++] = d;
}
}
}
}
/// <summary>
/// Always returns false.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Returns an enumerator that iterates through the <see cref="CompositeDisposable"/>.
/// </summary>
/// <returns>An enumerator to iterate over the disposables.</returns>
public IEnumerator<IDisposable> GetEnumerator()
{
lock (_gate)
{
if (_disposed || _count == 0)
{
return EmptyEnumerator;
}
// the copy is unavoidable but the creation
// of an outer IEnumerable is avoidable
return new CompositeEnumerator(_disposables.ToArray());
}
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="CompositeDisposable"/>.
/// </summary>
/// <returns>An enumerator to iterate over the disposables.</returns>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Gets a value that indicates whether the object is disposed.
/// </summary>
public bool IsDisposed => Volatile.Read(ref _disposed);
/// <summary>
/// An empty enumerator for the <see cref="GetEnumerator"/>
/// method to avoid allocation on disposed or empty composites.
/// </summary>
private static readonly CompositeEnumerator EmptyEnumerator =
new CompositeEnumerator(Array.Empty<IDisposable>());
/// <summary>
/// An enumerator for an array of disposables.
/// </summary>
private sealed class CompositeEnumerator : IEnumerator<IDisposable>
{
private readonly IDisposable[] _disposables;
private int _index;
public CompositeEnumerator(IDisposable[] disposables)
{
_disposables = disposables;
_index = -1;
}
public IDisposable Current => _disposables[_index];
object IEnumerator.Current => _disposables[_index];
public void Dispose()
{
// Avoid retention of the referenced disposables
// beyond the lifecycle of the enumerator.
// Not sure if this happens by default to
// generic array enumerators though.
var disposables = _disposables;
Array.Clear(disposables, 0, disposables.Length);
}
public bool MoveNext()
{
var disposables = _disposables;
for (; ; )
{
var idx = ++_index;
if (idx >= disposables.Length)
{
return false;
}
// inlined that filter for null elements
if (disposables[idx] != null)
{
return true;
}
}
}
public void Reset()
{
_index = -1;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Components.Server
{
// **Component descriptor protocol**
// MVC serializes one or more components as comments in HTML.
// Each comment is in the form <!-- Blazor:<<Json>>--> for example { "type": "server", "sequence": 0, descriptor: "base64(dataprotected(<<ServerComponent>>))" }
// Where <<Json>> has the following properties:
// 'type' indicates the marker type. For now it's limited to server.
// 'sequence' indicates the order in which this component got rendered on the server.
// 'descriptor' a data-protected payload that allows the server to validate the legitimacy of the rendered component.
// 'prerenderId' a unique identifier that uniquely identifies the marker to match start and end markers.
//
// descriptor holds the information to validate a component render request. It prevents an infinite number of components
// from being rendered by a given client.
//
// descriptor is a data protected json payload that holds the following information
// 'sequence' indicates the order in which this component got rendered on the server.
// 'assemblyName' the assembly name for the rendered component.
// 'type' the full type name for the rendered component.
// 'parameterDefinitions' a JSON serialized array that contains the definitions for the parameters including their names and types and assemblies.
// 'parameterValues' a JSON serialized array containing the parameter values.
// 'invocationId' a random string that matches all components rendered by as part of a single HTTP response.
// For example: base64(dataprotection({ "sequence": 1, "assemblyName": "Microsoft.AspNetCore.Components", "type":"Microsoft.AspNetCore.Components.Routing.Router", "invocationId": "<<guid>>"}))
// With parameters
// For example: base64(dataprotection({ "sequence": 1, "assemblyName": "Microsoft.AspNetCore.Components", "type":"Microsoft.AspNetCore.Components.Routing.Router", "invocationId": "<<guid>>", parameterDefinitions: "[{ \"name\":\"Parameter\", \"typeName\":\"string\", \"assembly\":\"System.Private.CoreLib\"}], parameterValues: [<<string-value>>]}))
// Serialization:
// For a given response, MVC renders one or more markers in sequence, including a descriptor for each rendered
// component containing the information described above.
// Deserialization:
// To prevent a client from rendering an infinite amount of components, we require clients to send all component
// markers in order. They can do so thanks to the sequence included in the marker.
// When we process a marker we do the following.
// * We unprotect the data-protected information.
// * We validate that the sequence number for the descriptor goes after the previous descriptor.
// * We compare the invocationId for the previous descriptor against the invocationId for the current descriptor to make sure they match.
// By doing this we achieve three things:
// * We ensure that the descriptor came from the server.
// * We ensure that a client can't just send an infinite amount of components to render.
// * We ensure that we do the minimal amount of work in the case of an invalid sequence of descriptors.
//
// For example:
// A client can't just send 100 component markers and force us to process them if the server didn't generate those 100 markers.
// * If a marker is out of sequence we will fail early, so we process at most n-1 markers.
// * If a marker has the right sequence but the invocation ID is different we will fail at that point. We know for sure that the
// component wasn't render as part of the same response.
// * If a marker can't be unprotected we will fail early. We know that the marker was tampered with and can't be trusted.
internal sealed partial class ServerComponentDeserializer : IServerComponentDeserializer
{
private readonly IDataProtector _dataProtector;
private readonly ILogger<ServerComponentDeserializer> _logger;
private readonly RootComponentTypeCache _rootComponentTypeCache;
private readonly ComponentParameterDeserializer _parametersDeserializer;
public ServerComponentDeserializer(
IDataProtectionProvider dataProtectionProvider,
ILogger<ServerComponentDeserializer> logger,
RootComponentTypeCache rootComponentTypeCache,
ComponentParameterDeserializer parametersDeserializer)
{
// When we protect the data we use a time-limited data protector with the
// limits established in 'ServerComponentSerializationSettings.DataExpiration'
// We don't use any of the additional methods provided by ITimeLimitedDataProtector
// in this class, but we need to create one for the unprotect operations to work
// even though we simply call '_dataProtector.Unprotect'.
// See the comment in ServerComponentSerializationSettings.DataExpiration to understand
// why we limit the validity of the protected payloads.
_dataProtector = dataProtectionProvider
.CreateProtector(ServerComponentSerializationSettings.DataProtectionProviderPurpose)
.ToTimeLimitedDataProtector();
_logger = logger;
_rootComponentTypeCache = rootComponentTypeCache;
_parametersDeserializer = parametersDeserializer;
}
public bool TryDeserializeComponentDescriptorCollection(string serializedComponentRecords, out List<ComponentDescriptor> descriptors)
{
var markers = JsonSerializer.Deserialize<IEnumerable<ServerComponentMarker>>(serializedComponentRecords, ServerComponentSerializationSettings.JsonSerializationOptions);
descriptors = new List<ComponentDescriptor>();
int lastSequence = -1;
var previousInstance = new ServerComponent();
foreach (var marker in markers)
{
if (marker.Type != ServerComponentMarker.ServerMarkerType)
{
Log.InvalidMarkerType(_logger, marker.Type);
descriptors.Clear();
return false;
}
if (marker.Descriptor == null)
{
Log.MissingMarkerDescriptor(_logger);
descriptors.Clear();
return false;
}
var (descriptor, serverComponent) = DeserializeServerComponent(marker);
if (descriptor == null)
{
// We failed to deserialize the component descriptor for some reason.
descriptors.Clear();
return false;
}
// We force our client to send the descriptors in order so that we do minimal work.
// The list of descriptors starts with 0 and lastSequence is initialized to -1 so this
// check covers that the sequence starts by 0.
if (lastSequence != serverComponent.Sequence - 1)
{
if (lastSequence == -1)
{
Log.DescriptorSequenceMustStartAtZero(_logger, serverComponent.Sequence);
}
else
{
Log.OutOfSequenceDescriptor(_logger, lastSequence, serverComponent.Sequence);
}
descriptors.Clear();
return false;
}
if (lastSequence != -1 && !previousInstance.InvocationId.Equals(serverComponent.InvocationId))
{
Log.MismatchedInvocationId(_logger, previousInstance.InvocationId.ToString("N"), serverComponent.InvocationId.ToString("N"));
descriptors.Clear();
return false;
}
// As described below, we build a chain of descriptors to prevent being flooded by
// descriptors from a client not behaving properly.
lastSequence = serverComponent.Sequence;
previousInstance = serverComponent;
descriptors.Add(descriptor);
}
return true;
}
private (ComponentDescriptor, ServerComponent) DeserializeServerComponent(ServerComponentMarker record)
{
string unprotected;
try
{
var payload = Convert.FromBase64String(record.Descriptor);
var unprotectedBytes = _dataProtector.Unprotect(payload);
unprotected = Encoding.UTF8.GetString(unprotectedBytes);
}
catch (Exception e)
{
Log.FailedToUnprotectDescriptor(_logger, e);
return default;
}
ServerComponent serverComponent;
try
{
serverComponent = JsonSerializer.Deserialize<ServerComponent>(
unprotected,
ServerComponentSerializationSettings.JsonSerializationOptions);
}
catch (Exception e)
{
Log.FailedToDeserializeDescriptor(_logger, e);
return default;
}
var componentType = _rootComponentTypeCache
.GetRootComponent(serverComponent.AssemblyName, serverComponent.TypeName);
if (componentType == null)
{
Log.FailedToFindComponent(_logger, serverComponent.TypeName, serverComponent.AssemblyName);
return default;
}
if (!_parametersDeserializer.TryDeserializeParameters(serverComponent.ParameterDefinitions, serverComponent.ParameterValues, out var parameters))
{
// TryDeserializeParameters does appropriate logging.
return default;
}
var componentDescriptor = new ComponentDescriptor
{
ComponentType = componentType,
Parameters = parameters,
Sequence = serverComponent.Sequence
};
return (componentDescriptor, serverComponent);
}
private static partial class Log
{
[LoggerMessage(1, LogLevel.Debug, "Failed to deserialize the component descriptor.", EventName = "FailedToDeserializeDescriptor")]
public static partial void FailedToDeserializeDescriptor(ILogger<ServerComponentDeserializer> logger, Exception e);
[LoggerMessage(2, LogLevel.Debug, "Failed to find component '{ComponentName}' in assembly '{Assembly}'.", EventName = "FailedToFindComponent")]
public static partial void FailedToFindComponent(ILogger<ServerComponentDeserializer> logger, string componentName, string assembly);
[LoggerMessage(3, LogLevel.Debug, "Failed to unprotect the component descriptor.", EventName = "FailedToUnprotectDescriptor")]
public static partial void FailedToUnprotectDescriptor(ILogger<ServerComponentDeserializer> logger, Exception e);
[LoggerMessage(4, LogLevel.Debug, "Invalid component marker type '{MarkerType}'.", EventName = "InvalidMarkerType")]
public static partial void InvalidMarkerType(ILogger<ServerComponentDeserializer> logger, string markerType);
[LoggerMessage(5, LogLevel.Debug, "The component marker is missing the descriptor.", EventName = "MissingMarkerDescriptor")]
public static partial void MissingMarkerDescriptor(ILogger<ServerComponentDeserializer> logger);
[LoggerMessage(6, LogLevel.Debug, "The descriptor invocationId is '{invocationId}' and got a descriptor with invocationId '{currentInvocationId}'.", EventName = "MismatchedInvocationId")]
public static partial void MismatchedInvocationId(ILogger<ServerComponentDeserializer> logger, string invocationId, string currentInvocationId);
[LoggerMessage(7, LogLevel.Debug, "The last descriptor sequence was '{lastSequence}' and got a descriptor with sequence '{sequence}'.", EventName = "OutOfSequenceDescriptor")]
public static partial void OutOfSequenceDescriptor(ILogger<ServerComponentDeserializer> logger, int lastSequence, int sequence);
[LoggerMessage(8, LogLevel.Debug, "The descriptor sequence '{sequence}' is an invalid start sequence.", EventName = "DescriptorSequenceMustStartAtZero")]
public static partial void DescriptorSequenceMustStartAtZero(ILogger<ServerComponentDeserializer> logger, int sequence);
}
}
}
| |
//
// FlickrRemote.cs
//
// Author:
// Lorenzo Milesi <maxxer@yetopen.it>
// Stephane Delcroix <stephane@delcroix.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008-2009 Lorenzo Milesi
// Copyright (C) 2008-2009 Stephane Delcroix
//
// 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.
//
/*
* Simple upload based on the api at
* http://www.flickr.com/services/api/upload.api.html
*
* Modified by acs in order to use Flickr.Net
*
* Modified in order to use the new Auth API
*
* We use now the search API also
*
*/
using System;
using System.Text;
using System.Collections.Generic;
using FlickrNet;
using FSpot.Core;
using FSpot.Filters;
using Hyena;
namespace FSpot.Exporters.Flickr
{
public class FlickrRemote
{
public static LicenseCollection licenses;
string frob;
string token;
Auth auth;
FlickrNet.Flickr flickr;
public bool ExportTags;
public bool ExportTagHierarchy;
public bool ExportIgnoreTopLevel;
public ProgressItem Progress;
public const string TOKEN_FLICKR = Preferences.APP_FSPOT_EXPORT_TOKENS + "flickr";
public const string TOKEN_23HQ = Preferences.APP_FSPOT_EXPORT_TOKENS + "23hq";
public const string TOKEN_ZOOOMR = Preferences.APP_FSPOT_EXPORT_TOKENS + "zooomr";
public FlickrRemote (string token, Service service)
{
if (string.IsNullOrEmpty (token)) {
flickr = new FlickrNet.Flickr (service.ApiKey, service.Secret);
this.token = null;
} else {
flickr = new FlickrNet.Flickr (service.ApiKey, service.Secret, token);
this.token = token;
}
flickr.CurrentService = service.Id;
}
public string Token {
get { return token; }
set {
token = value;
flickr.AuthToken = value;
}
}
public FlickrNet.Flickr Connection {
get { return flickr; }
}
public LicenseCollection GetLicenses ()
{
// Licenses won't change normally in a user session
if (licenses == null) {
try {
licenses = flickr.PhotosLicensesGetInfo ();
} catch (FlickrNet.FlickrApiException e) {
Log.Error (e.Code + ": " + e.OriginalMessage);
return null;
}
}
return licenses;
}
public List<string> Search (string [] tags, int licenseId)
{
var photos_url = new List<string> ();
// Photos photos = flickr.PhotosSearchText (tags, licenseId);
var options = new PhotoSearchOptions ();
options.Tags = string.Join (",", tags);
PhotoCollection photos = flickr.PhotosSearch (options);
if (photos != null) {
foreach (FlickrNet.Photo photo in photos) {
photos_url.Add (photo.ThumbnailUrl);
}
}
return photos_url;
}
public List<string> Search (string tags, int licenseId)
{
var photos_url = new List<string> ();
var options = new PhotoSearchOptions ();
options.Tags = tags;
PhotoCollection photos = flickr.PhotosSearch (options);
if (photos != null) {
foreach (FlickrNet.Photo photo in photos) {
photos_url.Add (photo.ThumbnailUrl);
}
}
return photos_url;
}
public Auth CheckLogin ()
{
try {
if (frob == null) {
frob = flickr.AuthGetFrob ();
if (frob == null) {
Log.Error ("ERROR: Problems login in Flickr. Don't have a frob");
return null;
}
}
} catch (Exception e) {
Log.Error ("Error logging in: {0}", e.Message);
return null;
}
if (token == null) {
try {
auth = flickr.AuthGetToken (frob);
token = auth.Token;
flickr.AuthToken = token;
return auth;
} catch (FlickrApiException ex) {
Log.Error ("Problems logging in to Flickr - " + ex.OriginalMessage);
return null;
}
}
auth = flickr.AuthCheckToken ("token");
return auth;
}
public string Upload (IPhoto photo, IFilter filter, bool is_public, bool is_family, bool is_friend)
{
if (token == null) {
throw new Exception ("Must Login First");
}
// FIXME flickr needs rotation
string error_verbose;
using (FilterRequest request = new FilterRequest (photo.DefaultVersion.Uri)) {
try {
string tags = null;
filter.Convert (request);
string path = request.Current.LocalPath;
if (ExportTags && photo.Tags != null) {
var taglist = new StringBuilder ();
Core.Tag [] t = photo.Tags;
Core.Tag tag_iter = null;
for (int i = 0; i < t.Length; i++) {
if (i > 0)
taglist.Append (",");
taglist.Append (string.Format ("\"{0}\"", t [i].Name));
// Go through the tag parents
if (ExportTagHierarchy) {
tag_iter = t [i].Category;
while (tag_iter != App.Instance.Database.Tags.RootCategory && tag_iter != null) {
// Skip top level tags because they have no meaning in a linear tag database
if (ExportIgnoreTopLevel && tag_iter.Category == App.Instance.Database.Tags.RootCategory) {
break;
}
// FIXME Look if the tag is already there!
taglist.Append (",");
taglist.Append (string.Format ("\"{0}\"", tag_iter.Name));
tag_iter = tag_iter.Category;
}
}
}
tags = taglist.ToString ();
}
try {
string photoid =
flickr.UploadPicture (path, photo.Name, photo.Description, tags, is_public, is_family, is_friend);
return photoid;
} catch (FlickrException ex) {
Log.Error ("Problems uploading picture: " + ex.Message);
error_verbose = ex.ToString ();
}
} catch (Exception e) {
// FIXME we need to distinguish between file IO errors and xml errors here
throw new Exception ("Error while uploading", e);
}
}
throw new Exception (error_verbose);
}
public void TryWebLogin ()
{
frob = flickr.AuthGetFrob ();
string login_url = flickr.AuthCalcUrl (frob, AuthLevel.Write);
GtkBeans.Global.ShowUri (null, login_url);
}
public class Service
{
public string ApiKey;
public string Secret;
public SupportedService Id;
public string Name;
public string PreferencePath;
public static Service [] Supported = {
new Service (SupportedService.Flickr, "Flickr.com", "c6b39ee183385d9ce4ea188f85945016", "0a951ac44a423a04", TOKEN_FLICKR),
new Service (SupportedService.TwentyThreeHQ, "23hq.com", "c6b39ee183385d9ce4ea188f85945016", "0a951ac44a423a04", TOKEN_23HQ),
new Service (SupportedService.Zooomr, "Zooomr.com", "a2075d8ff1b7b059df761649835562e4", "6c66738681", TOKEN_ZOOOMR)
};
public Service (SupportedService id, string name, string api_key, string secret, string pref)
{
Id = id;
ApiKey = api_key;
Secret = secret;
Name = name;
PreferencePath = pref;
}
public static Service FromSupported (SupportedService id)
{
foreach (Service s in Supported) {
if (s.Id == id)
return s;
}
throw new ArgumentException ("Unknown service type");
}
}
}
}
| |
//
// File.cs: Provides tagging for PNG files
//
// Author:
// Mike Gemuende (mike@gemuende.be)
//
// Copyright (C) 2010 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Collections.Generic;
using TagLib;
using TagLib.Image;
using TagLib.Xmp;
namespace TagLib.Png
{
/// <summary>
/// This class extends <see cref="TagLib.Image.ImageBlockFile" /> to provide tagging
/// for PNG image files.
/// </summary>
/// <remarks>
/// This implementation is based on http://www.w3.org/TR/PNG
/// </remarks>
[SupportedMimeType("taglib/png", "png")]
[SupportedMimeType("image/png")]
public class File : TagLib.Image.ImageBlockFile
{
#region GIF specific constants
/// <summary>
/// The PNG Header every png file starts with.
/// </summary>
private readonly byte [] HEADER = new byte [] {137, 80, 78, 71, 13, 10, 26, 10};
/// <summary>
/// byte sequence to indicate a IHDR Chunk
/// </summary>
private readonly byte [] IHDR_CHUNK_TYPE = new byte [] {73, 72, 68, 82};
/// <summary>
/// byte sequence to indicate a IEND Chunk
/// </summary>
private readonly byte [] IEND_CHUNK_TYPE = new byte [] {73, 69, 78, 68};
/// <summary>
/// byte sequence to indicate a iTXt Chunk
/// </summary>
private readonly byte [] iTXt_CHUNK_TYPE = new byte [] {105, 84, 88, 116};
/// <summary>
/// byte sequence to indicate a tEXt Chunk
/// </summary>
private readonly byte [] tEXt_CHUNK_TYPE = new byte [] {116, 69, 88, 116};
/// <summary>
/// byte sequence to indicate a zTXt Chunk
/// </summary>
private readonly byte [] zTXt_CHUNK_TYPE = new byte [] {122, 84, 88, 116};
/// <summary>
/// header of a iTXt which contains XMP data.
/// </summary>
private readonly byte [] XMP_CHUNK_HEADER = new byte [] {
// Keyword ("XML:com.adobe.xmp")
0x58, 0x4D, 0x4C, 0x3A, 0x63, 0x6F, 0x6D, 0x2E, 0x61, 0x64, 0x6F, 0x62, 0x65, 0x2E, 0x78, 0x6D, 0x70,
// Null Separator
0x00,
// Compression Flag
0x00,
// Compression Method
0x00,
// Language Tag Null Separator
0x00,
// Translated Keyword Null Separator
0x00
};
#endregion
#region private fields
/// <summary>
/// The height of the image
/// </summary>
private int height;
/// <summary>
/// The width of the image
/// </summary>
private int width;
/// <summary>
/// The Properties of the image
/// </summary>
private Properties properties;
#endregion
#region public Properties
/// <summary>
/// Gets the media properties of the file represented by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Properties" /> object containing the
/// media properties of the file represented by the current
/// instance.
/// </value>
public override TagLib.Properties Properties {
get { return properties; }
}
#endregion
#region constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system and specified read style.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path, ReadStyle propertiesStyle)
: this (new File.LocalFileAbstraction (path),
propertiesStyle)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path) : this (path, ReadStyle.Average)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction and
/// specified read style.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
public File (File.IFileAbstraction abstraction,
ReadStyle propertiesStyle) : base (abstraction)
{
Read (propertiesStyle);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
protected File (IFileAbstraction abstraction)
: this (abstraction, ReadStyle.Average)
{
}
#endregion
#region Public Methods
/// <summary>
/// Saves the changes made in the current instance to the
/// file it represents.
/// </summary>
public override void Save ()
{
Mode = AccessMode.Write;
try {
SaveMetadata ();
TagTypesOnDisk = TagTypes;
} finally {
Mode = AccessMode.Closed;
}
}
#endregion
#region private methods
/// <summary>
/// Reads the information from file with a specified read style.
/// </summary>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
private void Read (ReadStyle propertiesStyle)
{
Mode = AccessMode.Read;
try {
ImageTag = new CombinedImageTag (TagTypes.XMP | TagTypes.Png);
ValidateHeader ();
ReadMetadata ();
TagTypesOnDisk = TagTypes;
if (propertiesStyle != ReadStyle.None)
properties = ExtractProperties ();
} finally {
Mode = AccessMode.Closed;
}
}
/// <summary>
/// Validates the header of a PNG file. Therfore, the current position to
/// read must be the start of the file.
/// </summary>
private void ValidateHeader ()
{
ByteVector data = ReadBlock (8);
if (data.Count != 8)
throw new CorruptFileException ("Unexpected end of header");
if (! data.Equals (new ByteVector (HEADER)))
throw new CorruptFileException ("PNG Header was expected");
}
/// <summary>
/// Reads the length of data of a chunk from the current position
/// </summary>
/// <returns>
/// A <see cref="System.Int32"/> with the length of data.
/// </returns>
/// <remarks>
/// The length is stored in a 4-byte unsigned integer in the file,
/// but due to the PNG specification this value does not exceed
/// 2^31-1 and can therfore be safely returned as an signed integer.
/// This prevents unsafe casts for using the length as parameter
/// for other methods.
/// </remarks>
private int ReadChunkLength ()
{
ByteVector data = ReadBlock (4);
if (data.Count != 4)
throw new CorruptFileException ("Unexpected end of Chunk Length");
uint length = data.ToUInt (true);
if (length > Int32.MaxValue)
throw new CorruptFileException ("PNG limits the Chunk Length to 2^31-1");
return (int) length;
}
/// <summary>
/// Reads the type of a chunk from the current position.
/// </summary>
/// <returns>
/// A <see cref="ByteVector"/> with 4 bytes containing the type of
/// the Chunk.
/// </returns>
private ByteVector ReadChunkType ()
{
ByteVector data = ReadBlock (4);
if (data.Count != 4)
throw new CorruptFileException ("Unexpected end of Chunk Type");
return data;
}
/// <summary>
/// Reads the CRC value for a chunk from the current position.
/// </summary>
/// <returns>
/// A <see cref="ByteVector"/> with 4 bytes with the CRC value.
/// </returns>
private ByteVector ReadCRC ()
{
ByteVector data = ReadBlock (4);
if (data.Count != 4)
throw new CorruptFileException ("Unexpected end of CRC");
return data;
}
/// <summary>
/// Reads the whole Chunk data starting from the current position.
/// </summary>
/// <param name="data_length">
/// A <see cref="System.Int32"/> with the length of the Chunk Data.
/// </param>
/// <returns>
/// A <see cref="ByteVector"/> with the Chunk Data which is read.
/// </returns>
private ByteVector ReadChunkData (int data_length)
{
ByteVector data = ReadBlock (data_length);
if (data.Count != data_length)
throw new CorruptFileException (String.Format ("Chunk Data of Length {0} expected", data_length));
return data;
}
/// <summary>
/// Reads a null terminated string from the given data from given position.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector"/> with teh data to read the string from
/// </param>
/// <param name="start_index">
/// A <see cref="System.Int32"/> with the index to start reading
/// </param>
/// <param name="terminator_index">
/// A <see cref="System.Int32"/> with the index of the null byte
/// </param>
/// <returns>
/// A <see cref="System.String"/> with the read string. The null byte
/// is not included.
/// </returns>
private string ReadTerminatedString (ByteVector data, int start_index, out int terminator_index)
{
if (start_index >= data.Count)
throw new CorruptFileException ("Unexpected End of Data");
terminator_index = data.Find ("\0", start_index);
if (terminator_index < 0)
throw new CorruptFileException ("Cannot find string terminator");
return data.Mid (start_index, terminator_index - start_index).ToString ();
}
/// <summary>
/// Reads a null terminated keyword from he given data from given position.
/// </summary>
/// <param name="data">
/// A <see cref="ByteVector"/> with teh data to read the string from
/// </param>
/// <param name="start_index">
/// A <see cref="System.Int32"/> with the index to start reading
/// </param>
/// <param name="terminator_index">
/// A <see cref="System.Int32"/> with the index of the null byte
/// </param>
/// <returns>
/// A <see cref="System.String"/> with the read keyword. The null byte
/// is not included.
/// </returns>
private string ReadKeyword (ByteVector data, int start_index, out int terminator_index)
{
string keyword = ReadTerminatedString (data, start_index, out terminator_index);
if (String.IsNullOrEmpty (keyword))
throw new CorruptFileException ("Keyword cannot be empty");
return keyword;
}
/// <summary>
/// Skips the Chunk Data and CRC Data. The read position must be at the
/// beginning of the Chunk data.
/// </summary>
/// <param name="data_size">
/// A <see cref="System.Int32"/> with the length of the chunk data read
/// before.
/// </param>
private void SkipChunkData (int data_size)
{
long position = Tell;
if (position + data_size >= Length)
throw new CorruptFileException (String.Format ("Chunk Data of Length {0} expected", data_size));
Seek (Tell + data_size);
ReadCRC ();
}
/// <summary>
/// Reads the whole metadata from file. The current position must be set to
/// the first Chunk which is contained in the file.
/// </summary>
private void ReadMetadata ()
{
int data_length = ReadChunkLength ();
ByteVector type = ReadChunkType ();
// File should start with a header chunk
if (! type.StartsWith (IHDR_CHUNK_TYPE))
throw new CorruptFileException (
String.Format ("IHDR Chunk was expected, but Chunk {0} was found", type.ToString ()));
ReadIHDRChunk (data_length);
// Read all following chunks
while (true) {
data_length = ReadChunkLength ();
type = ReadChunkType ();
if (type.StartsWith (IEND_CHUNK_TYPE))
return;
else if (type.StartsWith (iTXt_CHUNK_TYPE))
ReadiTXtChunk (data_length);
else if (type.StartsWith (tEXt_CHUNK_TYPE))
ReadtEXtChunk (data_length);
else if (type.StartsWith (zTXt_CHUNK_TYPE))
ReadzTXtChunk (data_length);
else
SkipChunkData (data_length);
}
}
/// <summary>
/// Reads the IHDR Chunk from file and extracts some image information
/// like width and height. The current position must be set to the start
/// of the Chunk Data.
/// </summary>
/// <param name="data_length">
/// A <see cref="System.Int32"/> with the length of the Chunk Data.
/// </param>
private void ReadIHDRChunk (int data_length)
{
// IHDR Chunk
//
// 4 Bytes Width
// 4 Bytes Height
// 1 Byte Bit depth
// 1 Byte Colour type
// 1 Byte Compression method
// 1 Byte Filter method
// 1 Byte Interlace method
//
// Followed by 4 Bytes CRC data
if (data_length != 13)
throw new CorruptFileException ("IHDR chunk data length must be 13");
ByteVector data = ReadChunkData (data_length);
CheckCRC (IHDR_CHUNK_TYPE, data, ReadCRC ());
// The PNG specification limits the size of 4-byte unsigned integers to 2^31-1.
// That allows us to safely cast them to an signed integer.
uint width = data.Mid (0, 4).ToUInt (true);
uint height = data.Mid (4, 4).ToUInt (true);
if (width > Int32.MaxValue || height > Int32.MaxValue)
throw new CorruptFileException ("PNG limits width and heigth to 2^31-1");
this.width = (int) width;
this.height = (int) height;
}
/// <summary>
/// Reads an iTXt Chunk from file. The current position must be set
/// to the start of the Chunk Data. Such a Chunk may contain XMP data
/// or translated keywords.
/// </summary>
/// <param name="data_length">
/// A <see cref="System.Int32"/> with the length of the Chunk Data.
/// </param>
private void ReadiTXtChunk (int data_length)
{
long position = Tell;
// iTXt Chunk
//
// N Bytes Keyword
// 1 Byte Null Separator
// 1 Byte Compression Flag (0 for uncompressed data)
// 1 Byte Compression Method
// N Bytes Language Tag
// 1 Byte Null Separator
// N Bytes Translated Keyword
// 1 Byte Null Terminator
// N Bytes Txt
//
// Followed by 4 Bytes CRC data
ByteVector data = ReadChunkData (data_length);
CheckCRC (iTXt_CHUNK_TYPE, data, ReadCRC ());
// handle XMP, which has a fixed header
if (data.StartsWith (XMP_CHUNK_HEADER)) {
ImageTag.AddTag (new XmpTag (data.Mid (XMP_CHUNK_HEADER.Length).ToString (StringType.UTF8), this));
AddMetadataBlock (position - 8, data_length + 8 + 4);
return;
}
int terminator_index;
string keyword = ReadKeyword (data, 0, out terminator_index);
if (terminator_index + 2 >= data_length)
throw new CorruptFileException ("Compression Flag and Compression Method byte expected");
byte compression_flag = data[terminator_index + 1];
byte compression_method = data[terminator_index + 2];
//string language = ReadTerminatedString (data, terminator_index + 3, out terminator_index);
//string translated_keyword = ReadTerminatedString (data, terminator_index + 1, out terminator_index);
ByteVector txt_data = data.Mid (terminator_index + 1);
if (compression_flag != 0x00) {
txt_data = Decompress (compression_method, txt_data);
// ignore unknown compression methods
if (txt_data == null)
return;
}
string value = txt_data.ToString ();
PngTag png_tag = GetTag (TagTypes.Png, true) as PngTag;
if (png_tag.GetKeyword (keyword) == null)
png_tag.SetKeyword (keyword, value);
AddMetadataBlock (position - 8, data_length + 8 + 4);
}
/// <summary>
/// Reads an tEXt Chunk from file. The current position must be set
/// to the start of the Chunk Data. Such a Chunk contains plain
/// keywords.
/// </summary>
/// <param name="data_length">
/// A <see cref="System.Int32"/> with the length of the Chunk Data.
/// </param>
private void ReadtEXtChunk (int data_length)
{
long position = Tell;
// tEXt Chunk
//
// N Bytes Keyword
// 1 Byte Null Separator
// N Bytes Txt
//
// Followed by 4 Bytes CRC data
ByteVector data = ReadChunkData (data_length);
CheckCRC (tEXt_CHUNK_TYPE, data, ReadCRC ());
int keyword_terminator;
string keyword = ReadKeyword (data, 0, out keyword_terminator);
string value = data.Mid (keyword_terminator + 1).ToString ();
PngTag png_tag = GetTag (TagTypes.Png, true) as PngTag;
if (png_tag.GetKeyword (keyword) == null)
png_tag.SetKeyword (keyword, value);
AddMetadataBlock (position - 8, data_length + 8 + 4);
}
/// <summary>
/// Reads an zTXt Chunk from file. The current position must be set
/// to the start of the Chunk Data. Such a Chunk contains compressed
/// keywords.
/// </summary>
/// <param name="data_length">
/// A <see cref="System.Int32"/> with the length of the Chunk Data.
/// </param>
/// <remarks>
/// The Chunk may also contain compressed Exif data which is written
/// by other tools. But, since the PNG specification does not support
/// Exif data, we ignore it here.
/// </remarks>
private void ReadzTXtChunk (int data_length)
{
long position = Tell;
// zTXt Chunk
//
// N Bytes Keyword
// 1 Byte Null Separator
// 1 Byte Compression Method
// N Bytes Txt
//
// Followed by 4 Bytes CRC data
ByteVector data = ReadChunkData (data_length);
CheckCRC (zTXt_CHUNK_TYPE, data, ReadCRC ());
int terminator_index;
string keyword = ReadKeyword (data, 0, out terminator_index);
if (terminator_index + 1 >= data_length)
throw new CorruptFileException ("Compression Method byte expected");
byte compression_method = data[terminator_index + 1];
ByteVector plain_data = Decompress (compression_method, data.Mid (terminator_index + 2));
// ignore unknown compression methods
if (plain_data == null)
return;
string value = plain_data.ToString ();
PngTag png_tag = GetTag (TagTypes.Png, true) as PngTag;
if (png_tag.GetKeyword (keyword) == null)
png_tag.SetKeyword (keyword, value);
AddMetadataBlock (position - 8, data_length + 8 + 4);
}
/// <summary>
/// Save the metadata to file.
/// </summary>
private void SaveMetadata ()
{
ByteVector metadata_chunks = new ByteVector ();
metadata_chunks.Add (RenderXMPChunk ());
metadata_chunks.Add (RenderKeywordChunks ());
// Metadata is stored after the PNG header and the IDHR chunk.
SaveMetadata (metadata_chunks, HEADER.Length + 13 + 4 + 4 + 4);
}
/// <summary>
/// Creates a Chunk containing the XMP data.
/// </summary>
/// <returns>
/// A <see cref="ByteVector"/> with the XMP data chunk
/// or <see langword="null" /> if no XMP data is contained.
/// </returns>
private ByteVector RenderXMPChunk ()
{
// Check, if XmpTag is contained
XmpTag xmp = ImageTag.Xmp;
if (xmp == null)
return null;
ByteVector chunk = new ByteVector ();
// render the XMP data itself
ByteVector xmp_data = xmp.Render ();
// TODO check uint size.
chunk.Add (ByteVector.FromUInt ((uint) xmp_data.Count + (uint) XMP_CHUNK_HEADER.Length));
chunk.Add (iTXt_CHUNK_TYPE);
chunk.Add (XMP_CHUNK_HEADER);
chunk.Add (xmp_data);
chunk.Add (ComputeCRC (iTXt_CHUNK_TYPE, XMP_CHUNK_HEADER, xmp_data));
return chunk;
}
/// <summary>
/// Creates a list of Chunks containing the PNG keywords
/// </summary>
/// <returns>
/// A <see cref="ByteVector"/> with the list of chunks, or
/// or <see langword="null" /> if no PNG Keywords are contained.
/// </returns>
private ByteVector RenderKeywordChunks ()
{
// Check, if PngTag is contained
PngTag png_tag = GetTag (TagTypes.Png, true) as PngTag;
if (png_tag == null)
return null;
ByteVector chunks = new ByteVector ();
foreach (KeyValuePair<string, string> keyword in png_tag) {
ByteVector data = new ByteVector ();
data.Add (keyword.Key);
data.Add ("\0");
data.Add (keyword.Value);
chunks.Add (ByteVector.FromUInt ((uint) data.Count));
chunks.Add (tEXt_CHUNK_TYPE);
chunks.Add (data);
chunks.Add (ComputeCRC (tEXt_CHUNK_TYPE, data));
}
return chunks;
}
/// <summary>
/// Attempts to extract the media properties of the main
/// photo.
/// </summary>
/// <returns>
/// A <see cref="Properties" /> object with a best effort guess
/// at the right values. When no guess at all can be made,
/// <see langword="null" /> is returned.
/// </returns>
private Properties ExtractProperties ()
{
if (width > 0 && height > 0)
return new Properties (TimeSpan.Zero, new Codec (width, height));
return null;
}
#endregion
#region Utility Stuff
/// <summary>
/// Checks the CRC for a Chunk.
/// </summary>
/// <param name="chunk_type">
/// A <see cref="ByteVector"/> whith the Chunk type
/// </param>
/// <param name="chunk_data">
/// A <see cref="ByteVector"/> with the Chunk data.
/// </param>
/// <param name="crc_data">
/// A <see cref="ByteVector"/> with the read CRC data.
/// </param>
private static void CheckCRC (ByteVector chunk_type, ByteVector chunk_data, ByteVector crc_data)
{
ByteVector computed_crc = ComputeCRC (chunk_type, chunk_data);
if (computed_crc != crc_data)
throw new CorruptFileException (
String.Format ("CRC check failed for {0} Chunk (expected: 0x{1:X4}, read: 0x{2:X4}",
chunk_type.ToString (), computed_crc.ToUInt (), crc_data.ToUInt ()));
}
/// <summary>
/// Computes a 32bit CRC for the given data.
/// </summary>
/// <param name="datas">
/// A <see cref="ByteVector[]"/> with data to compute
/// the CRC for.
/// </param>
/// <returns>
/// A <see cref="ByteVector"/> with 4 bytes (32bit) containing the CRC.
/// </returns>
private static ByteVector ComputeCRC (params ByteVector [] datas)
{
uint crc = 0xFFFFFFFF;
if (crc_table == null)
BuildCRCTable ();
foreach (var data in datas) {
foreach (byte b in data) {
crc = crc_table[(crc ^ b) & 0xFF] ^ (crc >> 8);
}
}
// Invert
return ByteVector.FromUInt (crc ^ 0xFFFFFFFF);
}
/// <summary>
/// Table for faster computation of CRC.
/// </summary>
private static uint[] crc_table;
/// <summary>
/// Initializes the CRC Table.
/// </summary>
private static void BuildCRCTable ()
{
uint polynom = 0xEDB88320;
crc_table = new uint [256];
for (int i = 0; i < 256; i++) {
uint c = (uint) i;
for (int k = 0; k < 8; k++) {
if ((c & 0x00000001) != 0x00)
c = polynom ^ (c >> 1);
else
c = c >> 1;
}
crc_table[i] = c;
}
}
private static ByteVector Inflate (ByteVector data)
{
#if HAVE_SHARPZIPLIB
using (System.IO.MemoryStream out_stream = new System.IO.MemoryStream ()) {
ICSharpCode.SharpZipLib.Zip.Compression.Inflater inflater =
new ICSharpCode.SharpZipLib.Zip.Compression.Inflater ();
inflater.SetInput (data.Data);
byte [] buffer = new byte [1024];
int written_bytes;
while ((written_bytes = inflater.Inflate (buffer)) > 0)
out_stream.Write (buffer, 0, written_bytes);
return new ByteVector (out_stream.ToArray ());
}
#else
return null;
#endif
}
private static ByteVector Decompress (byte compression_method, ByteVector compressed_data)
{
// there is currently just one compression method specified
// for PNG.
switch (compression_method) {
case 0:
return Inflate (compressed_data);
default:
return null;
}
}
#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.Reflection;
using System.Collections;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System.Reflection.Emit
{
internal sealed class TypeBuilderInstantiation : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Static Members
internal static Type MakeGenericType(Type type, Type[] typeArguments)
{
Contract.Requires(type != null, "this is only called from RuntimeType.MakeGenericType and TypeBuilder.MakeGenericType so 'type' cannot be null");
if (!type.IsGenericTypeDefinition)
throw new InvalidOperationException();
if (typeArguments == null)
throw new ArgumentNullException(nameof(typeArguments));
Contract.EndContractBlock();
foreach (Type t in typeArguments)
{
if (t == null)
throw new ArgumentNullException(nameof(typeArguments));
}
return new TypeBuilderInstantiation(type, typeArguments);
}
#endregion
#region Private Data Mebers
private Type m_type;
private Type[] m_inst;
private string m_strFullQualName;
internal Hashtable m_hashtable = new Hashtable();
#endregion
#region Constructor
private TypeBuilderInstantiation(Type type, Type[] inst)
{
m_type = type;
m_inst = inst;
m_hashtable = new Hashtable();
}
#endregion
#region Object Overrides
public override String ToString()
{
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string comma = "";
for (int i = 1; i < rank; i++)
comma += ",";
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", comma);
return SymbolType.FormCompoundType(s, this, 0);
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName
{
get
{
if (m_strFullQualName == null)
m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
return m_strFullQualName;
}
}
public override String Namespace { get { return m_type.Namespace; } }
public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } }
private Type Substitute(Type[] substitutes)
{
Type[] inst = GetGenericArguments();
Type[] instSubstituted = new Type[inst.Length];
for (int i = 0; i < instSubstituted.Length; i++)
{
Type t = inst[i];
if (t is TypeBuilderInstantiation)
{
instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes);
}
else if (t is GenericTypeParameterBuilder)
{
// Substitute
instSubstituted[i] = substitutes[t.GenericParameterPosition];
}
else
{
instSubstituted[i] = t;
}
}
return GetGenericTypeDefinition().MakeGenericType(instSubstituted);
}
public override Type BaseType
{
// B<A,B,C>
// D<T,S> : B<S,List<T>,char>
// D<string,int> : B<int,List<string>,char>
// D<S,T> : B<T,List<S>,char>
// D<S,string> : B<string,List<S>,char>
get
{
Type typeBldrBase = m_type.BaseType;
if (typeBldrBase == null)
return null;
TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
if (typeBldrBaseAs == null)
return typeBldrBase;
return typeBldrBaseAs.Substitute(GetGenericArguments());
}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; }
public override bool IsSZArray => false;
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { return m_inst; }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return true; } }
public override bool IsConstructedGenericType { get { return true; } }
public override bool IsGenericParameter { get { return false; } }
public override int GenericParameterPosition { get { throw new InvalidOperationException(); } }
protected override bool IsValueTypeImpl() { return m_type.IsValueType; }
public override bool ContainsGenericParameters
{
get
{
for (int i = 0; i < m_inst.Length; i++)
{
if (m_inst[i].ContainsGenericParameters)
return true;
}
return false;
}
}
public override MethodBase DeclaringMethod { get { return null; } }
public override Type GetGenericTypeDefinition() { return m_type; }
public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[Pure]
public override bool IsSubclassOf(Type c)
{
throw new NotSupportedException();
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class File_Move : FileSystemTest
{
#region Utilities
public virtual void Move(string sourceFile, string destFile)
{
File.Move(sourceFile, destFile);
}
#endregion
#region UniversalTests
[Fact]
public void NullPath()
{
Assert.Throws<ArgumentNullException>(() => Move(null, "."));
Assert.Throws<ArgumentNullException>(() => Move(".", null));
}
[Fact]
public void EmptyPath()
{
Assert.Throws<ArgumentException>(() => Move(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Move(".", string.Empty));
}
[Fact]
public virtual void NonExistentPath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Move(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<FileNotFoundException>(() => Move(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void PathWithIllegalCharacters_Desktop(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
}
[ActiveIssue(27269)]
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void PathWithIllegalCharacters_Core(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
if (invalidPath.Contains('\0'.ToString()))
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
else
Assert.ThrowsAny<IOException>(() => Move(testFile.FullName, invalidPath));
}
[Fact]
public void BasicMove()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void MoveNonEmptyFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
using (var stream = testFileSource.Create())
{
var writer = new StreamWriter(stream);
writer.Write("testing\nwrite\n");
writer.Flush();
}
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
Assert.Equal("testing\nwrite\n", File.ReadAllText(testFileDest));
}
[Fact]
public void MoveOntoDirectory()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFile.FullName, TestDirectory));
}
[Fact]
public void MoveOntoExistingFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(GetTestFilePath());
testFileDest.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFileSource.FullName, testFileDest.FullName));
Assert.True(File.Exists(testFileSource.FullName));
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MoveIntoParentDirectory()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, GetTestFileName()));
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(Path.Combine(testDir, "..", GetTestFileName()));
Move(testFileSource.FullName, testFileDest.FullName);
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MoveToSameName()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, GetTestFileName()));
testFileSource.Create().Dispose();
Move(testFileSource.FullName, testFileSource.FullName);
Assert.True(File.Exists(testFileSource.FullName));
}
[Fact]
public void MoveToSameNameDifferentCasing()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, Path.GetRandomFileName().ToLowerInvariant()));
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(Path.Combine(testFileSource.DirectoryName, testFileSource.Name.ToUpperInvariant()));
Move(testFileSource.FullName, testFileDest.FullName);
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MultipleMoves()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest1 = GetTestFilePath();
string testFileDest2 = GetTestFilePath();
Move(testFileSource.FullName, testFileDest1);
Move(testFileDest1, testFileDest2);
Assert.True(File.Exists(testFileDest2));
Assert.False(File.Exists(testFileDest1));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void FileNameWithSignificantWhitespace()
{
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
string testFileDest = Path.Combine(TestDirectory, " e n d");
File.Create(testFileSource).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[PlatformSpecific(TestPlatforms.Windows)] // Path longer than max path limit
public void OverMaxPathWorks_Windows()
{
// Create a destination path longer than the traditional Windows limit of 256 characters,
// but under the long path limitation (32K).
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.True(File.Exists(testFileSource), "test file should exist");
Assert.All(IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()), (path) =>
{
string baseDestinationPath = Path.GetDirectoryName(path);
if (!Directory.Exists(baseDestinationPath))
{
Directory.CreateDirectory(baseDestinationPath);
}
Assert.True(Directory.Exists(baseDestinationPath), "base destination path should exist");
Move(testFileSource, path);
Assert.True(File.Exists(path), "moved test file should exist");
File.Delete(testFileSource);
Assert.False(File.Exists(testFileSource), "source test file should not exist");
Move(path, testFileSource);
Assert.True(File.Exists(testFileSource), "restored test file should exist");
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void LongPath()
{
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.All(IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()), (path) =>
{
AssertExtensions.ThrowsAny<PathTooLongException, FileNotFoundException, DirectoryNotFoundException>(() => Move(testFileSource, path));
File.Delete(testFileSource);
AssertExtensions.ThrowsAny<PathTooLongException, FileNotFoundException, DirectoryNotFoundException>(() => Move(path, testFileSource));
});
}
#endregion
#region PlatformSpecific
[Theory, MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsPathWithIllegalColons_Desktop(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
if (PathFeatures.IsUsingLegacyPathNormalization())
{
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalidPath));
}
else
{
Assert.Throws<NotSupportedException>(() => Move(testFile.FullName, invalidPath));
}
}
[ActiveIssue(27269)]
[Theory, MemberData(nameof(PathsWithInvalidColons))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsPathWithIllegalColons_Core(string invalidPath)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.ThrowsAny<IOException>(() => Move(testFile.FullName, invalidPath));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsWildCharacterPath_Desktop()
{
Assert.Throws<ArgumentException>(() => Move("*", GetTestFilePath()));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "Test*t"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*Test"));
}
[ActiveIssue(27269)]
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsWildCharacterPath_Core()
{
Assert.Throws<FileNotFoundException>(() => Move(Path.Combine(TestDirectory, "*"), GetTestFilePath()));
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), Path.Combine(TestDirectory, "*")));
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), Path.Combine(TestDirectory, "Test*t")));
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), Path.Combine(TestDirectory, "*Test")));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Wild characters in path are allowed
public void UnixWildCharacterPath()
{
string testDir = GetTestFilePath();
string testFileSource = Path.Combine(testDir, "*");
string testFileShouldntMove = Path.Combine(testDir, "*t");
string testFileDest = Path.Combine(testDir, "*" + GetTestFileName());
Directory.CreateDirectory(testDir);
File.Create(testFileSource).Dispose();
File.Create(testFileShouldntMove).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
Move(testFileDest, testFileSource);
Assert.False(File.Exists(testFileDest));
Assert.True(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
}
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public void WindowsControlPath_Desktop(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
}
[ActiveIssue(27269)]
[Theory,
MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void WindowsControlPath_Core(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.ThrowsAny<IOException>(() => Move(testFile.FullName, Path.Combine(TestDirectory, whitespace)));
}
[Theory,
MemberData(nameof(SimpleWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
public void WindowsSimpleWhitespacePath(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace in path allowed
public void UnixWhitespacePath(string whitespace)
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
Move(testFileSource.FullName, Path.Combine(TestDirectory, whitespace));
Move(Path.Combine(TestDirectory, whitespace), testFileSource.FullName);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
/// </summary>
public static swizzle_hvec4 swizzle(hvec4 v) => v.swizzle;
/// <summary>
/// Returns an array with all values
/// </summary>
public static Half[] Values(hvec4 v) => v.Values;
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public static IEnumerator<Half> GetEnumerator(hvec4 v) => v.GetEnumerator();
/// <summary>
/// Returns a string representation of this vector using ', ' as a seperator.
/// </summary>
public static string ToString(hvec4 v) => v.ToString();
/// <summary>
/// Returns a string representation of this vector using a provided seperator.
/// </summary>
public static string ToString(hvec4 v, string sep) => v.ToString(sep);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format provider for each component.
/// </summary>
public static string ToString(hvec4 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format for each component.
/// </summary>
public static string ToString(hvec4 v, string sep, string format) => v.ToString(sep, format);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.
/// </summary>
public static string ToString(hvec4 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);
/// <summary>
/// Returns the number of components (4).
/// </summary>
public static int Count(hvec4 v) => v.Count;
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool Equals(hvec4 v, hvec4 rhs) => v.Equals(rhs);
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public static bool Equals(hvec4 v, object obj) => v.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public static int GetHashCode(hvec4 v) => v.GetHashCode();
/// <summary>
/// Returns true iff distance between lhs and rhs is less than or equal to epsilon
/// </summary>
public static bool ApproxEqual(hvec4 lhs, hvec4 rhs, float eps = 0.1f) => hvec4.ApproxEqual(lhs, rhs, eps);
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec4 Equal(hvec4 lhs, hvec4 rhs) => hvec4.Equal(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec4 NotEqual(hvec4 lhs, hvec4 rhs) => hvec4.NotEqual(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec4 GreaterThan(hvec4 lhs, hvec4 rhs) => hvec4.GreaterThan(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec4 GreaterThanEqual(hvec4 lhs, hvec4 rhs) => hvec4.GreaterThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec4 LesserThan(hvec4 lhs, hvec4 rhs) => hvec4.LesserThan(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec4 LesserThanEqual(hvec4 lhs, hvec4 rhs) => hvec4.LesserThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of IsInfinity (Half.IsInfinity(v)).
/// </summary>
public static bvec4 IsInfinity(hvec4 v) => hvec4.IsInfinity(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsFinite (!Half.IsNaN(v) && !Half.IsInfinity(v)).
/// </summary>
public static bvec4 IsFinite(hvec4 v) => hvec4.IsFinite(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsNaN (Half.IsNaN(v)).
/// </summary>
public static bvec4 IsNaN(hvec4 v) => hvec4.IsNaN(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsNegativeInfinity (Half.IsNegativeInfinity(v)).
/// </summary>
public static bvec4 IsNegativeInfinity(hvec4 v) => hvec4.IsNegativeInfinity(v);
/// <summary>
/// Returns a bvec4 from component-wise application of IsPositiveInfinity (Half.IsPositiveInfinity(v)).
/// </summary>
public static bvec4 IsPositiveInfinity(hvec4 v) => hvec4.IsPositiveInfinity(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Abs (Half.Abs(v)).
/// </summary>
public static hvec4 Abs(hvec4 v) => hvec4.Abs(v);
/// <summary>
/// Returns a hvec4 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
/// </summary>
public static hvec4 HermiteInterpolationOrder3(hvec4 v) => hvec4.HermiteInterpolationOrder3(v);
/// <summary>
/// Returns a hvec4 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
/// </summary>
public static hvec4 HermiteInterpolationOrder5(hvec4 v) => hvec4.HermiteInterpolationOrder5(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Sqr (v * v).
/// </summary>
public static hvec4 Sqr(hvec4 v) => hvec4.Sqr(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Pow2 (v * v).
/// </summary>
public static hvec4 Pow2(hvec4 v) => hvec4.Pow2(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Pow3 (v * v * v).
/// </summary>
public static hvec4 Pow3(hvec4 v) => hvec4.Pow3(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Step (v >= Half.Zero ? Half.One : Half.Zero).
/// </summary>
public static hvec4 Step(hvec4 v) => hvec4.Step(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Sqrt ((Half)Math.Sqrt((double)v)).
/// </summary>
public static hvec4 Sqrt(hvec4 v) => hvec4.Sqrt(v);
/// <summary>
/// Returns a hvec4 from component-wise application of InverseSqrt ((Half)(1.0 / Math.Sqrt((double)v))).
/// </summary>
public static hvec4 InverseSqrt(hvec4 v) => hvec4.InverseSqrt(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Sign (Math.Sign(v)).
/// </summary>
public static ivec4 Sign(hvec4 v) => hvec4.Sign(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Max (Half.Max(lhs, rhs)).
/// </summary>
public static hvec4 Max(hvec4 lhs, hvec4 rhs) => hvec4.Max(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Min (Half.Min(lhs, rhs)).
/// </summary>
public static hvec4 Min(hvec4 lhs, hvec4 rhs) => hvec4.Min(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Pow ((Half)Math.Pow((double)lhs, (double)rhs)).
/// </summary>
public static hvec4 Pow(hvec4 lhs, hvec4 rhs) => hvec4.Pow(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Log ((Half)Math.Log((double)lhs, (double)rhs)).
/// </summary>
public static hvec4 Log(hvec4 lhs, hvec4 rhs) => hvec4.Log(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Clamp (Half.Min(Half.Max(v, min), max)).
/// </summary>
public static hvec4 Clamp(hvec4 v, hvec4 min, hvec4 max) => hvec4.Clamp(v, min, max);
/// <summary>
/// Returns a hvec4 from component-wise application of Mix (min * (1-a) + max * a).
/// </summary>
public static hvec4 Mix(hvec4 min, hvec4 max, hvec4 a) => hvec4.Mix(min, max, a);
/// <summary>
/// Returns a hvec4 from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static hvec4 Lerp(hvec4 min, hvec4 max, hvec4 a) => hvec4.Lerp(min, max, a);
/// <summary>
/// Returns a hvec4 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
/// </summary>
public static hvec4 Smoothstep(hvec4 edge0, hvec4 edge1, hvec4 v) => hvec4.Smoothstep(edge0, edge1, v);
/// <summary>
/// Returns a hvec4 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
/// </summary>
public static hvec4 Smootherstep(hvec4 edge0, hvec4 edge1, hvec4 v) => hvec4.Smootherstep(edge0, edge1, v);
/// <summary>
/// Returns a hvec4 from component-wise application of Fma (a * b + c).
/// </summary>
public static hvec4 Fma(hvec4 a, hvec4 b, hvec4 c) => hvec4.Fma(a, b, c);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static hmat2x4 OuterProduct(hvec4 c, hvec2 r) => hvec4.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static hmat3x4 OuterProduct(hvec4 c, hvec3 r) => hvec4.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static hmat4 OuterProduct(hvec4 c, hvec4 r) => hvec4.OuterProduct(c, r);
/// <summary>
/// Returns a hvec4 from component-wise application of Add (lhs + rhs).
/// </summary>
public static hvec4 Add(hvec4 lhs, hvec4 rhs) => hvec4.Add(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Sub (lhs - rhs).
/// </summary>
public static hvec4 Sub(hvec4 lhs, hvec4 rhs) => hvec4.Sub(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Mul (lhs * rhs).
/// </summary>
public static hvec4 Mul(hvec4 lhs, hvec4 rhs) => hvec4.Mul(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Div (lhs / rhs).
/// </summary>
public static hvec4 Div(hvec4 lhs, hvec4 rhs) => hvec4.Div(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Modulo (lhs % rhs).
/// </summary>
public static hvec4 Modulo(hvec4 lhs, hvec4 rhs) => hvec4.Modulo(lhs, rhs);
/// <summary>
/// Returns a hvec4 from component-wise application of Degrees (Radians-To-Degrees Conversion).
/// </summary>
public static hvec4 Degrees(hvec4 v) => hvec4.Degrees(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Radians (Degrees-To-Radians Conversion).
/// </summary>
public static hvec4 Radians(hvec4 v) => hvec4.Radians(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Acos ((Half)Math.Acos((double)v)).
/// </summary>
public static hvec4 Acos(hvec4 v) => hvec4.Acos(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Asin ((Half)Math.Asin((double)v)).
/// </summary>
public static hvec4 Asin(hvec4 v) => hvec4.Asin(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Atan ((Half)Math.Atan((double)v)).
/// </summary>
public static hvec4 Atan(hvec4 v) => hvec4.Atan(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Cos ((Half)Math.Cos((double)v)).
/// </summary>
public static hvec4 Cos(hvec4 v) => hvec4.Cos(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Cosh ((Half)Math.Cosh((double)v)).
/// </summary>
public static hvec4 Cosh(hvec4 v) => hvec4.Cosh(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Exp ((Half)Math.Exp((double)v)).
/// </summary>
public static hvec4 Exp(hvec4 v) => hvec4.Exp(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Log ((Half)Math.Log((double)v)).
/// </summary>
public static hvec4 Log(hvec4 v) => hvec4.Log(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Log2 ((Half)Math.Log((double)v, 2)).
/// </summary>
public static hvec4 Log2(hvec4 v) => hvec4.Log2(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Log10 ((Half)Math.Log10((double)v)).
/// </summary>
public static hvec4 Log10(hvec4 v) => hvec4.Log10(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Floor ((Half)Math.Floor(v)).
/// </summary>
public static hvec4 Floor(hvec4 v) => hvec4.Floor(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Ceiling ((Half)Math.Ceiling(v)).
/// </summary>
public static hvec4 Ceiling(hvec4 v) => hvec4.Ceiling(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Round ((Half)Math.Round(v)).
/// </summary>
public static hvec4 Round(hvec4 v) => hvec4.Round(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Sin ((Half)Math.Sin((double)v)).
/// </summary>
public static hvec4 Sin(hvec4 v) => hvec4.Sin(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Sinh ((Half)Math.Sinh((double)v)).
/// </summary>
public static hvec4 Sinh(hvec4 v) => hvec4.Sinh(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Tan ((Half)Math.Tan((double)v)).
/// </summary>
public static hvec4 Tan(hvec4 v) => hvec4.Tan(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Tanh ((Half)Math.Tanh((double)v)).
/// </summary>
public static hvec4 Tanh(hvec4 v) => hvec4.Tanh(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Truncate ((Half)Math.Truncate((double)v)).
/// </summary>
public static hvec4 Truncate(hvec4 v) => hvec4.Truncate(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Fract ((Half)(v - Math.Floor(v))).
/// </summary>
public static hvec4 Fract(hvec4 v) => hvec4.Fract(v);
/// <summary>
/// Returns a hvec4 from component-wise application of Trunc ((long)(v)).
/// </summary>
public static hvec4 Trunc(hvec4 v) => hvec4.Trunc(v);
/// <summary>
/// Returns the minimal component of this vector.
/// </summary>
public static Half MinElement(hvec4 v) => v.MinElement;
/// <summary>
/// Returns the maximal component of this vector.
/// </summary>
public static Half MaxElement(hvec4 v) => v.MaxElement;
/// <summary>
/// Returns the euclidean length of this vector.
/// </summary>
public static float Length(hvec4 v) => v.Length;
/// <summary>
/// Returns the squared euclidean length of this vector.
/// </summary>
public static float LengthSqr(hvec4 v) => v.LengthSqr;
/// <summary>
/// Returns the sum of all components.
/// </summary>
public static Half Sum(hvec4 v) => v.Sum;
/// <summary>
/// Returns the euclidean norm of this vector.
/// </summary>
public static float Norm(hvec4 v) => v.Norm;
/// <summary>
/// Returns the one-norm of this vector.
/// </summary>
public static float Norm1(hvec4 v) => v.Norm1;
/// <summary>
/// Returns the two-norm (euclidean length) of this vector.
/// </summary>
public static float Norm2(hvec4 v) => v.Norm2;
/// <summary>
/// Returns the max-norm of this vector.
/// </summary>
public static float NormMax(hvec4 v) => v.NormMax;
/// <summary>
/// Returns the p-norm of this vector.
/// </summary>
public static double NormP(hvec4 v, double p) => v.NormP(p);
/// <summary>
/// Returns a copy of this vector with length one (undefined if this has zero length).
/// </summary>
public static hvec4 Normalized(hvec4 v) => v.Normalized;
/// <summary>
/// Returns a copy of this vector with length one (returns zero if length is zero).
/// </summary>
public static hvec4 NormalizedSafe(hvec4 v) => v.NormalizedSafe;
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two vectors.
/// </summary>
public static Half Dot(hvec4 lhs, hvec4 rhs) => hvec4.Dot(lhs, rhs);
/// <summary>
/// Returns the euclidean distance between the two vectors.
/// </summary>
public static float Distance(hvec4 lhs, hvec4 rhs) => hvec4.Distance(lhs, rhs);
/// <summary>
/// Returns the squared euclidean distance between the two vectors.
/// </summary>
public static float DistanceSqr(hvec4 lhs, hvec4 rhs) => hvec4.DistanceSqr(lhs, rhs);
/// <summary>
/// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result).
/// </summary>
public static hvec4 Reflect(hvec4 I, hvec4 N) => hvec4.Reflect(I, N);
/// <summary>
/// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result).
/// </summary>
public static hvec4 Refract(hvec4 I, hvec4 N, Half eta) => hvec4.Refract(I, N, eta);
/// <summary>
/// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N).
/// </summary>
public static hvec4 FaceForward(hvec4 N, hvec4 I, hvec4 Nref) => hvec4.FaceForward(N, I, Nref);
/// <summary>
/// Returns a hvec4 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static hvec4 Random(Random random, hvec4 minValue, hvec4 maxValue) => hvec4.Random(random, minValue, maxValue);
/// <summary>
/// Returns a hvec4 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
/// </summary>
public static hvec4 RandomUniform(Random random, hvec4 minValue, hvec4 maxValue) => hvec4.RandomUniform(random, minValue, maxValue);
/// <summary>
/// Returns a hvec4 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static hvec4 RandomNormal(Random random, hvec4 mean, hvec4 variance) => hvec4.RandomNormal(random, mean, variance);
/// <summary>
/// Returns a hvec4 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
/// </summary>
public static hvec4 RandomGaussian(Random random, hvec4 mean, hvec4 variance) => hvec4.RandomGaussian(random, mean, variance);
}
}
| |
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.Reflection;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
namespace Signum.Engine
{
public static class BulkInserter
{
const SqlBulkCopyOptions SafeDefaults = SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.KeepNulls;
public static int BulkInsert<T>(this IEnumerable<T> entities,
SqlBulkCopyOptions copyOptions = SafeDefaults,
bool preSaving = true,
bool validateFirst = true,
bool disableIdentity = false,
int? timeout = null,
string? message = null)
where T : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsert), () => typeof(T).TypeName()))
using (Transaction tr = new Transaction())
{
var table = Schema.Current.Table(typeof(T));
if (!disableIdentity && table.IdentityBehaviour && table.TablesMList().Any())
throw new InvalidOperationException($@"Table {typeof(T)} contains MList but the entities have no IDs. Consider:
* Using BulkInsertQueryIds, that queries the inserted rows and uses the IDs to insert the MList elements.
* Set {nameof(disableIdentity)} = true, and set manually the Ids of the entities before inseting using {nameof(UnsafeEntityExtensions.SetId)}.
* If you know what you doing, call ${nameof(BulkInsertTable)} manually (MList wont be saved)."
);
var list = entities.ToList();
var rowNum = BulkInsertTable(list, copyOptions, preSaving, validateFirst, disableIdentity, timeout, message);
BulkInsertMLists<T>(list, copyOptions, timeout, message);
return tr.Commit(rowNum);
}
}
/// <param name="keySelector">Unique key to retrieve ids</param>
/// <param name="isNewPredicate">Optional filter to query only the recently inseted entities</param>
public static int BulkInsertQueryIds<T, K>(this IEnumerable<T> entities,
Expression<Func<T, K>> keySelector,
Expression<Func<T, bool>>? isNewPredicate = null,
SqlBulkCopyOptions copyOptions = SafeDefaults,
bool preSaving = true,
bool validateFirst = true,
int? timeout = null,
string? message = null)
where T : Entity
where K : notnull
{
using (HeavyProfiler.Log(nameof(BulkInsertQueryIds), () => typeof(T).TypeName()))
using (Transaction tr = new Transaction())
{
var t = Schema.Current.Table(typeof(T));
var list = entities.ToList();
if (isNewPredicate == null)
isNewPredicate = GetFilterAutomatic<T>(t);
var rowNum = BulkInsertTable<T>(list, copyOptions, preSaving, validateFirst, false, timeout, message);
var dictionary = Database.Query<T>().Where(isNewPredicate).Select(a => KeyValuePair.Create(keySelector.Evaluate(a), a.Id)).ToDictionaryEx();
var getKeyFunc = keySelector.Compile();
list.ForEach(e =>
{
e.SetId(dictionary.GetOrThrow(getKeyFunc(e)));
e.SetIsNew(false);
});
BulkInsertMLists(list, copyOptions, timeout, message);
GraphExplorer.CleanModifications(GraphExplorer.FromRoots(list));
return tr.Commit(rowNum);
}
}
static void BulkInsertMLists<T>(List<T> list, SqlBulkCopyOptions options, int? timeout, string? message) where T : Entity
{
var mlistPrs = PropertyRoute.GenerateRoutes(typeof(T), includeIgnored: false).Where(a => a.PropertyRouteType == PropertyRouteType.FieldOrProperty && a.Type.IsMList()).ToList();
foreach (var pr in mlistPrs)
{
giBulkInsertMListFromEntities.GetInvoker(typeof(T), pr.Type.ElementType()!)(list, pr, options, timeout, message);
}
}
static Expression<Func<T, bool>> GetFilterAutomatic<T>(Table table) where T : Entity
{
if (table.PrimaryKey.Identity)
{
var max = ExecutionMode.Global().Using(_ => Database.Query<T>().Max(a => (PrimaryKey?)a.Id));
if (max == null)
return a => true;
return a => a.Id > max;
}
var count = ExecutionMode.Global().Using(_ => Database.Query<T>().Count());
if (count == 0)
return a => true;
throw new InvalidOperationException($"Impossible to determine the filter for the IDs query automatically because the table is not Identity and has rows");
}
public static int BulkInsertTable<T>(IEnumerable<T> entities,
SqlBulkCopyOptions copyOptions = SafeDefaults,
bool preSaving = true,
bool validateFirst = true,
bool disableIdentity = false,
int? timeout = null,
string? message = null)
where T : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsertTable), () => typeof(T).TypeName()))
{
if (message != null)
return SafeConsole.WaitRows(message == "auto" ? $"BulkInsering {entities.Count()} {typeof(T).TypeName()}" : message,
() => BulkInsertTable(entities, copyOptions, preSaving, validateFirst, disableIdentity, timeout, message: null));
if (disableIdentity)
copyOptions |= SqlBulkCopyOptions.KeepIdentity;
if (copyOptions.HasFlag(SqlBulkCopyOptions.UseInternalTransaction))
throw new InvalidOperationException("BulkInsertDisableIdentity not compatible with UseInternalTransaction");
var list = entities.ToList();
if (preSaving)
{
Saver.PreSaving(() => GraphExplorer.FromRoots(list));
}
if (validateFirst)
{
Validate<T>(list);
}
var t = Schema.Current.Table<T>();
bool disableIdentityBehaviour = copyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);
DataTable dt = new DataTable();
var columns = t.Columns.Values.Where(c => !(c is SystemVersionedInfo.SqlServerPeriodColumn) && (disableIdentityBehaviour || !c.IdentityBehaviour)).ToList();
foreach (var c in columns)
dt.Columns.Add(new DataColumn(c.Name, ConvertType(c.Type)));
using (disableIdentityBehaviour ? Administrator.DisableIdentity(t, behaviourOnly: true) : null)
{
foreach (var e in list)
{
if (!e.IsNew)
throw new InvalidOperationException("Entites should be new");
t.SetToStrField(e);
dt.Rows.Add(t.BulkInsertDataRow(e));
}
}
using (Transaction tr = new Transaction())
{
Schema.Current.OnPreBulkInsert(typeof(T), inMListTable: false);
Executor.BulkCopy(dt, columns, t.Name, copyOptions, timeout);
foreach (var item in list)
item.SetNotModified();
return tr.Commit(list.Count);
}
}
}
private static Type ConvertType(Type type)
{
var result = type.UnNullify();
if (result == typeof(Date))
return typeof(DateTime);
return result;
}
static void Validate<T>(IEnumerable<T> entities) where T : Entity
{
foreach (var e in entities)
{
var ic = e.FullIntegrityCheck();
if (ic != null)
{
#if DEBUG
var withEntites = ic.WithEntities(GraphExplorer.FromRoots(entities));
throw new IntegrityCheckException(withEntites);
#else
throw new IntegrityCheckException(ic);
#endif
}
}
}
static readonly GenericInvoker<Func<IList, PropertyRoute, SqlBulkCopyOptions, int?, string?, int>> giBulkInsertMListFromEntities =
new GenericInvoker<Func<IList, PropertyRoute, SqlBulkCopyOptions, int?, string?, int>>((entities, propertyRoute, options, timeout, message) =>
BulkInsertMListTablePropertyRoute<Entity, string>((List<Entity>)entities, propertyRoute, options, timeout, message));
static int BulkInsertMListTablePropertyRoute<E, V>(List<E> entities, PropertyRoute route, SqlBulkCopyOptions copyOptions, int? timeout, string? message)
where E : Entity
{
return BulkInsertMListTable<E, V>(entities, route.GetLambdaExpression<E, MList<V>>(safeNullAccess: false), copyOptions, timeout, message);
}
public static int BulkInsertMListTable<E, V>(
List<E> entities,
Expression<Func<E, MList<V>>> mListProperty,
SqlBulkCopyOptions copyOptions = SafeDefaults,
int? timeout = null,
string? message = null)
where E : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsertMListTable), () => $"{mListProperty} ({typeof(E).TypeName()})"))
{
try
{
var func = PropertyRoute.Construct(mListProperty).GetLambdaExpression<E, MList<V>>(safeNullAccess: true).Compile();
var mlistElements = (from e in entities
from mle in func(e).EmptyIfNull().Select((iw, i) => new MListElement<E, V>
{
Order = i,
Element = iw,
Parent = e,
})
select mle).ToList();
return BulkInsertMListTable(mlistElements, mListProperty, copyOptions, timeout, updateParentTicks: false, message: message);
}
catch (InvalidOperationException e) when (e.Message.Contains("has no Id"))
{
throw new InvalidOperationException($"{nameof(BulkInsertMListTable)} requires that you set the Id of the entities manually using {nameof(UnsafeEntityExtensions.SetId)}");
}
}
}
public static int BulkInsertMListTable<E, V>(
this IEnumerable<MListElement<E, V>> mlistElements,
Expression<Func<E, MList<V>>> mListProperty,
SqlBulkCopyOptions copyOptions = SafeDefaults,
int? timeout = null,
bool? updateParentTicks = null, /*Needed for concurrency and Temporal tables*/
string? message = null)
where E : Entity
{
using (HeavyProfiler.Log(nameof(BulkInsertMListTable), () => $"{mListProperty} ({typeof(MListElement<E, V>).TypeName()})"))
{
if (message != null)
return SafeConsole.WaitRows(message == "auto" ? $"BulkInsering MList<{ typeof(V).TypeName()}> in { typeof(E).TypeName()}" : message,
() => BulkInsertMListTable(mlistElements, mListProperty, copyOptions, timeout, updateParentTicks, message: null));
if (copyOptions.HasFlag(SqlBulkCopyOptions.UseInternalTransaction))
throw new InvalidOperationException("BulkInsertDisableIdentity not compatible with UseInternalTransaction");
var mlistTable = ((FieldMList)Schema.Current.Field(mListProperty)).TableMList;
if (updateParentTicks == null)
{
updateParentTicks = mlistTable.PrimaryKey.Type != typeof(Guid) && mlistTable.BackReference.ReferenceTable.Ticks != null;
}
var maxRowId = updateParentTicks.Value ? Database.MListQuery(mListProperty).Max(a => (PrimaryKey?)a.RowId) : null;
DataTable dt = new DataTable();
var columns = mlistTable.Columns.Values.Where(c => !(c is SystemVersionedInfo.SqlServerPeriodColumn) && !c.IdentityBehaviour).ToList();
foreach (var c in columns)
dt.Columns.Add(new DataColumn(c.Name, ConvertType(c.Type)));
var list = mlistElements.ToList();
foreach (var e in list)
{
dt.Rows.Add(mlistTable.BulkInsertDataRow(e.Parent, e.Element!, e.Order));
}
using (Transaction tr = new Transaction())
{
Schema.Current.OnPreBulkInsert(typeof(E), inMListTable: true);
Executor.BulkCopy(dt, columns, mlistTable.Name, copyOptions, timeout);
var result = list.Count;
if (updateParentTicks.Value)
{
Database.MListQuery(mListProperty)
.Where(a => maxRowId == null || a.RowId > maxRowId)
.Select(a => a.Parent)
.UnsafeUpdate()
.Set(e => e.Ticks, a => TimeZoneManager.Now.Ticks)
.Execute();
}
return tr.Commit(result);
}
}
}
public static int BulkInsertView<T>(this IEnumerable<T> entities,
SqlBulkCopyOptions copyOptions = SafeDefaults,
int? timeout = null,
string? message = null)
where T : IView
{
using (HeavyProfiler.Log(nameof(BulkInsertView), () => typeof(T).Name))
{
if (message != null)
return SafeConsole.WaitRows(message == "auto" ? $"BulkInsering {entities.Count()} {typeof(T).TypeName()}" : message,
() => BulkInsertView(entities, copyOptions, timeout, message: null));
if (copyOptions.HasFlag(SqlBulkCopyOptions.UseInternalTransaction))
throw new InvalidOperationException("BulkInsertDisableIdentity not compatible with UseInternalTransaction");
var t = Schema.Current.View<T>();
var list = entities.ToList();
bool disableIdentityBehaviour = copyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);
var columns = t.Columns.Values.ToList();
DataTable dt = new DataTable();
foreach (var c in columns)
dt.Columns.Add(new DataColumn(c.Name, ConvertType(c.Type)));
foreach (var e in entities)
{
dt.Rows.Add(t.BulkInsertDataRow(e));
}
using (Transaction tr = new Transaction())
{
Schema.Current.OnPreBulkInsert(typeof(T), inMListTable: false);
Executor.BulkCopy(dt, columns, t.Name, copyOptions, timeout);
return tr.Commit(list.Count);
}
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* 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.Threading;
using Common.Logging;
using Spring.Collections;
using Spring.Messaging.Nms.Core;
using Spring.Messaging.Nms.Support;
using Apache.NMS;
using Spring.Transaction.Support;
using Spring.Util;
namespace Spring.Messaging.Nms.Listener
{
/// <summary>
/// Message listener container that uses the plain NMS client API's
/// MessageConsumer.Listener method to create concurrent
/// MessageConsumers for the specified listeners.
/// </summary>
/// <author>Mark Pollack</author>
public class SimpleMessageListenerContainer : AbstractMessageListenerContainer, IExceptionListener
{
#region Logging
private readonly ILog logger = LogManager.GetLogger(typeof(SimpleMessageListenerContainer));
#endregion
#region fields
/// <summary>
/// The default recovery time interval between connection reconnection attempts
/// </summary>
public static string DEFAULT_RECOVERY_INTERVAL = "5s";
/// <summary>
/// The total time connection recovery will be attempted.
/// </summary>
public static string DEFAULT_MAX_RECOVERY_TIME = "10m";
private bool pubSubNoLocal = false;
private int concurrentConsumers = 1;
private ISet sessions;
private ISet consumers;
private object consumersMonitor = new object();
private TimeSpan recoveryInterval = new TimeSpan(0, 0, 0, 5, 0);
private TimeSpan maxRecoveryTime = new TimeSpan(0, 0, 10, 0, 0);
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether to inhibit the delivery of messages published by its own connection.
/// Default is "false".
/// </summary>
/// <value><c>true</c> if should inhibit the delivery of messages published by its own connection; otherwise, <c>false</c>.</value>
public bool PubSubNoLocal
{
get { return pubSubNoLocal; }
set { pubSubNoLocal = value; }
}
/// <summary>
/// Specify the number of concurrent consumers to create. Default is 1.
/// </summary>
/// <remarks>
/// Raising the number of concurrent consumers is recommendable in order
/// to scale the consumption of messages coming in from a queue. However,
/// note that any ordering guarantees are lost once multiple consumers are
/// registered. In general, stick with 1 consumer for low-volume queues.
/// <para>Do not raise the number of concurrent consumers for a topic.
/// This would lead to concurrent consumption of the same message,
/// which is hardly ever desirable.
/// </para>
/// </remarks>
/// <value>The concurrent consumers.</value>
public int ConcurrentConsumers
{
set
{
AssertUtils.IsTrue(value > 0, "'ConcurrentConsumer' value must be at least 1 (one)");
concurrentConsumers = value;
}
}
/// <summary>
/// Sets the time interval between connection recovery attempts. The default is 5 seconds.
/// </summary>
/// <value>The recovery interval.</value>
public TimeSpan RecoveryInterval
{
set { recoveryInterval = value; }
}
/// <summary>
/// Sets the max recovery time to try reconnection attempts. The default is 10 minutes.
/// </summary>
/// <value>The max recovery time.</value>
public TimeSpan MaxRecoveryTime
{
set { maxRecoveryTime = value; }
}
/// <summary>
/// Always use a shared NMS connection
/// </summary>
protected override bool SharedConnectionEnabled
{
get { return true; }
}
#endregion
/// <summary>
/// Call base class for valdation and then check that if the subscription is durable that the number of
/// concurrent consumers is equal to one.
/// </summary>
protected override void ValidateConfiguration()
{
base.ValidateConfiguration();
if (SubscriptionDurable && concurrentConsumers !=1 )
{
throw new ArgumentException("Only 1 concurrent consumer supported for durable subscription");
}
}
/// <summary>
/// Creates the specified number of concurrent consumers,
/// in the form of a JMS Session plus associated MessageConsumer
/// </summary>
/// <see cref="CreateListenerConsumer"/>
protected override void DoInitialize()
{
EstablishSharedConnection();
InitializeConsumers();
}
/// <summary>
/// Re-initializes this container's NMS message consumers,
/// if not initialized already.
/// </summary>
protected override void DoStart()
{
base.DoStart();
InitializeConsumers();
}
/// <summary>
/// Registers this listener container as NMS ExceptionListener on the shared connection.
/// </summary>
/// <param name="connection"></param>
protected override void PrepareSharedConnection(IConnection connection)
{
base.PrepareSharedConnection(connection);
connection.ExceptionListener += OnException;
}
/// <summary>
/// <see cref="IExceptionListener"/> implementation, invoked by the NMS provider in
/// case of connection failures. Re-initializes this listener container's
/// shared connection and its sessions and consumers.
/// </summary>
/// <param name="exception">The reported connection exception.</param>
public void OnException(Exception exception)
{
// First invoke the user-specific ExceptionListener, if any.
InvokeExceptionListener(exception);
// now try to recover the shared Connection and all consumers...
if (logger.IsInfoEnabled)
{
logger.Info("Trying to recover from NMS Connection exception: " + exception);
}
try
{
lock (consumersMonitor)
{
sessions = null;
consumers = null;
}
RefreshConnectionUntilSuccessful();
InitializeConsumers();
logger.Info("Successfully refreshed NMS Connection");
} catch (RecoveryTimeExceededException)
{
throw;
} catch (Exception recoverEx)
{
logger.Debug("Failed to recover NMS Connection", recoverEx);
logger.Error("Encountered non-recoverable Exception", exception);
throw;
}
}
/// <summary>
/// Refresh the underlying Connection, not returning before an attempt has been
/// successful. Called in case of a shared Connection as well as without shared
/// Connection, so either needs to operate on the shared Connection or on a
/// temporary Connection that just gets established for validation purposes.
/// </summary>
/// <remarks>
/// The default implementation retries until it successfully established a
/// Connection, for as long as this message listener container is active.
/// Applies the specified recovery interval between retries.
/// </remarks>
protected virtual void RefreshConnectionUntilSuccessful()
{
TimeSpan totalTryTime = new TimeSpan();
while (IsRunning)
{
try
{
RefreshSharedConnection();
break;
} catch (Exception ex)
{
if (logger.IsInfoEnabled)
{
logger.Info("Could not refresh Connection - retrying in " + recoveryInterval, ex);
}
}
if (totalTryTime > maxRecoveryTime)
{
logger.Info("Could not refresh Connection after " + totalTryTime + ". Stopping reconnection attempts.");
throw new RecoveryTimeExceededException("Could not recover after " + totalTryTime);
}
DateTime startTime = DateTime.Now;
SleepInBetweenRecoveryAttempts();
TimeSpan sleepTimeSpan = DateTime.Now - startTime;
totalTryTime += sleepTimeSpan;
}
}
/// <summary>
/// The amount of time to sleep in between recovery attempts.
/// </summary>
protected virtual void SleepInBetweenRecoveryAttempts()
{
Thread.Sleep(recoveryInterval);
}
/// <summary>
/// Initialize the Sessions and MessageConsumers for this container.
/// </summary>
/// <exception cref="NMSException">in case of setup failure.</exception>
protected virtual void InitializeConsumers()
{
// Register Sessions and MessageConsumers
lock (consumersMonitor)
{
if (this.consumers == null)
{
this.sessions = new HashedSet();
this.consumers = new HashedSet();
IConnection con = SharedConnection;
for (int i = 0; i < this.concurrentConsumers; i++)
{
ISession session = CreateSession(SharedConnection);
IMessageConsumer consumer = CreateListenerConsumer(session);
this.sessions.Add(session);
this.consumers.Add(consumer);
}
}
}
}
/// <summary>
/// Creates a MessageConsumer for the given Session,
/// registering a MessageListener for the specified listener
/// </summary>
/// <param name="session">The session to work on.</param>
/// <returns>the MessageConsumer"/></returns>
/// <exception cref="NMSException">if thrown by NMS methods</exception>
private IMessageConsumer CreateListenerConsumer(ISession session)
{
IDestination destination = Destination;
if (destination == null)
{
destination = ResolveDestinationName(session, DestinationName);
}
IMessageConsumer consumer = CreateConsumer(session, destination);
SimpleMessageListener listener = new SimpleMessageListener(this, session);
// put in explicit registration with 'new' for compilation on .NET 1.1
consumer.Listener += listener.OnMessage;
return consumer;
}
/// <summary>
/// Close the message consumers and sessions.
/// </summary>
/// <throws>NMSException if destruction failed </throws>
protected override void DoShutdown()
{
lock (consumersMonitor)
{
if (consumers != null)
{
logger.Debug("Closing NMS MessageConsumers");
foreach (IMessageConsumer messageConsumer in consumers)
{
NmsUtils.CloseMessageConsumer(messageConsumer);
}
}
if (sessions != null)
{
logger.Debug("Closing NMS Sessions");
foreach (ISession session in sessions)
{
NmsUtils.CloseSession(session);
}
}
consumers = null;
sessions = null;
}
}
/// <summary>
/// Creates a MessageConsumer for the given Session and Destination.
/// </summary>
/// <param name="session">The session to create a MessageConsumer for.</param>
/// <param name="destination">The destination to create a MessageConsumer for.</param>
/// <returns>The new MessageConsumer</returns>
protected IMessageConsumer CreateConsumer(ISession session, IDestination destination)
{
// Only pass in the NoLocal flag in case of a Topic:
// Some NMS providers, such as WebSphere MQ 6.0, throw IllegalStateException
// in case of the NoLocal flag being specified for a Queue.
if (PubSubDomain)
{
if (SubscriptionDurable && destination is ITopic)
{
return session.CreateDurableConsumer(
(ITopic) destination, DurableSubscriptionName, MessageSelector, PubSubNoLocal);
}
else
{
return session.CreateConsumer(destination, MessageSelector, PubSubNoLocal);
}
}
else
{
return session.CreateConsumer(destination, MessageSelector);
}
}
}
internal class SimpleMessageListener : IMessageListener
{
private SimpleMessageListenerContainer container;
private ISession session;
public SimpleMessageListener(SimpleMessageListenerContainer container, ISession session)
{
this.container = container;
this.session = session;
}
public void OnMessage(IMessage message)
{
bool exposeResource = container.ExposeListenerSession;
if (exposeResource)
{
TransactionSynchronizationManager.BindResource(
container.ConnectionFactory, new LocallyExposedNmsResourceHolder(session));
}
try
{
container.ExecuteListener(session, message);
} finally
{
if (exposeResource)
{
TransactionSynchronizationManager.UnbindResource(container.ConnectionFactory);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Finance.Service.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: iam/rpc/department_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.IAM.RPC {
public static partial class DepartmentSvc
{
static readonly string __ServiceName = "holms.types.iam.rpc.DepartmentSvc";
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse> __Marshaller_DepartmentSvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.IAM.DepartmentIndicator> __Marshaller_DepartmentIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.IAM.DepartmentIndicator.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.IAM.Department> __Marshaller_Department = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.IAM.Department.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse>(
grpc::MethodType.Unary,
__ServiceName,
"All",
__Marshaller_Empty,
__Marshaller_DepartmentSvcAllResponse);
static readonly grpc::Method<global::HOLMS.Types.IAM.DepartmentIndicator, global::HOLMS.Types.IAM.Department> __Method_GetById = new grpc::Method<global::HOLMS.Types.IAM.DepartmentIndicator, global::HOLMS.Types.IAM.Department>(
grpc::MethodType.Unary,
__ServiceName,
"GetById",
__Marshaller_DepartmentIndicator,
__Marshaller_Department);
static readonly grpc::Method<global::HOLMS.Types.IAM.Department, global::HOLMS.Types.IAM.Department> __Method_Create = new grpc::Method<global::HOLMS.Types.IAM.Department, global::HOLMS.Types.IAM.Department>(
grpc::MethodType.Unary,
__ServiceName,
"Create",
__Marshaller_Department,
__Marshaller_Department);
static readonly grpc::Method<global::HOLMS.Types.IAM.Department, global::HOLMS.Types.IAM.Department> __Method_Update = new grpc::Method<global::HOLMS.Types.IAM.Department, global::HOLMS.Types.IAM.Department>(
grpc::MethodType.Unary,
__ServiceName,
"Update",
__Marshaller_Department,
__Marshaller_Department);
static readonly grpc::Method<global::HOLMS.Types.IAM.Department, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.IAM.Department, global::HOLMS.Types.Primitive.ServerActionConfirmation>(
grpc::MethodType.Unary,
__ServiceName,
"Delete",
__Marshaller_Department,
__Marshaller_ServerActionConfirmation);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.IAM.RPC.DepartmentSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of DepartmentSvc</summary>
public abstract partial class DepartmentSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.IAM.Department> GetById(global::HOLMS.Types.IAM.DepartmentIndicator request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.IAM.Department> Create(global::HOLMS.Types.IAM.Department request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.IAM.Department> Update(global::HOLMS.Types.IAM.Department request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.IAM.Department request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for DepartmentSvc</summary>
public partial class DepartmentSvcClient : grpc::ClientBase<DepartmentSvcClient>
{
/// <summary>Creates a new client for DepartmentSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public DepartmentSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for DepartmentSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public DepartmentSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected DepartmentSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected DepartmentSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return All(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.RPC.DepartmentSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request);
}
public virtual global::HOLMS.Types.IAM.Department GetById(global::HOLMS.Types.IAM.DepartmentIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.IAM.Department GetById(global::HOLMS.Types.IAM.DepartmentIndicator request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.Department> GetByIdAsync(global::HOLMS.Types.IAM.DepartmentIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.Department> GetByIdAsync(global::HOLMS.Types.IAM.DepartmentIndicator request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request);
}
public virtual global::HOLMS.Types.IAM.Department Create(global::HOLMS.Types.IAM.Department request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.IAM.Department Create(global::HOLMS.Types.IAM.Department request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.Department> CreateAsync(global::HOLMS.Types.IAM.Department request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.Department> CreateAsync(global::HOLMS.Types.IAM.Department request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request);
}
public virtual global::HOLMS.Types.IAM.Department Update(global::HOLMS.Types.IAM.Department request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.IAM.Department Update(global::HOLMS.Types.IAM.Department request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.Department> UpdateAsync(global::HOLMS.Types.IAM.Department request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.IAM.Department> UpdateAsync(global::HOLMS.Types.IAM.Department request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request);
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.IAM.Department request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.IAM.Department request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.IAM.Department request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.IAM.Department request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override DepartmentSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new DepartmentSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(DepartmentSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_All, serviceImpl.All)
.AddMethod(__Method_GetById, serviceImpl.GetById)
.AddMethod(__Method_Create, serviceImpl.Create)
.AddMethod(__Method_Update, serviceImpl.Update)
.AddMethod(__Method_Delete, serviceImpl.Delete).Build();
}
}
}
#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.Diagnostics;
using System.Reflection;
using Xunit;
namespace System.Linq.Tests
{
public class ToLookupTests : EnumerableTests
{
private static void AssertMatches<K, T>(IEnumerable<K> keys, IEnumerable<T> elements, System.Linq.ILookup<K, T> lookup)
{
Assert.NotNull(lookup);
Assert.NotNull(keys);
Assert.NotNull(elements);
int num = 0;
using (IEnumerator<K> keyEnumerator = keys.GetEnumerator())
using (IEnumerator<T> elEnumerator = elements.GetEnumerator())
{
while (keyEnumerator.MoveNext())
{
Assert.True(lookup.Contains(keyEnumerator.Current));
foreach (T e in lookup[keyEnumerator.Current])
{
Assert.True(elEnumerator.MoveNext());
Assert.Equal(e, elEnumerator.Current);
}
++num;
}
Assert.False(elEnumerator.MoveNext());
}
Assert.Equal(num, lookup.Count);
}
[Fact]
public void SameResultsRepeatCall()
{
var q1 = from x1 in new string[] { "Alen", "Felix", null, null, "X", "Have Space", "Clinton", "" }
select x1; ;
var q2 = from x2 in new int[] { 55, 49, 9, -100, 24, 25, -1, 0 }
select x2;
var q = from x3 in q1
from x4 in q2
select new { a1 = x3, a2 = x4 };
Assert.Equal(q.ToLookup(e => e.a1), q.ToLookup(e => e.a1));
}
[Fact]
public void NullKeyIncluded()
{
string[] key = { "Chris", "Bob", null, "Tim" };
int[] element = { 50, 95, 55, 90 };
var source = key.Zip(element, (k, e) => new { Name = k, Score = e });
AssertMatches(key, source, source.ToLookup(e => e.Name));
}
[Fact]
public void OneElementCustomComparer()
{
string[] key = { "Chris" };
int[] element = { 50 };
var source = new [] { new {Name = "risCh", Score = 50} };
AssertMatches(key, source, source.ToLookup(e => e.Name, new AnagramEqualityComparer()));
}
[Fact]
public void UniqueElementsElementSelector()
{
string[] key = { "Chris", "Prakash", "Tim", "Robert", "Brian" };
int[] element = { 50, 100, 95, 60, 80 };
var source = new []
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[1] },
new { Name = key[2], Score = element[2] },
new { Name = key[3], Score = element[3] },
new { Name = key[4], Score = element[4] }
};
AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score));
}
[Fact]
public void DuplicateKeys()
{
string[] key = { "Chris", "Prakash", "Robert" };
int[] element = { 50, 80, 100, 95, 99, 56 };
var source = new[]
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[2] },
new { Name = key[2], Score = element[5] },
new { Name = key[1], Score = element[3] },
new { Name = key[0], Score = element[1] },
new { Name = key[1], Score = element[4] }
};
AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void RunOnce()
{
string[] key = { "Chris", "Prakash", "Robert" };
int[] element = { 50, 80, 100, 95, 99, 56 };
var source = new[]
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[2] },
new { Name = key[2], Score = element[5] },
new { Name = key[1], Score = element[3] },
new { Name = key[0], Score = element[1] },
new { Name = key[1], Score = element[4] }
};
AssertMatches(key, element, source.RunOnce().ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void Count()
{
string[] key = { "Chris", "Prakash", "Robert" };
int[] element = { 50, 80, 100, 95, 99, 56 };
var source = new[]
{
new { Name = key[0], Score = element[0] },
new { Name = key[1], Score = element[2] },
new { Name = key[2], Score = element[5] },
new { Name = key[1], Score = element[3] },
new { Name = key[0], Score = element[1] },
new { Name = key[1], Score = element[4] }
};
Assert.Equal(3, source.ToLookup(e => e.Name, e => e.Score).Count());
}
[Fact]
public void EmptySource()
{
string[] key = { };
int[] element = { };
var source = key.Zip(element, (k, e) => new { Name = k, Score = e });
AssertMatches(key, element, source.ToLookup(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void SingleNullKeyAndElement()
{
string[] key = { null };
string[] element = { null };
string[] source = new string[] { null };
AssertMatches(key, element, source.ToLookup(e => e, e => e, EqualityComparer<string>.Default));
}
[Fact]
public void NullSource()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10));
}
[Fact]
public void NullSourceExplicitComparer()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, EqualityComparer<int>.Default));
}
[Fact]
public void NullSourceElementSelector()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2));
}
[Fact]
public void NullSourceElementSelectorExplicitComparer()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.ToLookup(i => i / 10, i => i + 2, EqualityComparer<int>.Default));
}
[Fact]
public void NullKeySelector()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector));
}
[Fact]
public void NullKeySelectorExplicitComparer()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, EqualityComparer<int>.Default));
}
[Fact]
public void NullKeySelectorElementSelector()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2));
}
[Fact]
public void NullKeySelectorElementSelectorExplicitComparer()
{
Func<int, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Range(0, 1000).ToLookup(keySelector, i => i + 2, EqualityComparer<int>.Default));
}
[Fact]
public void NullElementSelector()
{
Func<int, int> elementSelector = null;
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector));
}
[Fact]
public void NullElementSelectorExplicitComparer()
{
Func<int, int> elementSelector = null;
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => Enumerable.Range(0, 1000).ToLookup(i => i / 10, elementSelector, EqualityComparer<int>.Default));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void ApplyResultSelectorForGroup(int enumType)
{
//Create test data
var roles = new List<Role>
{
new Role { Id = 1 },
new Role { Id = 2 },
new Role { Id = 3 },
};
var memberships = Enumerable.Range(0, 50).Select(i => new Membership
{
Id = i,
Role = roles[i % 3],
CountMe = i % 3 == 0
});
//Run actual test
var grouping = memberships.GroupBy(
m => m.Role,
(role, mems) => new RoleMetadata
{
Role = role,
CountA = mems.Count(m => m.CountMe),
CountrB = mems.Count(m => !m.CountMe)
});
IEnumerable<RoleMetadata> result;
switch (enumType)
{
case 1:
result = grouping.ToList();
break;
case 2:
result = grouping.ToArray();
break;
default:
result = grouping;
break;
}
var expected = new[]
{
new RoleMetadata {Role = new Role {Id = 1}, CountA = 17, CountrB = 0 },
new RoleMetadata {Role = new Role {Id = 2}, CountA = 0, CountrB = 17 },
new RoleMetadata {Role = new Role {Id = 3}, CountA = 0, CountrB = 16 }
};
Assert.Equal(expected, result);
}
[Theory]
[MemberData(nameof(DebuggerAttributesValid_Data))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Lookup<T> doesn't have a Debugger proxy in the full .NET framework. See https://github.com/dotnet/corefx/issues/14790.")]
public void DebuggerAttributesValid<TKey, TElement>(ILookup<TKey, TElement> lookup, TKey dummy1, TElement dummy2)
{
// The dummy parameters can be removed once https://github.com/dotnet/buildtools/pull/1300 is brought in.
Assert.Equal($"Count = {lookup.Count}", DebuggerAttributes.ValidateDebuggerDisplayReferences(lookup));
object proxyObject = DebuggerAttributes.GetProxyObject(lookup);
// Validate proxy fields
Assert.Empty(DebuggerAttributes.GetDebuggerVisibleFields(proxyObject.GetType()));
// Validate proxy properties
IEnumerable<PropertyInfo> properties = DebuggerAttributes.GetDebuggerVisibleProperties(proxyObject.GetType());
Assert.Equal(1, properties.Count());
// Groupings
PropertyInfo groupingsProperty = properties.Single(property => property.Name == "Groupings");
Assert.Equal(DebuggerBrowsableState.RootHidden, DebuggerAttributes.GetDebuggerBrowsableState(groupingsProperty));
var groupings = (IGrouping<TKey, TElement>[])groupingsProperty.GetValue(proxyObject);
Assert.IsType<IGrouping<TKey, TElement>[]>(groupings); // Arrays can be covariant / of assignment-compatible types
Assert.All(groupings.Zip(lookup, (l, r) => Tuple.Create(l, r)), tuple =>
{
Assert.Same(tuple.Item1, tuple.Item2);
});
Assert.Same(groupings, groupingsProperty.GetValue(proxyObject)); // The result should be cached, as Lookup is immutable.
}
public static IEnumerable<object[]> DebuggerAttributesValid_Data()
{
IEnumerable<int> source = new[] { 1 };
yield return new object[] { source.ToLookup(i => i), 0, 0 };
yield return new object[] { source.ToLookup(i => i.ToString(), i => i), string.Empty, 0 };
yield return new object[] { source.ToLookup(i => TimeSpan.FromSeconds(i), i => i), TimeSpan.Zero, 0 };
yield return new object[] { new string[] { null }.ToLookup(x => x), string.Empty, string.Empty };
// This test won't even work with the work-around because nullables lose their type once boxed, so xUnit sees an `int` and thinks
// we're trying to pass an ILookup<int, int> rather than an ILookup<int?, int?>.
// However, it should also be fixed once that PR is brought in, so leaving in this comment.
// yield return new object[] { new int?[] { null }.ToLookup(x => x), new int?(0), new int?(0) };
}
public class Membership
{
public int Id { get; set; }
public Role Role { get; set; }
public bool CountMe { get; set; }
}
public class Role : IEquatable<Role>
{
public int Id { get; set; }
public bool Equals(Role other) => other != null && Id == other.Id;
public override bool Equals(object obj) => Equals(obj as Role);
public override int GetHashCode() => Id;
}
public class RoleMetadata : IEquatable<RoleMetadata>
{
public Role Role { get; set; }
public int CountA { get; set; }
public int CountrB { get; set; }
public bool Equals(RoleMetadata other)
=> other != null && Role.Equals(other.Role) && CountA == other.CountA && CountrB == other.CountrB;
public override bool Equals(object obj) => Equals(obj as RoleMetadata);
public override int GetHashCode() => Role.GetHashCode() * 31 + CountA + CountrB;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.Text;
using SIL.Xml;
namespace SIL.WritingSystems.Migration.WritingSystemsLdmlV0To1Migration
{
internal class LdmlCollationParserV1
{
private const string NewLine = "\r\n";
private static readonly Regex UnicodeEscape4Digit = new Regex(@"\\[u]([0-9A-F]{4})", RegexOptions.IgnoreCase);
private static readonly Regex UnicodeEscape8Digit = new Regex(@"\\[U]([0-9A-F]{8})", RegexOptions.IgnoreCase);
/// <summary>
/// This method will replace any unicode escapes in rules with their actual unicode characters
/// and return the resulting string.
/// Method created since IcuRulesCoallator does not appear to interpret unicode escapes.
/// </summary>
/// <param name="rules"></param>
public static string ReplaceUnicodeEscapesForICU(string rules)
{
if (!string.IsNullOrEmpty(rules))
{
//replace all unicode escapes in the rules string with the unicode character they represent.
rules = UnicodeEscape8Digit.Replace(rules, match => ((char) int.Parse(match.Groups[1].Value,
NumberStyles.HexNumber)).ToString());
rules = UnicodeEscape4Digit.Replace(rules, match => ((char) int.Parse(match.Groups[1].Value,
NumberStyles.HexNumber)).ToString());
}
return rules;
}
public static string GetIcuRulesFromCollationNode(string collationXml)
{
if (collationXml == null)
{
throw new ArgumentNullException("collationXml");
}
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.CloseInput = true;
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
string icuRules = string.Empty;
string variableTop = null;
int variableTopPositionIfNotUsed = 0;
using (XmlReader collationReader = XmlReader.Create(new StringReader(collationXml), readerSettings))
{
if (XmlHelpers.FindNextElementInSequence(collationReader, "settings", LdmlNodeComparer.CompareElementNames))
{
icuRules += GetIcuSettingsFromSettingsNode(collationReader, out variableTop);
variableTopPositionIfNotUsed = icuRules.Length;
}
if (XmlHelpers.FindNextElementInSequence(collationReader, "suppress_contractions",
LdmlNodeComparer.CompareElementNames))
{
icuRules += GetIcuOptionFromNode(collationReader);
}
if (XmlHelpers.FindNextElementInSequence(collationReader, "optimize", LdmlNodeComparer.CompareElementNames))
{
icuRules += GetIcuOptionFromNode(collationReader);
}
if (XmlHelpers.FindNextElementInSequence(collationReader, "rules", LdmlNodeComparer.CompareElementNames))
{
icuRules += GetIcuRulesFromRulesNode(collationReader, ref variableTop);
}
}
if (variableTop != null)
{
string variableTopRule = String.Format(NewLine + "&{0} < [variable top]", EscapeForIcu(variableTop));
if (variableTopPositionIfNotUsed == icuRules.Length)
{
icuRules += variableTopRule;
}
else
{
icuRules = String.Format("{0}{1}{2}", icuRules.Substring(0, variableTopPositionIfNotUsed),
variableTopRule, icuRules.Substring(variableTopPositionIfNotUsed));
}
}
return TrimUnescapedWhitespace(icuRules);
}
/// <summary>
/// Trim all whitespace from the beginning, and all unescaped whitespace from the end.
/// </summary>
/// <param name="icuRules"></param>
/// <returns></returns>
private static string TrimUnescapedWhitespace(string icuRules)
{
var lastEscapeIndex = icuRules.LastIndexOf('\\');
if(lastEscapeIndex + 2 == icuRules.Length)
{
return icuRules.TrimStart();
}
return icuRules.Trim();
}
public static bool TryGetSimpleRulesFromCollationNode(string collationXml, out string rules)
{
if (collationXml == null)
{
throw new ArgumentNullException("collationXml");
}
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.CloseInput = true;
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
readerSettings.IgnoreWhitespace = true;
rules = null;
using (XmlReader collationReader = XmlReader.Create(new StringReader(collationXml), readerSettings))
{
// simple rules can't deal with any non-default settings
if (XmlHelpers.FindNextElementInSequence(collationReader, "settings", LdmlNodeComparer.CompareElementNames))
{
return false;
}
if (!XmlHelpers.FindNextElementInSequence(collationReader, "rules", LdmlNodeComparer.CompareElementNames))
{
rules = string.Empty;
return true;
}
rules = GetSimpleRulesFromRulesNode(collationReader);
}
return rules != null;
}
private static string GetSimpleRulesFromRulesNode(XmlReader reader)
{
if (reader.IsEmptyElement)
{
return string.Empty;
}
bool first = true;
bool inGroup = false;
string simpleRules = string.Empty;
reader.Read();
while (reader.NodeType != XmlNodeType.EndElement && !reader.EOF)
{
if (reader.NodeType != XmlNodeType.Element)
{
reader.Read();
continue;
}
// First child node MUST BE <reset before="primary"><first_non_ignorable /></reset>
if (first &&
(reader.Name != "reset" || GetBeforeOption(reader) != "[before 1] " || GetIcuData(reader) != "[first regular]"))
{
return null;
}
if (first)
{
first = false;
reader.Read();
continue;
}
switch (reader.Name)
{
case "p":
simpleRules += EndSimpleGroupIfNeeded(ref inGroup) + NewLine + GetTextData(reader);
break;
case "s":
simpleRules += EndSimpleGroupIfNeeded(ref inGroup) + " " + GetTextData(reader);
break;
case "t":
BeginSimpleGroupIfNeeded(ref inGroup, ref simpleRules);
simpleRules += " " + GetTextData(reader);
break;
case "pc":
simpleRules += EndSimpleGroupIfNeeded(ref inGroup) +
BuildSimpleRulesFromConcatenatedData(NewLine, GetTextData(reader));
break;
case "sc":
simpleRules += EndSimpleGroupIfNeeded(ref inGroup) +
BuildSimpleRulesFromConcatenatedData(" ", GetTextData(reader));
break;
case "tc":
BeginSimpleGroupIfNeeded(ref inGroup, ref simpleRules);
simpleRules += BuildSimpleRulesFromConcatenatedData(" ", GetTextData(reader));
break;
default: // element name not allowed for simple rules conversion
return null;
}
reader.ReadEndElement();
}
simpleRules += EndSimpleGroupIfNeeded(ref inGroup);
return simpleRules.Trim();
}
private static string EndSimpleGroupIfNeeded(ref bool inGroup)
{
if (!inGroup)
{
return string.Empty;
}
inGroup = false;
return ")";
}
private static void BeginSimpleGroupIfNeeded(ref bool inGroup, ref string rules)
{
if (inGroup)
{
return;
}
inGroup = true;
int lastIndexOfNewLine = rules.LastIndexOf(NewLine) + NewLine.Length;
int lastIndexOfSpace = rules.LastIndexOf(" ") + " ".Length;
int mostRecentPossiblepositionForABracket = Math.Max(lastIndexOfNewLine, lastIndexOfSpace);
rules = rules.Insert(mostRecentPossiblepositionForABracket, "(");
return;
}
/// <summary>
/// This method will escape necessary characters while avoiding escaping characters that are already escaped
/// and leave unicode escape sequences alone.
/// </summary>
/// <param name="unescapedData"></param>
/// <returns></returns>
private static string EscapeForIcu(string unescapedData)
{
const int longEscapeLen = 10; //length of a \UFFFFFFFF escape
const int shortEscLen = 6; //length of a \uFFFF escape
string result = string.Empty;
bool escapeNeedsClosing = false;
for (int i = 0; i < unescapedData.Length; i++)
{
//if we are looking at an backslash check if the following character needs escaping, if it does
//we do not need to escape it again
if ((unescapedData[i] == '\\' || unescapedData[i] == '\'') && i + 1 < unescapedData.Length
&& NeedsEscaping(Char.ConvertToUtf32(unescapedData, i + 1), "" + unescapedData[i + 1]))
{
result += unescapedData[i++]; //add the backslash and advance
result += unescapedData[i]; //add the already escaped character
} //handle long unicode escapes
else if (i + longEscapeLen <= unescapedData.Length &&
UnicodeEscape8Digit.IsMatch(unescapedData.Substring(i, longEscapeLen)))
{
result += unescapedData.Substring(i, longEscapeLen);
i += longEscapeLen - 1;
} //handle short unicode escapes
else if (i + shortEscLen <= unescapedData.Length &&
UnicodeEscape4Digit.IsMatch(unescapedData.Substring(i, shortEscLen)))
{
result += unescapedData.Substring(i, shortEscLen);
i += shortEscLen - 1;
}
else
{
//handle everything else
result += EscapeForIcu(Char.ConvertToUtf32(unescapedData, i), ref escapeNeedsClosing);
if (Char.IsSurrogate(unescapedData, i))
{
i++;
}
}
}
return escapeNeedsClosing ? result + "'" : result;
}
private static string EscapeForIcu(int code, ref bool alreadyEscaping)
{
string result = String.Empty;
string ch = Char.ConvertFromUtf32(code);
// ICU only requires escaping all whitespace and any ASCII character that is not a letter or digit
// Honestly, there shouldn't be any whitespace that is a surrogate, but we're checking
// to maintain the highest compatibility with future Unicode code points.
if (NeedsEscaping(code, ch))
{
if (!alreadyEscaping)
{
//Escape a single quote ' with single quote '', but don't start a sequence.
if (ch != "'")
{
alreadyEscaping = true;
}
//begin the escape sequence.
result += "'";
}
result += ch;
}
else
{
if (alreadyEscaping)
{
alreadyEscaping = false;
result = "'";
}
result += ch;
}
return result;
}
private static bool NeedsEscaping(int code, string ch)
{
return (code < 0x7F && !Char.IsLetterOrDigit(ch, 0)) || Char.IsWhiteSpace(ch, 0);
}
private static string BuildSimpleRulesFromConcatenatedData(string op, string data)
{
string rule = string.Empty;
bool surrogate = false;
for (int i = 0; i < data.Length; i++)
{
if (surrogate)
{
rule += data[i];
surrogate = false;
continue;
}
rule += op + data[i];
if (Char.IsSurrogate(data, i))
{
surrogate = true;
}
}
return rule;
}
private static string GetIcuSettingsFromSettingsNode(XmlReader reader, out string variableTop)
{
Debug.Assert(reader.NodeType == XmlNodeType.Element);
Debug.Assert(reader.Name == "settings");
variableTop = null;
Dictionary<string, string> strengthValues = new Dictionary<string, string>();
strengthValues["primary"] = "1";
strengthValues["secondary"] = "2";
strengthValues["tertiary"] = "3";
strengthValues["quaternary"] = "4";
strengthValues["identical"] = "I";
string icuSettings = string.Empty;
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "alternate":
case "normalization":
case "caseLevel":
case "caseFirst":
case "numeric":
icuSettings += String.Format(NewLine + "[{0} {1}]", reader.Name, reader.Value);
break;
case "strength":
if (!strengthValues.ContainsKey(reader.Value))
{
throw new ApplicationException("Invalid collation strength setting in LDML");
}
icuSettings += String.Format(NewLine + "[strength {0}]", strengthValues[reader.Value]);
break;
case "backwards":
if (reader.Value != "off" && reader.Value != "on")
{
throw new ApplicationException("Invalid backwards setting in LDML collation.");
}
icuSettings += String.Format(NewLine + "[backwards {0}]", reader.Value == "off" ? "1" : "2");
break;
case "hiraganaQuaternary":
icuSettings += String.Format(NewLine + "[hiraganaQ {0}]", reader.Value);
break;
case "variableTop":
variableTop = EscapeForIcu(UnescapeVariableTop(reader.Value));
break;
}
}
return icuSettings;
}
private static string UnescapeVariableTop(string variableTop)
{
string result = string.Empty;
foreach (string hexCode in variableTop.Split('u'))
{
if (String.IsNullOrEmpty(hexCode))
{
continue;
}
result += Char.ConvertFromUtf32(int.Parse(hexCode, NumberStyles.AllowHexSpecifier));
}
return result;
}
private static string GetIcuOptionFromNode(XmlReader reader)
{
Debug.Assert(reader.NodeType == XmlNodeType.Element);
string result;
switch (reader.Name)
{
case "suppress_contractions":
case "optimize":
result = String.Format(NewLine + "[{0} {1}]", reader.Name.Replace('_', ' '), reader.ReadElementString());
break;
default:
throw new ApplicationException(String.Format("Invalid LDML collation option element: {0}", reader.Name));
}
return result;
}
private static string GetIcuRulesFromRulesNode(XmlReader reader, ref string variableTop)
{
string rules = string.Empty;
using (XmlReader rulesReader = reader.ReadSubtree())
{
// skip initial "rules" element
rulesReader.Read();
while (rulesReader.Read())
{
string icuData;
if (rulesReader.NodeType != XmlNodeType.Element)
{
continue;
}
switch (rulesReader.Name)
{
case "reset":
string beforeOption = GetBeforeOption(rulesReader);
icuData = GetIcuData(rulesReader);
// I added a space after the ampersand to increase readability with situations where the first
// character following a reset may be a combining character or some other character that would be
// rendered around the ampersand
rules += String.Format(NewLine + "& {2}{0}{1}", icuData, GetVariableTopString(icuData, ref variableTop),
beforeOption);
break;
case "p":
icuData = GetIcuData(rulesReader);
rules += String.Format(" < {0}{1}", icuData, GetVariableTopString(icuData, ref variableTop));
break;
case "s":
icuData = GetIcuData(rulesReader);
rules += String.Format(" << {0}{1}", icuData, GetVariableTopString(icuData, ref variableTop));
break;
case "t":
icuData = GetIcuData(rulesReader);
rules += String.Format(" <<< {0}{1}", icuData, GetVariableTopString(icuData, ref variableTop));
break;
case "i":
icuData = GetIcuData(rulesReader);
rules += String.Format(" = {0}{1}", icuData, GetVariableTopString(icuData, ref variableTop));
break;
case "pc":
rules += BuildRuleFromConcatenatedData("<", rulesReader, ref variableTop);
break;
case "sc":
rules += BuildRuleFromConcatenatedData("<<", rulesReader, ref variableTop);
break;
case "tc":
rules += BuildRuleFromConcatenatedData("<<<", rulesReader, ref variableTop);
break;
case "ic":
rules += BuildRuleFromConcatenatedData("=", rulesReader, ref variableTop);
break;
case "x":
rules += GetRuleFromExtendedNode(rulesReader);
break;
default:
throw new ApplicationException(String.Format("Invalid LDML collation rule element: {0}", rulesReader.Name));
}
}
}
return rules;
}
private static string GetBeforeOption(XmlReader reader)
{
switch (reader.GetAttribute("before"))
{
case "primary":
return "[before 1] ";
case "secondary":
return "[before 2] ";
case "tertiary":
return "[before 3] ";
case "":
case null:
return string.Empty;
default:
throw new ApplicationException("Invalid before specifier on reset collation element.");
}
}
private static string GetIcuData(XmlReader reader)
{
if (reader.IsEmptyElement)
{
throw new ApplicationException(String.Format("Empty LDML collation rule: {0}", reader.Name));
}
string data = reader.ReadString();
if (reader.NodeType == XmlNodeType.Element && reader.Name != "cp")
{
return GetIndirectPosition(reader);
}
data += GetTextData(reader);
return EscapeForIcu(data);
}
private static string GetTextData(XmlReader reader)
{
string data = reader.ReadString();
while (reader.NodeType != XmlNodeType.EndElement)
{
switch (reader.NodeType)
{
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
reader.Read();
break;
case XmlNodeType.CDATA:
case XmlNodeType.EntityReference:
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
data += reader.ReadString();
break;
case XmlNodeType.Element:
data += GetCPData(reader);
break;
default:
throw new ApplicationException("Unexpected XML node type inside LDML collation data element.");
}
}
return data;
}
private static string GetCPData(XmlReader reader)
{
Debug.Assert(reader.NodeType == XmlNodeType.Element);
if (reader.Name != "cp")
{
throw new ApplicationException(string.Format("Unexpected element '{0}' in text data node", reader.Name));
}
string hex = reader.GetAttribute("hex");
string result = string.Empty;
if (!string.IsNullOrEmpty(hex))
{
int code;
if (!int.TryParse(hex, NumberStyles.AllowHexSpecifier, null, out code))
{
throw new ApplicationException("Invalid non-hexadecimal character code in LDML 'cp' element.");
}
try
{
result = Char.ConvertFromUtf32(code);
}
catch (ArgumentOutOfRangeException e)
{
throw new ApplicationException("Invalid Unicode code point in LDML 'cp' element.", e);
}
}
reader.Skip();
return result;
}
private static string GetIndirectPosition(XmlReader reader)
{
string result;
switch (reader.Name)
{
case "first_non_ignorable":
result = "[first regular]";
break;
case "last_non_ignorable":
result = "[last regular]";
break;
default:
result = "[" + reader.Name.Replace('_', ' ') + "]";
break;
}
reader.Skip();
return result;
}
private static string BuildRuleFromConcatenatedData(string op, XmlReader reader, ref string variableTop)
{
string data = GetTextData(reader);
StringBuilder rule = new StringBuilder(20*data.Length);
for (int i = 0; i < data.Length; i++)
{
bool escapeNeedsClosing = false;
string icuData = EscapeForIcu(Char.ConvertToUtf32(data, i), ref escapeNeedsClosing);
if (escapeNeedsClosing)
icuData += ('\'');
rule.AppendFormat(" {0} {1}{2}", op, icuData, GetVariableTopString(icuData, ref variableTop));
if (Char.IsSurrogate(data, i))
{
i++;
}
}
return rule.ToString();
}
private static string GetVariableTopString(string icuData, ref string variableTop)
{
if (variableTop == null || variableTop != icuData)
{
return string.Empty;
}
variableTop = null;
return " < [variable top]";
}
private static string GetRuleFromExtendedNode(XmlReader reader)
{
string rule = string.Empty;
if (reader.IsEmptyElement)
{
return rule;
}
reader.Read();
while (reader.NodeType != XmlNodeType.EndElement && !reader.EOF)
{
if (reader.NodeType != XmlNodeType.Element)
{
reader.Read();
continue;
}
switch (reader.Name)
{
case "context":
rule += String.Format("{0} | ", GetIcuData(reader));
break;
case "extend":
rule += String.Format(" / {0}", GetIcuData(reader));
break;
case "p":
rule = String.Format(" < {0}{1}", rule, GetIcuData(reader));
break;
case "s":
rule = String.Format(" << {0}{1}", rule, GetIcuData(reader));
break;
case "t":
rule = String.Format(" <<< {0}{1}", rule, GetIcuData(reader));
break;
case "i":
rule = String.Format(" = {0}{1}", rule, GetIcuData(reader));
break;
default:
throw new ApplicationException(String.Format("Invalid node in extended LDML collation rule: {0}", reader.Name));
}
reader.Read();
}
return rule;
}
}
}
| |
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Miningcore.Contracts;
using Miningcore.Extensions;
using Miningcore.Messaging;
using Miningcore.Notifications.Messages;
using NLog;
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming
namespace Miningcore.Native;
public static unsafe class LibRandomX
{
private static readonly ILogger logger = LogManager.GetCurrentClassLogger();
internal static IMessageBus messageBus;
#region VM managment
internal static readonly Dictionary<string, Dictionary<string, Tuple<GenContext, BlockingCollection<RxVm>>>> realms = new();
private static readonly byte[] empty = new byte[32];
#endregion // VM managment
[Flags]
public enum randomx_flags
{
RANDOMX_FLAG_DEFAULT = 0,
RANDOMX_FLAG_LARGE_PAGES = 1,
RANDOMX_FLAG_HARD_AES = 2,
RANDOMX_FLAG_FULL_MEM = 4,
RANDOMX_FLAG_JIT = 8,
RANDOMX_FLAG_SECURE = 16,
RANDOMX_FLAG_ARGON2_SSSE3 = 32,
RANDOMX_FLAG_ARGON2_AVX2 = 64,
RANDOMX_FLAG_ARGON2 = 96
};
[DllImport("librandomx", EntryPoint = "randomx_get_flags", CallingConvention = CallingConvention.Cdecl)]
private static extern randomx_flags randomx_get_flags();
[DllImport("librandomx", EntryPoint = "randomx_alloc_cache", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr randomx_alloc_cache(randomx_flags flags);
[DllImport("librandomx", EntryPoint = "randomx_init_cache", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr randomx_init_cache(IntPtr cache, IntPtr key, int keysize);
[DllImport("librandomx", EntryPoint = "randomx_release_cache", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr randomx_release_cache(IntPtr cache);
[DllImport("librandomx", EntryPoint = "randomx_alloc_dataset", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr randomx_alloc_dataset(randomx_flags flags);
[DllImport("librandomx", EntryPoint = "randomx_dataset_item_count", CallingConvention = CallingConvention.Cdecl)]
private static extern ulong randomx_dataset_item_count();
[DllImport("librandomx", EntryPoint = "randomx_init_dataset", CallingConvention = CallingConvention.Cdecl)]
private static extern void randomx_init_dataset(IntPtr dataset, IntPtr cache, ulong startItem, ulong itemCount);
[DllImport("librandomx", EntryPoint = "randomx_get_dataset_memory", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr randomx_get_dataset_memory(IntPtr dataset);
[DllImport("librandomx", EntryPoint = "randomx_release_dataset", CallingConvention = CallingConvention.Cdecl)]
private static extern void randomx_release_dataset(IntPtr dataset);
[DllImport("librandomx", EntryPoint = "randomx_create_vm", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr randomx_create_vm(randomx_flags flags, IntPtr cache, IntPtr dataset);
[DllImport("librandomx", EntryPoint = "randomx_vm_set_cache", CallingConvention = CallingConvention.Cdecl)]
private static extern void randomx_vm_set_cache(IntPtr machine, IntPtr cache);
[DllImport("librandomx", EntryPoint = "randomx_vm_set_dataset", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr randomx_vm_set_dataset(IntPtr machine, IntPtr dataset);
[DllImport("librandomx", EntryPoint = "randomx_destroy_vm", CallingConvention = CallingConvention.Cdecl)]
private static extern void randomx_destroy_vm(IntPtr machine);
[DllImport("librandomx", EntryPoint = "randomx_calculate_hash", CallingConvention = CallingConvention.Cdecl)]
private static extern void randomx_calculate_hash(IntPtr machine, byte* input, int inputSize, byte* output);
public class GenContext
{
public DateTime LastAccess { get; set; } = DateTime.Now;
public int VmCount { get; init; }
}
public class RxDataSet : IDisposable
{
private IntPtr dataset = IntPtr.Zero;
public void Dispose()
{
if(dataset != IntPtr.Zero)
{
randomx_release_dataset(dataset);
dataset = IntPtr.Zero;
}
}
public IntPtr Init(ReadOnlySpan<byte> key, randomx_flags flags, IntPtr cache)
{
dataset = randomx_alloc_dataset(flags);
var itemCount = randomx_dataset_item_count();
randomx_init_dataset(dataset, cache, 0, itemCount);
return dataset;
}
}
public class RxVm : IDisposable
{
private IntPtr cache = IntPtr.Zero;
private IntPtr vm = IntPtr.Zero;
private RxDataSet ds;
public void Dispose()
{
if(vm != IntPtr.Zero)
{
randomx_destroy_vm(vm);
vm = IntPtr.Zero;
}
ds?.Dispose();
if(cache != IntPtr.Zero)
{
randomx_release_cache(cache);
cache = IntPtr.Zero;
}
}
public void Init(ReadOnlySpan<byte> key, randomx_flags flags)
{
var ds_ptr = IntPtr.Zero;
// alloc cache
cache = randomx_alloc_cache(flags);
// init cache
fixed(byte* key_ptr = key)
{
randomx_init_cache(cache, (IntPtr) key_ptr, key.Length);
}
// Enable fast-mode? (requires 2GB+ memory per VM)
if((flags & randomx_flags.RANDOMX_FLAG_FULL_MEM) != 0)
{
ds = new RxDataSet();
ds_ptr = ds.Init(key, flags, cache);
// cache is no longer needed in fast-mode
randomx_release_cache(cache);
cache = IntPtr.Zero;
}
vm = randomx_create_vm(flags, cache, ds_ptr);
}
public void CalculateHash(ReadOnlySpan<byte> data, Span<byte> result)
{
fixed (byte* input = data)
{
fixed (byte* output = result)
{
randomx_calculate_hash(vm, input, data.Length, output);
}
}
}
}
public static void WithLock(Action action)
{
lock(realms)
{
action();
}
}
public static void CreateSeed(string realm, string seedHex,
randomx_flags? flagsOverride = null, randomx_flags? flagsAdd = null, int vmCount = 1)
{
lock(realms)
{
if(!realms.TryGetValue(realm, out var seeds))
{
seeds = new Dictionary<string, Tuple<GenContext, BlockingCollection<RxVm>>>();
realms[realm] = seeds;
}
if(!seeds.TryGetValue(seedHex, out var seed))
{
var flags = flagsOverride ?? randomx_get_flags();
if(flagsAdd.HasValue)
flags |= flagsAdd.Value;
if (vmCount == -1)
vmCount = Environment.ProcessorCount;
seed = CreateSeed(realm, seedHex, flags, vmCount);
seeds[seedHex] = seed;
}
}
}
private static Tuple<GenContext, BlockingCollection<RxVm>> CreateSeed(string realm, string seedHex, randomx_flags flags, int vmCount)
{
var vms = new BlockingCollection<RxVm>();
var seed = new Tuple<GenContext, BlockingCollection<RxVm>>(new GenContext
{
VmCount = vmCount
}, vms);
void createVm(int index)
{
var start = DateTime.Now;
logger.Info(() => $"Creating VM {realm}@{index + 1} [{flags}], hash {seedHex} ...");
var vm = new RxVm();
vm.Init(seedHex.HexToByteArray(), flags);
vms.Add(vm);
logger.Info(() => $"Created VM {realm}@{index + 1} in {DateTime.Now - start}");
};
Parallel.For(0, vmCount, createVm);
return seed;
}
public static void DeleteSeed(string realm, string seedHex)
{
Tuple<GenContext, BlockingCollection<RxVm>> seed;
lock(realms)
{
if(!realms.TryGetValue(realm, out var seeds))
return;
if(!seeds.Remove(seedHex, out seed))
return;
}
// dispose all VMs
var (ctx, col) = seed;
var remaining = ctx.VmCount;
while (remaining > 0)
{
var vm = col.Take();
logger.Info($"Disposing VM {ctx.VmCount - remaining} for realm {realm} and key {seedHex}");
vm.Dispose();
remaining--;
}
}
public static Tuple<GenContext, BlockingCollection<RxVm>> GetSeed(string realm, string seedHex)
{
lock(realms)
{
if(!realms.TryGetValue(realm, out var seeds))
return null;
if(!seeds.TryGetValue(seedHex, out var seed))
return null;
return seed;
}
}
public static void CalculateHash(string realm, string seedHex, ReadOnlySpan<byte> data, Span<byte> result)
{
Contract.Requires<ArgumentException>(result.Length >= 32, $"{nameof(result)} must be greater or equal 32 bytes");
var sw = Stopwatch.StartNew();
var success = false;
var (ctx, seedVms) = GetSeed(realm, seedHex);
if(ctx != null)
{
RxVm vm = null;
try
{
// lease a VM
vm = seedVms.Take();
vm.CalculateHash(data, result);
ctx.LastAccess = DateTime.Now;
success = true;
messageBus?.SendTelemetry("RandomX", TelemetryCategory.Hash, sw.Elapsed, true);
}
catch(Exception ex)
{
logger.Error(() => ex.Message);
}
finally
{
// return it
if(vm != null)
seedVms.Add(vm);
}
}
if(!success)
{
// clear result on failure
empty.CopyTo(result);
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* 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.Xml;
namespace Reporting.Rdl
{
///<summary>
/// Collection of query parameters.
///</summary>
[Serializable]
internal class QueryParameters : ReportLink
{
List<QueryParameter> _Items; // list of QueryParameter
bool _ContainsArray; // true if any of the parameters is an array reference
internal QueryParameters(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_ContainsArray = false;
QueryParameter q;
_Items = new List<QueryParameter>();
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "QueryParameter":
q = new QueryParameter(r, this, xNodeLoop);
break;
default:
q=null; // don't know what this is
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown QueryParameters element '" + xNodeLoop.Name + "' ignored.");
break;
}
if (q != null)
_Items.Add(q);
}
if (_Items.Count == 0)
OwnerReport.rl.LogError(8, "For QueryParameters at least one QueryParameter is required.");
else
_Items.TrimExcess();
}
override internal void FinalPass()
{
foreach (QueryParameter q in _Items)
{
q.FinalPass();
if (q.IsArray)
_ContainsArray = true;
}
return;
}
internal List<QueryParameter> Items
{
get { return _Items; }
}
internal bool ContainsArray
{
get { return _ContainsArray; }
}
}
///<summary>
/// Represent query parameter.
///</summary>
[Serializable]
internal class QueryParameter : ReportLink, IComparable
{
Name _Name; // Name of the parameter
Expression _Value; // (Variant or Variant Array)
//An expression that evaluates to the value to
//hand to the data source. The expression can
//refer to report parameters but cannot contain
//references to report elements, fields in the data
//model or aggregate functions.
//In the case of a parameter to a Values or
//DefaultValue query, the expression can only
//refer to report parameters that occur earlier in
//the parameters list. The value for this query
//parameter is then taken from the user selection
//for that earlier report parameter.
internal QueryParameter(ReportDefn r, ReportLink p, XmlNode xNode)
: base(r, p)
{
_Name = null;
_Value = null;
// Run thru the attributes
foreach (XmlAttribute xAttr in xNode.Attributes)
{
switch (xAttr.Name)
{
case "Name":
_Name = new Name(xAttr.Value);
break;
}
}
// Loop thru all the child nodes
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Value":
_Value = new Expression(r, this, xNodeLoop, ExpressionType.Variant);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown QueryParameter element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
if (_Name == null)
OwnerReport.rl.LogError(8, "QueryParameter name is required but not specified.");
if (_Value == null)
OwnerReport.rl.LogError(8, "QueryParameter Value is required but not specified or invalid for " + _Name == null ? "<unknown name>" : _Name.Nm);
}
// Handle parsing of function in final pass
override internal void FinalPass()
{
if (_Value != null)
_Value.FinalPass();
return;
}
internal Name Name
{
get { return _Name; }
set { _Name = value; }
}
internal Expression Value
{
get { return _Value; }
set { _Value = value; }
}
internal bool IsArray
{
get
{
if (_Value == null) // when null; usually means a parsing error
return false; // but we want to continue as far as we can
return (_Value.GetTypeCode() == TypeCode.Object);
}
}
#region IComparable Members
public int CompareTo(object obj)
{
QueryParameter qp = obj as QueryParameter;
if (qp == null)
return 0;
string tname = this.Name.Nm;
string qpname = qp.Name.Nm;
int length_diff = qpname.Length - tname.Length;
if (length_diff == 0)
return qpname.CompareTo(tname);
return length_diff;
}
#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.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class zip_ManualAndCompatabilityTests : ZipFileTestBase
{
public static bool IsUsingNewPathNormalization => !PathFeatures.IsUsingLegacyPathNormalization();
[Theory]
[InlineData("7zip.zip", "normal", true, true)]
[InlineData("windows.zip", "normalWithoutEmptyDir", false, true)]
[InlineData("dotnetzipstreaming.zip", "normal", false, false)]
[InlineData("sharpziplib.zip", "normalWithoutEmptyDir", false, false)]
[InlineData("xceedstreaming.zip", "normal", false, false)]
public static async Task CompatibilityTests(string zipFile, string zipFolder, bool requireExplicit, bool checkTimes)
{
IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(compat(zipFile)), zfolder(zipFolder), ZipArchiveMode.Update, requireExplicit, checkTimes);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Deflate64 zip support is a netcore feature not available on full framework.")]
public static async Task Deflate64Zip()
{
IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(compat("deflate64.zip")), zfolder("normal"), ZipArchiveMode.Update, requireExplicit: true, checkTimes: true);
}
[Theory]
[InlineData("excel.xlsx", "excel", false, false)]
[InlineData("powerpoint.pptx", "powerpoint", false, false)]
[InlineData("word.docx", "word", false, false)]
[InlineData("silverlight.xap", "silverlight", false, false)]
[InlineData("packaging.package", "packaging", false, false)]
public static async Task CompatibilityTestsMsFiles(string withTrailing, string withoutTrailing, bool requireExplicit, bool checkTimes)
{
IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(compat(withTrailing)), compat(withoutTrailing), ZipArchiveMode.Update, requireExplicit, checkTimes);
}
/// <summary>
/// This test ensures that a zipfile created on one platform with a file containing potentially invalid characters elsewhere
/// will be interpreted based on the source OS path name validation rules.
///
/// For example, the file "aa\bb\cc\dd" in a zip created on Unix should be one file "aa\bb\cc\dd" whereas the same file
/// in a zip created on Windows should be interpreted as the file "dd" underneath three subdirectories.
/// </summary>
[ConditionalTheory(nameof(IsUsingNewPathNormalization))]
[InlineData("backslashes_FromUnix.zip", "aa\\bb\\cc\\dd")]
[InlineData("backslashes_FromWindows.zip", "dd")]
[InlineData("WindowsInvalid_FromUnix.zip", "aa<b>d")]
[InlineData("WindowsInvalid_FromWindows.zip", "aa<b>d")]
[InlineData("NullCharFileName_FromWindows.zip", "a\06b6d")]
[InlineData("NullCharFileName_FromUnix.zip", "a\06b6d")]
public static async Task ZipWithInvalidFileNames_ParsedBasedOnSourceOS(string zipName, string fileName)
{
using (Stream stream = await StreamHelpers.CreateTempCopyStream(compat(zipName)))
using (ZipArchive archive = new ZipArchive(stream))
{
Assert.Equal(1, archive.Entries.Count);
ZipArchiveEntry entry = archive.Entries[0];
Assert.Equal(fileName, entry.Name);
}
}
/// <summary>
/// This test compares binary content of a zip produced by the current version with a zip produced by
/// other frameworks. It does this by searching the two zips for the header signature and then
/// it compares the subsequent header values for equality.
///
/// This test looks for the local file headers that each entry within a zip possesses and compares these
/// values:
/// local file header signature 4 bytes (0x04034b50)
/// version needed to extract 2 bytes
/// general purpose bit flag 2 bytes
/// compression method 2 bytes
/// last mod file time 2 bytes
/// last mod file date 2 bytes
///
/// it does not compare these values:
///
/// crc-32 4 bytes
/// compressed size 4 bytes
/// uncompressed size 4 bytes
/// file name length 2 bytes
/// extra field length 2 bytes
/// file name(variable size)
/// extra field(variable size)
/// </summary>
[Theory]
[InlineData("net45_unicode.zip", "unicode")]
[InlineData("net46_unicode.zip", "unicode")]
[InlineData("net45_normal.zip", "normal")]
[InlineData("net46_normal.zip", "normal")]
public static async Task ZipBinaryCompat_LocalFileHeaders(string zipFile, string zipFolder)
{
using (MemoryStream actualArchiveStream = new MemoryStream())
using (MemoryStream expectedArchiveStream = await StreamHelpers.CreateTempCopyStream(compat(zipFile)))
{
byte[] localFileHeaderSignature = new byte[] { 0x50, 0x4b, 0x03, 0x04 };
// Produce a ZipFile
await CreateFromDir(zfolder(zipFolder), actualArchiveStream, ZipArchiveMode.Create);
// Read the streams to byte arrays
byte[] actualBytes = actualArchiveStream.ToArray();
byte[] expectedBytes = expectedArchiveStream.ToArray();
// Search for the file headers
int actualIndex = 0, expectedIndex = 0;
while ((expectedIndex = FindIndexOfSequence(expectedBytes, expectedIndex, localFileHeaderSignature)) != -1)
{
actualIndex = FindIndexOfSequence(actualBytes, actualIndex, localFileHeaderSignature);
Assert.NotEqual(-1, actualIndex);
for (int i = 0; i < 14; i++)
{
Assert.Equal(expectedBytes[expectedIndex], actualBytes[actualIndex]);
}
expectedIndex += 14;
actualIndex += 14;
}
}
}
/// <summary>
/// This test compares binary content of a zip produced by the current version with a zip produced by
/// other frameworks. It does this by searching the two zips for the header signature and then
/// it compares the subsequent header values for equality.
///
/// This test looks for the central directory headers that each entry within a zip possesses and compares these
/// values:
/// central file header signature 4 bytes (0x02014b50)
/// version made by 2 bytes
/// version needed to extract 2 bytes
/// general purpose bit flag 2 bytes
/// compression method 2 bytes
/// last mod file time 2 bytes
/// last mod file date 2 bytes
/// uncompressed size 4 bytes
/// file name length 2 bytes
/// extra field length 2 bytes
/// file comment length 2 bytes
/// disk number start 2 bytes
/// internal file attributes 2 bytes
/// external file attributes 4 bytes
///
/// it does not compare these values:
/// crc-32 4 bytes
/// compressed size 4 bytes
/// relative offset of local header 4 bytes
/// file name (variable size)
/// extra field (variable size)
/// file comment (variable size)
/// </summary>
[Theory]
[InlineData("net45_unicode.zip", "unicode")]
[InlineData("net46_unicode.zip", "unicode")]
[InlineData("net45_normal.zip", "normal")]
[InlineData("net46_normal.zip", "normal")]
public static async Task ZipBinaryCompat_CentralDirectoryHeaders(string zipFile, string zipFolder)
{
using (MemoryStream actualArchiveStream = new MemoryStream())
using (MemoryStream expectedArchiveStream = await StreamHelpers.CreateTempCopyStream(compat(zipFile)))
{
byte[] signature = new byte[] { 0x50, 0x4b, 0x03, 0x04 };
// Produce a ZipFile
await CreateFromDir(zfolder(zipFolder), actualArchiveStream, ZipArchiveMode.Create);
// Read the streams to byte arrays
byte[] actualBytes = actualArchiveStream.ToArray();
byte[] expectedBytes = expectedArchiveStream.ToArray();
// Search for the file headers
int actualIndex = 0, expectedIndex = 0;
while ((expectedIndex = FindIndexOfSequence(expectedBytes, expectedIndex, signature)) != -1)
{
actualIndex = FindIndexOfSequence(actualBytes, actualIndex, signature);
Assert.NotEqual(-1, actualIndex);
for (int i = 0; i < 16; i++)
{
Assert.Equal(expectedBytes[expectedIndex], actualBytes[actualIndex]);
}
for (int i = 24; i < 42; i++)
{
Assert.Equal(expectedBytes[expectedIndex], actualBytes[actualIndex]);
}
expectedIndex += 38;
actualIndex += 38;
}
}
}
/// <summary>
/// Simple helper method to search <paramref name="bytesToSearch"/> for the exact byte sequence specified by
/// <paramref name="sequenceToFind"/>, starting at <paramref name="startIndex"/>.
/// </summary>
/// <returns>The first index of the first element in the matching sequence</returns>
public static int FindIndexOfSequence(byte[] bytesToSearch, int startIndex, byte[] sequenceToFind)
{
for (int index = startIndex; index < bytesToSearch.Length - sequenceToFind.Length; index++)
{
bool equal = true;
for (int i = 0; i < sequenceToFind.Length; i++)
{
if (bytesToSearch[index + i] != sequenceToFind[i])
{
equal = false;
break;
}
}
if (equal)
return index;
}
return -1;
}
}
}
| |
/*
* 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.Linq.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Common;
using Remotion.Linq;
/// <summary>
/// Fields query executor.
/// </summary>
internal class CacheFieldsQueryExecutor : IQueryExecutor
{
/** */
private readonly ICacheInternal _cache;
/** */
private readonly QueryOptions _options;
/** */
private static readonly CopyOnWriteConcurrentDictionary<ConstructorInfo, object> CtorCache =
new CopyOnWriteConcurrentDictionary<ConstructorInfo, object>();
/// <summary>
/// Initializes a new instance of the <see cref="CacheFieldsQueryExecutor" /> class.
/// </summary>
/// <param name="cache">The executor function.</param>
/// <param name="options">Query options.</param>
public CacheFieldsQueryExecutor(ICacheInternal cache, QueryOptions options)
{
Debug.Assert(cache != null);
Debug.Assert(options != null);
_cache = cache;
_options = options;
}
/** <inheritdoc /> */
public T ExecuteScalar<T>(QueryModel queryModel)
{
return ExecuteSingle<T>(queryModel, false);
}
/** <inheritdoc /> */
public T ExecuteSingle<T>(QueryModel queryModel, bool returnDefaultWhenEmpty)
{
var col = ExecuteCollection<T>(queryModel);
return returnDefaultWhenEmpty ? col.SingleOrDefault() : col.Single();
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public IEnumerable<T> ExecuteCollection<T>(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
var qryData = GetQueryData(queryModel);
Debug.WriteLine("\nFields Query: {0} | {1}", qryData.QueryText,
string.Join(", ", qryData.Parameters.Select(x => x == null ? "null" : x.ToString())));
var qry = GetFieldsQuery(qryData.QueryText, qryData.Parameters.ToArray());
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
return _cache.Query(qry, selector);
}
/// <summary>
/// Compiles the query without regard to number or order of arguments.
/// </summary>
public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
var qryText = GetQueryData(queryModel).QueryText;
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
return args => _cache.Query(GetFieldsQuery(qryText, args), selector);
}
/// <summary>
/// Compiles the query.
/// </summary>
/// <typeparam name="T">Result type.</typeparam>
/// <param name="queryModel">The query model.</param>
/// <param name="queryLambdaModel">The query model generated from lambda body.</param>
/// <param name="queryLambda">The query lambda.</param>
/// <returns>Compiled query func.</returns>
public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel, QueryModel queryLambdaModel,
LambdaExpression queryLambda)
{
Debug.Assert(queryModel != null);
// Get model from lambda to map arguments properly.
var qryData = GetQueryData(queryLambdaModel);
var qryText = GetQueryData(queryModel).QueryText;
var qryTextLambda = qryData.QueryText;
if (qryText != qryTextLambda)
{
Debug.WriteLine(qryText);
Debug.WriteLine(qryTextLambda);
throw new InvalidOperationException("Error compiling query: entire LINQ expression should be " +
"specified within lambda passed to Compile method. " +
"Part of the query can't be outside the Compile method call.");
}
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
var qryParams = qryData.Parameters.ToArray();
// Compiled query is a delegate with query parameters
// Delegate parameters order and query parameters order may differ
// Simple case: lambda with no parameters. Only embedded parameters are used.
if (!queryLambda.Parameters.Any())
{
return argsUnused => _cache.Query(GetFieldsQuery(qryText, qryParams), selector);
}
// These are in order of usage in query
var qryOrderArgs = qryParams.OfType<ParameterExpression>().Select(x => x.Name).ToArray();
// These are in order they come from user
var userOrderArgs = queryLambda.Parameters.Select(x => x.Name).ToList();
// Simple case: all query args directly map to the lambda args in the same order
if (qryOrderArgs.Length == qryParams.Length
&& qryOrderArgs.SequenceEqual(userOrderArgs))
{
return args => _cache.Query(GetFieldsQuery(qryText, args), selector);
}
// General case: embedded args and lambda args are mixed; same args can be used multiple times.
// Produce a mapping that defines where query arguments come from.
var mapping = qryParams.Select(x =>
{
var pe = x as ParameterExpression;
if (pe != null)
return userOrderArgs.IndexOf(pe.Name);
return -1;
}).ToArray();
return args => _cache.Query(
GetFieldsQuery(qryText, MapQueryArgs(args, qryParams, mapping)), selector);
}
/// <summary>
/// Maps the query arguments.
/// </summary>
private static object[] MapQueryArgs(object[] userArgs, object[] embeddedArgs, int[] mapping)
{
var mappedArgs = new object[embeddedArgs.Length];
for (var i = 0; i < mappedArgs.Length; i++)
{
var map = mapping[i];
mappedArgs[i] = map < 0 ? embeddedArgs[i] : userArgs[map];
}
return mappedArgs;
}
/// <summary>
/// Gets the fields query.
/// </summary>
internal SqlFieldsQuery GetFieldsQuery(string text, object[] args)
{
return new SqlFieldsQuery(text)
{
EnableDistributedJoins = _options.EnableDistributedJoins,
PageSize = _options.PageSize,
EnforceJoinOrder = _options.EnforceJoinOrder,
Timeout = _options.Timeout,
#pragma warning disable 618
ReplicatedOnly = _options.ReplicatedOnly,
#pragma warning restore 618
Colocated = _options.Colocated,
Local = _options.Local,
Arguments = args,
Lazy = _options.Lazy
};
}
/// <summary>
/// Generates <see cref="QueryData"/> from specified <see cref="QueryModel"/>.
/// </summary>
public static QueryData GetQueryData(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
return new CacheQueryModelVisitor().GenerateQuery(queryModel);
}
/// <summary>
/// Gets the result selector.
/// </summary>
private static Func<IBinaryRawReader, int, T> GetResultSelector<T>(Expression selectorExpression)
{
var newExpr = selectorExpression as NewExpression;
if (newExpr != null)
return GetCompiledCtor<T>(newExpr.Constructor);
var entryCtor = GetCacheEntryCtorInfo(typeof(T));
if (entryCtor != null)
return GetCompiledCtor<T>(entryCtor);
if (typeof(T) == typeof(bool))
return ReadBool<T>;
return (reader, count) => reader.ReadObject<T>();
}
/// <summary>
/// Reads the bool. Actual data may be bool or int/long.
/// </summary>
private static T ReadBool<T>(IBinaryRawReader reader, int count)
{
var obj = reader.ReadObject<object>();
if (obj is bool)
return (T) obj;
if (obj is long)
return TypeCaster<T>.Cast((long) obj != 0);
if (obj is int)
return TypeCaster<T>.Cast((int) obj != 0);
throw new InvalidOperationException("Expected bool, got: " + obj);
}
/// <summary>
/// Gets the cache entry constructor.
/// </summary>
private static ConstructorInfo GetCacheEntryCtorInfo(Type entryType)
{
if (!entryType.IsGenericType || entryType.GetGenericTypeDefinition() != typeof(ICacheEntry<,>))
return null;
var args = entryType.GetGenericArguments();
var targetType = typeof (CacheEntry<,>).MakeGenericType(args);
return targetType.GetConstructors().Single();
}
/// <summary>
/// Gets the compiled constructor.
/// </summary>
private static Func<IBinaryRawReader, int, T> GetCompiledCtor<T>(ConstructorInfo ctorInfo)
{
object result;
if (CtorCache.TryGetValue(ctorInfo, out result))
return (Func<IBinaryRawReader, int, T>) result;
return (Func<IBinaryRawReader, int, T>) CtorCache.GetOrAdd(ctorInfo, x =>
{
var innerCtor1 = DelegateConverter.CompileCtor<T>(x, GetCacheEntryCtorInfo);
return (Func<IBinaryRawReader, int, T>) ((r, c) => innerCtor1(r));
});
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebServiceHandler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Services.Protocols {
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using System.Collections;
using System.Web;
using System.Web.SessionState;
using System.Web.Services.Interop;
using System.Configuration;
using Microsoft.Win32;
using System.Threading;
using System.Text;
using System.Web.UI;
using System.Web.Util;
using System.Web.UI.WebControls;
using System.ComponentModel; // for CompModSwitches
using System.EnterpriseServices;
using System.Runtime.Remoting.Messaging;
using System.Web.Services.Diagnostics;
internal class WebServiceHandler {
ServerProtocol protocol;
Exception exception;
AsyncCallback asyncCallback;
ManualResetEvent asyncBeginComplete;
int asyncCallbackCalls;
bool wroteException;
object[] parameters = null;
internal WebServiceHandler(ServerProtocol protocol) {
this.protocol = protocol;
}
// Flush the trace file after each request so that the trace output makes it to the disk.
static void TraceFlush() {
Debug.Flush();
}
void PrepareContext() {
this.exception = null;
this.wroteException = false;
this.asyncCallback = null;
this.asyncBeginComplete = new ManualResetEvent(false);
this.asyncCallbackCalls = 0;
if (protocol.IsOneWay)
return;
HttpContext context = protocol.Context;
if (context == null) return; // context is null in non-network case
// we want the default to be no caching on the client
int cacheDuration = protocol.MethodAttribute.CacheDuration;
if (cacheDuration > 0) {
context.Response.Cache.SetCacheability(HttpCacheability.Server);
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(cacheDuration));
context.Response.Cache.SetSlidingExpiration(false);
// with soap 1.2 the action is a param in the content-type
context.Response.Cache.VaryByHeaders["Content-type"] = true;
context.Response.Cache.VaryByHeaders["SOAPAction"] = true;
context.Response.Cache.VaryByParams["*"] = true;
}
else {
context.Response.Cache.SetNoServerCaching();
context.Response.Cache.SetMaxAge(TimeSpan.Zero);
}
context.Response.BufferOutput = protocol.MethodAttribute.BufferResponse;
context.Response.ContentType = null;
}
void WriteException(Exception e) {
if (this.wroteException) return;
if (CompModSwitches.Remote.TraceVerbose) Debug.WriteLine("Server Exception: " + e.ToString());
if (e is TargetInvocationException) {
if (CompModSwitches.Remote.TraceVerbose) Debug.WriteLine("TargetInvocationException caught.");
e = e.InnerException;
}
this.wroteException = protocol.WriteException(e, protocol.Response.OutputStream);
if (!this.wroteException)
throw e;
}
void Invoke() {
PrepareContext();
protocol.CreateServerInstance();
string stringBuffer;
#if !MONO
RemoteDebugger debugger = null;
if (!protocol.IsOneWay && RemoteDebugger.IsServerCallInEnabled(protocol, out stringBuffer)) {
debugger = new RemoteDebugger();
debugger.NotifyServerCallEnter(protocol, stringBuffer);
}
#endif
try {
TraceMethod caller = Tracing.On ? new TraceMethod(this, "Invoke") : null;
TraceMethod userMethod = Tracing.On ? new TraceMethod(protocol.Target, protocol.MethodInfo.Name, this.parameters) : null;
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller, userMethod);
object[] returnValues = protocol.MethodInfo.Invoke(protocol.Target, this.parameters);
if (Tracing.On) Tracing.Exit(protocol.MethodInfo.ToString(), caller);
WriteReturns(returnValues);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "Invoke", e);
if (!protocol.IsOneWay) {
WriteException(e);
throw;
}
}
finally {
protocol.DisposeServerInstance();
#if !MONO
if (debugger != null)
debugger.NotifyServerCallExit(protocol.Response);
#endif
}
}
// By keeping this in a separate method we avoid jitting system.enterpriseservices.dll in cases
// where transactions are not used.
void InvokeTransacted() {
Transactions.InvokeTransacted(new TransactedCallback(this.Invoke), protocol.MethodAttribute.TransactionOption);
}
void ThrowInitException() {
HandleOneWayException(new Exception(Res.GetString(Res.WebConfigExtensionError), protocol.OnewayInitException), "ThrowInitException");
}
void HandleOneWayException(Exception e, string method) {
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, string.IsNullOrEmpty(method) ? "HandleOneWayException" : method, e);
// exceptions for one-way calls are dropped because the response is already written
}
protected void CoreProcessRequest() {
try {
bool transacted = protocol.MethodAttribute.TransactionEnabled;
if (protocol.IsOneWay) {
WorkItemCallback callback = null;
TraceMethod callbackMethod = null;
if (protocol.OnewayInitException != null) {
callback = new WorkItemCallback(this.ThrowInitException);
callbackMethod = Tracing.On ? new TraceMethod(this, "ThrowInitException") : null;
}
else {
parameters = protocol.ReadParameters();
callback = transacted ? new WorkItemCallback(this.OneWayInvokeTransacted) : new WorkItemCallback(this.OneWayInvoke);
callbackMethod = Tracing.On ? transacted ? new TraceMethod(this, "OneWayInvokeTransacted") : new TraceMethod(this, "OneWayInvoke") : null;
}
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemIn, callbackMethod);
WorkItem.Post(callback);
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemOut, callbackMethod);
protocol.WriteOneWayResponse();
}
else if (transacted) {
parameters = protocol.ReadParameters();
InvokeTransacted();
}
else {
parameters = protocol.ReadParameters();
Invoke();
}
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "CoreProcessRequest", e);
if (!protocol.IsOneWay)
WriteException(e);
}
TraceFlush();
}
private HttpContext SwitchContext(HttpContext context) {
PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();
HttpContext oldContext = HttpContext.Current;
HttpContext.Current = context;
return oldContext;
}
private void OneWayInvoke() {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
Invoke();
}
catch (Exception e) {
HandleOneWayException(e, "OneWayInvoke");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
private void OneWayInvokeTransacted() {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
InvokeTransacted();
}
catch (Exception e) {
HandleOneWayException(e, "OneWayInvokeTransacted");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
private void Callback(IAsyncResult result) {
if (!result.CompletedSynchronously)
this.asyncBeginComplete.WaitOne();
DoCallback(result);
}
private void DoCallback(IAsyncResult result) {
if (this.asyncCallback != null) {
if (System.Threading.Interlocked.Increment(ref this.asyncCallbackCalls) == 1) {
this.asyncCallback(result);
}
}
}
protected IAsyncResult BeginCoreProcessRequest(AsyncCallback callback, object asyncState) {
IAsyncResult asyncResult;
if (protocol.MethodAttribute.TransactionEnabled)
throw new InvalidOperationException(Res.GetString(Res.WebAsyncTransaction));
parameters = protocol.ReadParameters();
if (protocol.IsOneWay) {
TraceMethod callbackMethod = Tracing.On ? new TraceMethod(this, "OneWayAsyncInvoke") : null;
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemIn, callbackMethod);
WorkItem.Post(new WorkItemCallback(this.OneWayAsyncInvoke));
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemOut, callbackMethod);
asyncResult = new CompletedAsyncResult(asyncState, true);
if (callback != null)
callback(asyncResult);
}
else
asyncResult = BeginInvoke(callback, asyncState);
return asyncResult;
}
private void OneWayAsyncInvoke() {
if (protocol.OnewayInitException != null)
HandleOneWayException(new Exception(Res.GetString(Res.WebConfigExtensionError), protocol.OnewayInitException), "OneWayAsyncInvoke");
else {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
BeginInvoke(new AsyncCallback(this.OneWayCallback), null);
}
catch (Exception e) {
HandleOneWayException(e, "OneWayAsyncInvoke");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
}
private IAsyncResult BeginInvoke(AsyncCallback callback, object asyncState) {
IAsyncResult asyncResult;
try {
PrepareContext();
protocol.CreateServerInstance();
this.asyncCallback = callback;
TraceMethod caller = Tracing.On ? new TraceMethod(this, "BeginInvoke") : null;
TraceMethod userMethod = Tracing.On ? new TraceMethod(protocol.Target, protocol.MethodInfo.Name, this.parameters) : null;
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller, userMethod);
asyncResult = protocol.MethodInfo.BeginInvoke(protocol.Target, this.parameters, new AsyncCallback(this.Callback), asyncState);
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller);
if (asyncResult == null) throw new InvalidOperationException(Res.GetString(Res.WebNullAsyncResultInBegin));
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "BeginInvoke", e);
// save off the exception and throw it in EndCoreProcessRequest
exception = e;
asyncResult = new CompletedAsyncResult(asyncState, true);
this.asyncCallback = callback;
this.DoCallback(asyncResult);
}
this.asyncBeginComplete.Set();
TraceFlush();
return asyncResult;
}
private void OneWayCallback(IAsyncResult asyncResult) {
EndInvoke(asyncResult);
}
protected void EndCoreProcessRequest(IAsyncResult asyncResult) {
if (asyncResult == null) return;
if (protocol.IsOneWay)
protocol.WriteOneWayResponse();
else
EndInvoke(asyncResult);
}
private void EndInvoke(IAsyncResult asyncResult) {
try {
if (exception != null)
throw (exception);
object[] returnValues = protocol.MethodInfo.EndInvoke(protocol.Target, asyncResult);
WriteReturns(returnValues);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "EndInvoke", e);
if (!protocol.IsOneWay)
WriteException(e);
}
finally {
protocol.DisposeServerInstance();
}
TraceFlush();
}
void WriteReturns(object[] returnValues) {
if (protocol.IsOneWay) return;
// By default ASP.NET will fully buffer the response. If BufferResponse=false
// then we still want to do partial buffering since each write is a named
// pipe call over to inetinfo.
bool fullyBuffered = protocol.MethodAttribute.BufferResponse;
Stream outputStream = protocol.Response.OutputStream;
if (!fullyBuffered) {
outputStream = new BufferedResponseStream(outputStream, 16 * 1024);
//#if DEBUG
((BufferedResponseStream)outputStream).FlushEnabled = false;
//#endif
}
protocol.WriteReturns(returnValues, outputStream);
// This will flush the buffered stream and the underlying stream. Its important
// that it flushes the Response.OutputStream because we always want BufferResponse=false
// to mean we are writing back a chunked response. This gives a consistent
// behavior to the client, independent of the size of the partial buffering.
if (!fullyBuffered) {
//#if DEBUG
((BufferedResponseStream)outputStream).FlushEnabled = true;
//#endif
outputStream.Flush();
}
}
}
internal class SyncSessionlessHandler : WebServiceHandler, IHttpHandler {
internal SyncSessionlessHandler(ServerProtocol protocol) : base(protocol) { }
public bool IsReusable {
get { return false; }
}
public void ProcessRequest(HttpContext context) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "ProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpHandler.ProcessRequest", method, Tracing.Details(context.Request));
CoreProcessRequest();
if (Tracing.On) Tracing.Exit("IHttpHandler.ProcessRequest", method);
}
}
internal class SyncSessionHandler : SyncSessionlessHandler, IRequiresSessionState {
internal SyncSessionHandler(ServerProtocol protocol) : base(protocol) { }
}
internal class AsyncSessionlessHandler : SyncSessionlessHandler, IHttpAsyncHandler {
internal AsyncSessionlessHandler(ServerProtocol protocol) : base(protocol) { }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callback, object asyncState) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "BeginProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpAsyncHandler.BeginProcessRequest", method, Tracing.Details(context.Request));
IAsyncResult result = BeginCoreProcessRequest(callback, asyncState);
if (Tracing.On) Tracing.Exit("IHttpAsyncHandler.BeginProcessRequest", method);
return result;
}
public void EndProcessRequest(IAsyncResult asyncResult) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "EndProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpAsyncHandler.EndProcessRequest", method);
EndCoreProcessRequest(asyncResult);
if (Tracing.On) Tracing.Exit("IHttpAsyncHandler.EndProcessRequest", method);
}
}
internal class AsyncSessionHandler : AsyncSessionlessHandler, IRequiresSessionState {
internal AsyncSessionHandler(ServerProtocol protocol) : base(protocol) { }
}
class CompletedAsyncResult : IAsyncResult {
object asyncState;
bool completedSynchronously;
internal CompletedAsyncResult(object asyncState, bool completedSynchronously) {
this.asyncState = asyncState;
this.completedSynchronously = completedSynchronously;
}
public object AsyncState { get { return asyncState; } }
public bool CompletedSynchronously { get { return completedSynchronously; } }
public bool IsCompleted { get { return true; } }
public WaitHandle AsyncWaitHandle { get { return null; } }
}
}
| |
namespace Topshelf.Internal
{
using System;
using System.Collections.Generic;
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class LocalizationRequiredAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationRequiredAttribute"/> class.
/// </summary>
/// <param name="required"><c>true</c> if a element should be localized; otherwise, <c>false</c>.</param>
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
/// <summary>
/// Gets a value indicating whether a element should be localized.
/// <value><c>true</c> if a element should be localized; otherwise, <c>false</c>.</value>
/// </summary>
public bool Required { get; set; }
/// <summary>
/// Returns whether the value of the given object is equal to the current <see cref="LocalizationRequiredAttribute"/>.
/// </summary>
/// <param name="obj">The object to test the value equality of. </param>
/// <returns>
/// <c>true</c> if the value of the given object is equal to that of the current; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
var attribute = obj as LocalizationRequiredAttribute;
return attribute != null && attribute.Required == Required;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A hash code for the current <see cref="LocalizationRequiredAttribute"/>.</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
}
/// <summary>
/// Indicates that marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor.
/// The format string should be in <see cref="string.Format(IFormatProvider,string,object[])"/> -like form
/// </summary>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class StringFormatMethodAttribute : Attribute
{
readonly string myFormatParameterName;
/// <summary>
/// Initializes new instance of StringFormatMethodAttribute
/// </summary>
/// <param name="formatParameterName">Specifies which parameter of an annotated method should be treated as format-string</param>
public StringFormatMethodAttribute(string formatParameterName)
{
myFormatParameterName = formatParameterName;
}
/// <summary>
/// Gets format parameter name
/// </summary>
public string FormatParameterName
{
get { return myFormatParameterName; }
}
}
/// <summary>
/// Indicates that the function argument should be string literal and match one of the parameters of the caller function.
/// For example, <see cref="ArgumentNullException"/> has such parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InvokerParameterNameAttribute : Attribute
{
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if one of the conditions is satisfied.
/// To set the condition, mark one of the parameters with <see cref="AssertionConditionAttribute"/> attribute
/// </summary>
/// <seealso cref="AssertionConditionAttribute"/>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AssertionMethodAttribute : Attribute
{
}
/// <summary>
/// Indicates the condition parameter of the assertion method.
/// The method itself should be marked by <see cref="AssertionMethodAttribute"/> attribute.
/// The mandatory argument of the attribute is the assertion type.
/// </summary>
/// <seealso cref="AssertionConditionType"/>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class AssertionConditionAttribute : Attribute
{
readonly AssertionConditionType myConditionType;
/// <summary>
/// Initializes new instance of AssertionConditionAttribute
/// </summary>
/// <param name="conditionType">Specifies condition type</param>
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
myConditionType = conditionType;
}
/// <summary>
/// Gets condition type
/// </summary>
public AssertionConditionType ConditionType
{
get { return myConditionType; }
}
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisifes the condition, then the execution continues.
/// Otherwise, execution is assumed to be halted
/// </summary>
public enum AssertionConditionType
{
/// <summary>
/// Indicates that the marked parameter should be evaluated to true
/// </summary>
IS_TRUE = 0,
/// <summary>
/// Indicates that the marked parameter should be evaluated to false
/// </summary>
IS_FALSE = 1,
/// <summary>
/// Indicates that the marked parameter should be evaluated to null value
/// </summary>
IS_NULL = 2,
/// <summary>
/// Indicates that the marked parameter should be evaluated to not null value
/// </summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class TerminatesProgramAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked element could be <c>null</c> sometimes, so the check for <c>null</c> is necessary before its usage
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate
| AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked element could never be <c>null</c>
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Delegate
| AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class NotNullAttribute : Attribute
{
}
/// <summary>
/// Indicates that the value of marked type (or its derivatives) cannot be compared using '==' or '!=' operators.
/// There is only exception to compare with <c>null</c>, it is permitted
/// </summary>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false,
Inherited = true)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute
{
}
/// <summary>
/// When applied to target attribute, specifies a requirement for any type which is marked with
/// target attribute to implement or inherit specific type or types
/// </summary>
/// <example>
/// <code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute
/// {}
///
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent
/// {}
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
readonly Type[] myBaseTypes;
/// <summary>
/// Initializes new instance of BaseTypeRequiredAttribute
/// </summary>
/// <param name="baseTypes">Specifies which types are required</param>
public BaseTypeRequiredAttribute(params Type[] baseTypes)
{
myBaseTypes = baseTypes;
}
/// <summary>
/// Gets enumerations of specified base types
/// </summary>
public IEnumerable<Type> BaseTypes
{
get { return myBaseTypes; }
}
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class UsedImplicitlyAttribute : Attribute
{
[UsedImplicitly]
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
[UsedImplicitly]
public ImplicitUseKindFlags UseKindFlags { get; private set; }
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class MeansImplicitUseAttribute : Attribute
{
[UsedImplicitly]
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly]
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default)
{
}
[UsedImplicitly]
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags)
{
}
[UsedImplicitly]
public ImplicitUseKindFlags UseKindFlags { get; private set; }
/// <summary>
/// Gets value indicating what is meant to be used
/// </summary>
[UsedImplicitly]
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | Instantiated,
/// <summary>
/// Only entity marked with attribute considered used
/// </summary>
Access = 1,
/// <summary>
/// Indicates implicit assignment to a member
/// </summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type
/// </summary>
Instantiated = 4,
}
/// <summary>
/// Specify what is considered used implicitly when marked with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>
/// Members of entity marked with attribute are considered used
/// </summary>
Members = 2,
/// <summary>
/// Entity marked with attribute and all its members considered used
/// </summary>
WithMembers = Itself | Members
}
}
| |
#region Copyright & License
//
// Author: Ian Davis <ian.f.davis@gmail.com> Copyright (c) 2007, Ian Davs
//
// Portions of this software were developed for NUnit. See NOTICE.txt for more
// information.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
#endregion
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using Ensurance.Constraints;
using Ensurance.Properties;
namespace Ensurance.MessageWriters
{
/// <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>
#if !DEBUG
[System.Diagnostics.DebuggerNonUserCode]
#endif
public class TextMessageWriter : MessageWriter
{
#region Message Formats and Constants
private const int MAX_LINE_LENGTH = 78;
/// <summary>
/// Prefix used for the actual value line of a message
/// </summary>
public static readonly string Pfx_Actual = Resources.PrefixActual;
/// <summary>
/// Prefix used for the expected value line of a message
/// </summary>
public static readonly string Pfx_Expected = Resources.PrefixExpected;
/// <summary>
/// Length of a message prefix
/// </summary>
public static readonly int PrefixLength = Pfx_Expected.Length;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="TextMessageWriter"/>
/// class.
/// </summary>
public TextMessageWriter()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TextMessageWriter"/>
/// class.
/// </summary>
/// <param name="textWriter">The textWriter.</param>
public TextMessageWriter( TextWriter textWriter ) : base( textWriter )
{
}
#region Properties
/// <summary>
/// Gets the maximum line length for this writer
/// </summary>
public override int MaxLineLength
{
get { return MAX_LINE_LENGTH; }
}
#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 givel
/// 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 )
{
TextWriter.Write( " " );
}
if ( args != null && args.Length > 0 )
{
message = string.Format( CultureInfo.CurrentCulture, message, args );
}
TextWriter.WriteLine( 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="constraint">The constraint that failed</param>
public override void DisplayDifferences( Constraint constraint )
{
WriteExpectedLine( constraint );
WriteActualLine( constraint );
}
/// <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 )
{
WriteExpectedLine( expected );
WriteActualLine( actual );
}
/// <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, object tolerance )
{
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>
public override void DisplayStringDifferences( string expected, string actual, int mismatch, bool ignoreCase )
{
// Maximum string we can display without truncating
int maxStringLength = MAX_LINE_LENGTH
- PrefixLength // Allow for prefix
- 2; // 2 quotation marks
expected = MsgUtils.ConvertWhitespace( MsgUtils.ClipString( expected, maxStringLength, mismatch ) );
actual = MsgUtils.ConvertWhitespace( MsgUtils.ClipString( actual, maxStringLength, mismatch ) );
// The mismatch position may have changed due to clipping or white
// space conversion
mismatch = MsgUtils.FindMismatchPosition( expected, actual, 0, ignoreCase );
TextWriter.Write( Pfx_Expected );
WriteExpectedValue( expected );
if ( ignoreCase )
{
WriteModifier( Resources.IgnoringCase );
}
TextWriter.WriteLine();
WriteActualLine( actual );
//DisplayDifferences(expected, actual);
if ( mismatch >= 0 )
{
WriteCaretLine( mismatch );
}
}
#endregion
#region Public Methods - Low Level
/// <summary>
/// Writes the text for a connector.
/// </summary>
/// <param name="connector">The connector.</param>
public override void WriteConnector( string connector )
{
TextWriter.Write( Resources.Format_Connector, connector );
}
/// <summary>
/// Writes the text for a predicate.
/// </summary>
/// <param name="predicate">The predicate.</param>
public override void WritePredicate( string predicate )
{
TextWriter.Write( Resources.Format_Predicate, predicate );
}
/// <summary>
/// Write the text for a modifier.
/// </summary>
/// <param name="modifier">The modifier.</param>
public override void WriteModifier( string modifier )
{
TextWriter.Write( Resources.Format_Modifier, modifier );
}
/// <summary>
/// Writes the text for an expected value.
/// </summary>
/// <param name="expected">The expected value.</param>
public override void WriteExpectedValue( object expected )
{
WriteValue( expected );
}
/// <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 )
{
if ( val == null )
{
TextWriter.Write( Resources.Format_Null );
}
else if ( val.GetType().IsArray )
{
WriteArray( (Array) val );
}
else if ( val is ICollection )
{
WriteCollectionElements( (ICollection) val, 0, 10 );
}
else if ( val is string )
{
WriteString( (string) val );
}
else if ( val is char )
{
WriteChar( (char) val );
}
else if ( val is double )
{
WriteDouble( (double) val );
}
else if ( val is float )
{
WriteFloat( (float) val );
}
else if ( val is decimal )
{
WriteDecimal( (decimal) val );
}
else if ( val is DateTime )
{
WriteDateTime( (DateTime) val );
}
else if ( val.GetType().IsValueType )
{
TextWriter.Write( Resources.Format_ValueType, val );
}
else
{
TextWriter.Write( Resources.Format_Default, 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( ICollection collection, int start, int max )
{
if ( collection.Count == 0 )
{
TextWriter.Write( Resources.Format_EmptyCollection );
return;
}
int count = 0;
int index = 0;
TextWriter.Write( "< " );
foreach (object obj in collection)
{
if ( index++ >= start )
{
if ( count > 0 )
{
TextWriter.Write( ", " );
}
WriteValue( obj );
if ( ++count >= max )
{
break;
}
}
}
if ( index < collection.Count )
{
TextWriter.Write( "..." );
}
TextWriter.Write( " >" );
}
/// <summary>
/// Writes the array.
/// </summary>
/// <param name="array">The array.</param>
private void WriteArray( Array array )
{
if ( array.Length == 0 )
{
TextWriter.Write( Resources.Format_EmptyCollection );
return;
}
int rank = array.Rank;
int[] products = new int[rank];
for (int product = 1, r = rank; --r >= 0;)
{
products[r] = product *= array.GetLength( r );
}
int count = 0;
foreach (object obj in array)
{
if ( count > 0 )
{
TextWriter.Write( ", " );
}
bool startSegment = false;
for (int r = 0; r < rank; r++)
{
startSegment = startSegment || count % products[r] == 0;
if ( startSegment )
{
TextWriter.Write( "< " );
}
}
WriteValue( obj );
++count;
bool nextSegment = false;
for (int r = 0; r < rank; r++)
{
nextSegment = nextSegment || count % products[r] == 0;
if ( nextSegment )
{
TextWriter.Write( " >" );
}
}
}
}
/// <summary>
/// Writes the string.
/// </summary>
/// <param name="s">The s.</param>
private void WriteString( string s )
{
if ( string.IsNullOrEmpty( s ) )
{
TextWriter.Write( Resources.Format_EmptyString );
}
else
{
TextWriter.Write( Resources.Format_String, s );
}
}
/// <summary>
/// Writes the char.
/// </summary>
/// <param name="c">The c.</param>
private void WriteChar( char c )
{
TextWriter.Write( Resources.Format_Char, c );
}
/// <summary>
/// Writes the double.
/// </summary>
/// <param name="d">The d.</param>
private void WriteDouble( double d )
{
if ( double.IsNaN( d ) || double.IsInfinity( d ) )
{
TextWriter.Write( d );
}
else
{
string s = d.ToString( "G17", CultureInfo.InvariantCulture );
if ( s.IndexOf( '.' ) > 0 )
{
TextWriter.Write( s + "d" );
}
else
{
TextWriter.Write( s + ".0d" );
}
}
}
/// <summary>
/// Writes the float.
/// </summary>
/// <param name="f">The f.</param>
private void WriteFloat( float f )
{
if ( float.IsNaN( f ) || float.IsInfinity( f ) )
{
TextWriter.Write( f );
}
else
{
string s = f.ToString( "G9", CultureInfo.InvariantCulture );
if ( s.IndexOf( '.' ) > 0 )
{
TextWriter.Write( s + "f" );
}
else
{
TextWriter.Write( s + ".0f" );
}
}
}
/// <summary>
/// Writes the decimal.
/// </summary>
/// <param name="d">The d.</param>
private void WriteDecimal( Decimal d )
{
TextWriter.Write( d.ToString( "G29", CultureInfo.InvariantCulture ) + "m" );
}
/// <summary>
/// Writes the date time.
/// </summary>
/// <param name="dt">The dt.</param>
private void WriteDateTime( DateTime dt )
{
TextWriter.Write( dt.ToString( Resources.Format_DateTime, CultureInfo.InvariantCulture ) );
}
#endregion
#region Helper Methods
/// <summary>
/// Write the generic 'Expected' line for a constraint
/// </summary>
/// <param name="constraint">The constraint that failed</param>
private void WriteExpectedLine( Constraint constraint )
{
TextWriter.Write( Pfx_Expected );
constraint.WriteDescriptionTo( this );
TextWriter.WriteLine();
}
/// <summary>
/// Write the generic 'Expected' line for a given value
/// </summary>
/// <param name="expected">The expected value</param>
private void WriteExpectedLine( object expected )
{
TextWriter.Write( Pfx_Expected );
WriteExpectedValue( expected );
TextWriter.WriteLine();
}
/// <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, object tolerance )
{
TextWriter.Write( Pfx_Expected );
WriteExpectedValue( expected );
WriteConnector( "+/-" );
WriteExpectedValue( tolerance );
TextWriter.WriteLine();
}
/// <summary>
/// Write the generic 'Actual' line for a constraint
/// </summary>
/// <param name="constraint">The constraint for which the actual value is to be written</param>
private void WriteActualLine( Constraint constraint )
{
TextWriter.Write( Pfx_Actual );
constraint.WriteActualValueTo( this );
TextWriter.WriteLine();
}
/// <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 )
{
TextWriter.Write( Pfx_Actual );
WriteActualValue( actual );
TextWriter.WriteLine();
}
private void WriteCaretLine( int mismatch )
{
// We subtract 2 for the initial 2 blanks and add back 1 for the
// initial quote
TextWriter.WriteLine( " {0}^", new string( '-', PrefixLength + mismatch - 2 + 1 ) );
}
#endregion
/// <summary>
/// Handles an Ensurance failure for the given constraint. Implementors
/// should always call
/// <code>
/// if( successor != null ) {
/// successor.Handle( constraint, message, args );
/// }
/// </code>
/// So that the downstream handler can have a chance to process the
/// failure.
/// </summary>
/// <param name="constraint">The constraint.</param>
/// <param name="message">The message.</param>
/// <param name="args">The args.</param>
public override void Handle( Constraint constraint, string message, params object[] args )
{
try
{
if ( !string.IsNullOrEmpty( message ) )
{
WriteMessageLine( message, args );
}
constraint.WriteMessageTo( this );
}
finally
{
IEnsuranceResponsibilityChainLink handler = Successor;
if ( handler != null )
{
handler.Handle( constraint, message, args );
}
}
}
}
}
| |
// 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.AcceptanceTestsRequiredOptional
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Extension methods for ExplicitModel.
/// </summary>
public static partial class ExplicitModelExtensions
{
/// <summary>
/// Test explicitly required integer. Please put null and the client library
/// should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static Error PostRequiredIntegerParameter(this IExplicitModel operations, int bodyParameter)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required integer. Please put null and the client library
/// should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredIntegerParameterAsync(this IExplicitModel operations, int bodyParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional integer. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static void PostOptionalIntegerParameter(this IExplicitModel operations, int? bodyParameter = default(int?))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional integer. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalIntegerParameterAsync(this IExplicitModel operations, int? bodyParameter = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required integer. Please put a valid int-wrapper with
/// 'value' = null and the client library should throw before the request is
/// sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static Error PostRequiredIntegerProperty(this IExplicitModel operations, int value)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required integer. Please put a valid int-wrapper with
/// 'value' = null and the client library should throw before the request is
/// sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredIntegerPropertyAsync(this IExplicitModel operations, int value, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional integer. Please put a valid int-wrapper with
/// 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static void PostOptionalIntegerProperty(this IExplicitModel operations, int? value = default(int?))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional integer. Please put a valid int-wrapper with
/// 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalIntegerPropertyAsync(this IExplicitModel operations, int? value = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required integer. Please put a header 'headerParameter'
/// => null and the client library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
public static Error PostRequiredIntegerHeader(this IExplicitModel operations, int headerParameter)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required integer. Please put a header 'headerParameter'
/// => null and the client library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredIntegerHeaderAsync(this IExplicitModel operations, int headerParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional integer. Please put a header 'headerParameter'
/// => null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
public static void PostOptionalIntegerHeader(this IExplicitModel operations, int? headerParameter = default(int?))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional integer. Please put a header 'headerParameter'
/// => null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalIntegerHeaderAsync(this IExplicitModel operations, int? headerParameter = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required string. Please put null and the client library
/// should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static Error PostRequiredStringParameter(this IExplicitModel operations, string bodyParameter)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required string. Please put null and the client library
/// should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredStringParameterAsync(this IExplicitModel operations, string bodyParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional string. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static void PostOptionalStringParameter(this IExplicitModel operations, string bodyParameter = default(string))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional string. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalStringParameterAsync(this IExplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required string. Please put a valid string-wrapper with
/// 'value' = null and the client library should throw before the request is
/// sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static Error PostRequiredStringProperty(this IExplicitModel operations, string value)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required string. Please put a valid string-wrapper with
/// 'value' = null and the client library should throw before the request is
/// sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredStringPropertyAsync(this IExplicitModel operations, string value, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional integer. Please put a valid string-wrapper with
/// 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static void PostOptionalStringProperty(this IExplicitModel operations, string value = default(string))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional integer. Please put a valid string-wrapper with
/// 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalStringPropertyAsync(this IExplicitModel operations, string value = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required string. Please put a header 'headerParameter'
/// => null and the client library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
public static Error PostRequiredStringHeader(this IExplicitModel operations, string headerParameter)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required string. Please put a header 'headerParameter'
/// => null and the client library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredStringHeaderAsync(this IExplicitModel operations, string headerParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredStringHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional string. Please put a header 'headerParameter'
/// => null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static void PostOptionalStringHeader(this IExplicitModel operations, string bodyParameter = default(string))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringHeaderAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional string. Please put a header 'headerParameter'
/// => null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalStringHeaderAsync(this IExplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalStringHeaderWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required complex object. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static Error PostRequiredClassParameter(this IExplicitModel operations, Product bodyParameter)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required complex object. Please put null and the client
/// library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredClassParameterAsync(this IExplicitModel operations, Product bodyParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional complex object. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static void PostOptionalClassParameter(this IExplicitModel operations, Product bodyParameter = default(Product))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalClassParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional complex object. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalClassParameterAsync(this IExplicitModel operations, Product bodyParameter = default(Product), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required complex object. Please put a valid class-wrapper
/// with 'value' = null and the client library should throw before the
/// request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static Error PostRequiredClassProperty(this IExplicitModel operations, Product value)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required complex object. Please put a valid class-wrapper
/// with 'value' = null and the client library should throw before the
/// request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredClassPropertyAsync(this IExplicitModel operations, Product value, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional complex object. Please put a valid class-wrapper
/// with 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static void PostOptionalClassProperty(this IExplicitModel operations, Product value = default(Product))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalClassPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional complex object. Please put a valid class-wrapper
/// with 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalClassPropertyAsync(this IExplicitModel operations, Product value = default(Product), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required array. Please put null and the client library
/// should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static Error PostRequiredArrayParameter(this IExplicitModel operations, IList<string> bodyParameter)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required array. Please put null and the client library
/// should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredArrayParameterAsync(this IExplicitModel operations, IList<string> bodyParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional array. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
public static void PostOptionalArrayParameter(this IExplicitModel operations, IList<string> bodyParameter = default(IList<string>))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayParameterAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional array. Please put null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bodyParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalArrayParameterAsync(this IExplicitModel operations, IList<string> bodyParameter = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required array. Please put a valid array-wrapper with
/// 'value' = null and the client library should throw before the request is
/// sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static Error PostRequiredArrayProperty(this IExplicitModel operations, IList<string> value)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required array. Please put a valid array-wrapper with
/// 'value' = null and the client library should throw before the request is
/// sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredArrayPropertyAsync(this IExplicitModel operations, IList<string> value, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional array. Please put a valid array-wrapper with
/// 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
public static void PostOptionalArrayProperty(this IExplicitModel operations, IList<string> value = default(IList<string>))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayPropertyAsync(value), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional array. Please put a valid array-wrapper with
/// 'value' = null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='value'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalArrayPropertyAsync(this IExplicitModel operations, IList<string> value = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Test explicitly required array. Please put a header 'headerParameter'
/// => null and the client library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
public static Error PostRequiredArrayHeader(this IExplicitModel operations, IList<string> headerParameter)
{
return Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly required array. Please put a header 'headerParameter'
/// => null and the client library should throw before the request is sent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Error> PostRequiredArrayHeaderAsync(this IExplicitModel operations, IList<string> headerParameter, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PostRequiredArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Test explicitly optional integer. Please put a header 'headerParameter'
/// => null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
public static void PostOptionalArrayHeader(this IExplicitModel operations, IList<string> headerParameter = default(IList<string>))
{
Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayHeaderAsync(headerParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Test explicitly optional integer. Please put a header 'headerParameter'
/// => null.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='headerParameter'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PostOptionalArrayHeaderAsync(this IExplicitModel operations, IList<string> headerParameter = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PostOptionalArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
/*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Piranha.AspNetCore.Services;
using Piranha.Models;
namespace Piranha.AspNetCore.Http
{
/// <summary>
/// The main application middleware.
/// </summary>
public class RoutingMiddleware : MiddlewareBase
{
private readonly RoutingOptions _options;
/// <summary>
/// Creates a new middleware instance.
/// </summary>
/// <param name="next">The next middleware in the pipeline</param>
/// <param name="options">The current routing options</param>
/// <param name="factory">The logger factory</param>
public RoutingMiddleware(RequestDelegate next, IOptions<RoutingOptions> options, ILoggerFactory factory = null) : base(next, factory)
{
_options = options.Value;
}
/// <summary>
/// Invokes the middleware.
/// </summary>
/// <param name="context">The current http context</param>
/// <param name="api">The current api</param>
/// <param name="service">The application service</param>
/// <returns>An async task</returns>
public override async Task Invoke(HttpContext context, IApi api, IApplicationService service)
{
var appConfig = new Config(api);
if (!IsHandled(context) && !IsManagerRequest(context.Request.Path.Value))
{
var url = context.Request.Path.HasValue ? context.Request.Path.Value : "";
var segments = !string.IsNullOrEmpty(url) ? url.Substring(1).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries) : new string[] { };
int pos = 0;
_logger?.LogDebug($"Url: [{ url }]");
//
// 1: Store raw url & request information
//
service.Request.Url = context.Request.Path.Value;
service.Request.Host = context.Request.Host.Host;
service.Request.Port = context.Request.Host.Port;
service.Request.Scheme = context.Request.Scheme;
//
// 2: Get the current site
//
Site site = null;
var hostname = context.Request.Host.Host;
if (_options.UseSiteRouting)
{
// Try to get the requested site by hostname & prefix
if (segments.Length > 0)
{
var prefixedHostname = $"{hostname}/{segments[0]}";
site = await api.Sites.GetByHostnameAsync(prefixedHostname)
.ConfigureAwait(false);
if (site != null)
{
context.Request.Path = "/" + string.Join("/", segments.Skip(1));
hostname = prefixedHostname;
pos = 1;
}
}
// Try to get the requested site by hostname
if (site == null)
{
site = await api.Sites.GetByHostnameAsync(context.Request.Host.Host)
.ConfigureAwait(false);
}
}
// If we didn't find the site, get the default site
if (site == null)
{
site = await api.Sites.GetDefaultAsync()
.ConfigureAwait(false);
}
if (site != null)
{
// Update application service
service.Site.Id = site.Id;
service.Site.Culture = site.Culture;
service.Site.Sitemap = await api.Sites.GetSitemapAsync(site.Id);
// Set preferred hostname & prefix
var siteHost = GetMatchingHost(site, hostname);
service.Site.Host = siteHost[0];
service.Site.SitePrefix = siteHost[1];
// Set site description
service.Site.Description.Title = site.Title;
service.Site.Description.Body = site.Description;
service.Site.Description.Logo = site.Logo;
// Default to the request hostname
if (string.IsNullOrEmpty(service.Site.Host))
{
service.Site.Host = context.Request.Host.Host;
}
// Set current culture if specified in site
if (!string.IsNullOrEmpty(site.Culture))
{
var cultureInfo = new CultureInfo(service.Site.Culture);
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = cultureInfo;
}
}
else
{
// There's no sites available, let the application finish
await _next.Invoke(context);
return;
}
//
// Check if we shouldn't handle empty requests for start page
//
if (segments.Length <= pos && !_options.UseStartpageRouting)
{
await _next.Invoke(context);
return;
}
//
// 3: Check for alias
//
if (_options.UseAliasRouting && segments.Length > pos)
{
var alias = await api.Aliases.GetByAliasUrlAsync($"/{ string.Join("/", segments.Subset(pos)) }", service.Site.Id);
if (alias != null)
{
context.Response.Redirect(alias.RedirectUrl, alias.Type == RedirectType.Permanent);
return;
}
}
//
// 4: Get the current page
//
PageBase page = null;
PageType pageType = null;
if (segments.Length > pos)
{
// Scan for the most unique slug
for (var n = segments.Length; n > pos; n--)
{
var slug = string.Join("/", segments.Subset(pos, n - pos));
page = await api.Pages.GetBySlugAsync<PageBase>(slug, site.Id)
.ConfigureAwait(false);
if (page != null)
{
pos = n;
break;
}
}
}
else
{
page = await api.Pages.GetStartpageAsync<PageBase>(site.Id)
.ConfigureAwait(false);
}
if (page != null)
{
pageType = App.PageTypes.GetById(page.TypeId);
service.PageId = page.Id;
// Only cache published pages
if (page.IsPublished)
{
service.CurrentPage = page;
}
}
//
// 5: Get the current post
//
PostBase post = null;
if (_options.UsePostRouting)
{
if (page != null && pageType.IsArchive && segments.Length > pos)
{
post = await api.Posts.GetBySlugAsync<PostBase>(page.Id, segments[pos])
.ConfigureAwait(false);
if (post != null)
{
pos++;
}
}
if (post != null)
{
App.PostTypes.GetById(post.TypeId);
// Only cache published posts
if (post.IsPublished)
{
service.CurrentPost = post;
}
}
}
_logger?.LogDebug($"Found Site: [{ site.Id }]");
if (page != null)
{
_logger?.LogDebug($"Found Page: [{ page.Id }]");
}
if (post != null)
{
_logger?.LogDebug($"Found Post: [{ post.Id }]");
}
//
// 6: Route request
//
var route = new StringBuilder();
var query = new StringBuilder();
if (post != null)
{
if (string.IsNullOrWhiteSpace(post.RedirectUrl))
{
// Handle HTTP caching
if (HandleCache(context, site, post, appConfig.CacheExpiresPosts))
{
// Client has latest version
return;
}
route.Append(post.Route ?? "/post");
for (var n = pos; n < segments.Length; n++)
{
route.Append("/");
route.Append(segments[n]);
}
query.Append("id=");
query.Append(post.Id);
}
else
{
_logger?.LogDebug($"Setting redirect: [{ post.RedirectUrl }]");
context.Response.Redirect(post.RedirectUrl, post.RedirectType == RedirectType.Permanent);
return;
}
}
else if (page != null && _options.UsePageRouting)
{
if (string.IsNullOrWhiteSpace(page.RedirectUrl))
{
route.Append(page.Route ?? (pageType.IsArchive ? "/archive" : "/page"));
// Set the basic query
query.Append("id=");
query.Append(page.Id);
if (!page.ParentId.HasValue && page.SortOrder == 0)
{
query.Append("&startpage=true");
}
if (!pageType.IsArchive || !_options.UseArchiveRouting)
{
if (HandleCache(context, site, page, appConfig.CacheExpiresPages))
{
// Client has latest version.
return;
}
// This is a regular page, append trailing segments
for (var n = pos; n < segments.Length; n++)
{
route.Append("/");
route.Append(segments[n]);
}
}
else if (post == null)
{
// This is an archive, check for archive params
int? year = null;
bool foundCategory = false;
bool foundTag = false;
bool foundPage = false;
for (var n = pos; n < segments.Length; n++)
{
if (segments[n] == "category" && !foundPage)
{
foundCategory = true;
continue;
}
if (segments[n] == "tag" && !foundPage && !foundCategory)
{
foundTag = true;
continue;
}
if (segments[n] == "page")
{
foundPage = true;
continue;
}
if (foundCategory)
{
try
{
var categoryId = (await api.Posts.GetCategoryBySlugAsync(page.Id, segments[n]).ConfigureAwait(false))?.Id;
if (categoryId.HasValue)
{
query.Append("&category=");
query.Append(categoryId);
}
}
finally
{
foundCategory = false;
}
}
if (foundTag)
{
try
{
var tagId = (await api.Posts.GetTagBySlugAsync(page.Id, segments[n]).ConfigureAwait(false))?.Id;
if (tagId.HasValue)
{
query.Append("&tag=");
query.Append(tagId);
}
}
finally
{
foundTag = false;
}
}
if (foundPage)
{
try
{
var pageNum = Convert.ToInt32(segments[n]);
query.Append("&page=");
query.Append(pageNum);
query.Append("&pagenum=");
query.Append(pageNum);
}
catch
{
// We don't care about the exception, we just
// discard malformed input
}
// Page number should always be last, break the loop
break;
}
if (!year.HasValue)
{
try
{
year = Convert.ToInt32(segments[n]);
if (year.Value > DateTime.Now.Year)
{
year = DateTime.Now.Year;
}
query.Append("&year=");
query.Append(year);
}
catch
{
// We don't care about the exception, we just
// discard malformed input
}
}
else
{
try
{
var month = Math.Max(Math.Min(Convert.ToInt32(segments[n]), 12), 1);
query.Append("&month=");
query.Append(month);
}
catch
{
// We don't care about the exception, we just
// discard malformed input
}
}
}
}
}
else
{
_logger?.LogDebug($"Setting redirect: [{ page.RedirectUrl }]");
context.Response.Redirect(page.RedirectUrl, page.RedirectType == RedirectType.Permanent);
return;
}
}
if (route.Length > 0)
{
var strRoute = route.ToString();
var strQuery = query.ToString();
_logger?.LogDebug($"Setting Route: [{ strRoute }?{ strQuery }]");
context.Request.Path = new PathString(strRoute);
if (context.Request.QueryString.HasValue)
{
context.Request.QueryString =
new QueryString(context.Request.QueryString.Value + "&" + strQuery);
}
else {
context.Request.QueryString =
new QueryString("?" + strQuery);
}
}
}
await _next.Invoke(context);
}
/// <summary>
/// Handles HTTP Caching Headers and checks if the client has the
/// latest version in cache.
/// </summary>
/// <param name="context">The HTTP Cache</param>
/// <param name="site">The current site</param>
/// <param name="content">The current content</param>
/// <param name="expires">How many minutes the cache should be valid</param>
/// <returns>If the client has the latest version</returns>
public bool HandleCache(HttpContext context, Site site, RoutedContentBase content, int expires)
{
var headers = context.Response.GetTypedHeaders();
if (expires > 0 && content.Published.HasValue)
{
_logger?.LogDebug($"Setting HTTP Cache for [{ content.Slug }]");
var lastModified = !site.ContentLastModified.HasValue || content.LastModified > site.ContentLastModified
? content.LastModified : site.ContentLastModified.Value;
var etag = Utils.GenerateETag(content.Id.ToString(), lastModified);
headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = TimeSpan.FromMinutes(expires),
};
headers.ETag = new EntityTagHeaderValue(etag);
headers.LastModified = lastModified;
if (HttpCaching.IsCached(context, etag, lastModified))
{
_logger?.LogInformation("Client has current version. Setting NotModified");
context.Response.StatusCode = 304;
return true;
}
}
else
{
_logger?.LogDebug($"Setting HTTP NoCache for [{ content.Slug }]");
headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true
};
}
return false;
}
/// <summary>
/// Gets the matching hostname.
/// </summary>
/// <param name="site">The site</param>
/// <param name="hostname">The requested host</param>
/// <returns>The hostname split into host and prefix</returns>
private string[] GetMatchingHost(Site site, string hostname)
{
var result = new string[2];
if (!string.IsNullOrEmpty(site.Hostnames))
{
foreach (var host in site.Hostnames.Split(","))
{
if (host.Trim().ToLower() == hostname)
{
var segments = host.Split("/", StringSplitOptions.RemoveEmptyEntries);
result[0] = segments[0];
result[1] = segments.Length > 1 ? segments[1] : null;
break;
}
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using Northwind.Common.DataModel;
using NUnit.Framework;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Tests.Models;
namespace ServiceStack.Text.Tests.JsvTests
{
[TestFixture]
public class TypeSerializerToStringDictionaryTests
{
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
NorthwindData.LoadData(false);
}
[Test]
public void Can_serialize_ModelWithFieldsOfDifferentTypes_to_StringDictionary()
{
var model = new ModelWithFieldsOfDifferentTypes
{
Id = 1,
Name = "Name1",
LongId = 1000,
Guid = new Guid("{7da74353-a40c-468e-93aa-7ff51f4f0e84}"),
Bool = false,
DateTime = new DateTime(2010, 12, 20),
Double = 2.11d,
};
Console.WriteLine(model.Dump());
/* Prints out:
{
Id: 1,
Name: Name1,
LongId: 1000,
Guid: 7da74353a40c468e93aa7ff51f4f0e84,
Bool: False,
DateTime: 2010-12-20,
Double: 2.11
}
*/
Dictionary<string, string> map = model.ToStringDictionary();
Assert.That(map.EquivalentTo(
new Dictionary<string, string>
{
{"Id","1"},
{"Name","Name1"},
{"LongId","1000"},
{"Guid","7da74353a40c468e93aa7ff51f4f0e84"},
{"Bool","False"},
{"DateTime","2010-12-20"},
{"Double","2.11"},
}));
}
[Test]
public void Can_serialize_Category_to_StringDictionary()
{
Assert.That(NorthwindData.Categories[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","1"},
{"CategoryName","Beverages"},
{"Description","Soft drinks, coffees, teas, beers, and ales"},
}));
}
[Test]
public void Can_serialize_Customer_to_StringDictionary()
{
Assert.That(NorthwindData.Customers[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","ALFKI"},
{"CompanyName","Alfreds Futterkiste"},
{"ContactName","Maria Anders"},
{"ContactTitle","Sales Representative"},
{"Address","Obere Str. 57"},
{"City","Berlin"},
{"PostalCode","12209"},
{"Country","Germany"},
{"Phone","030-0074321"},
{"Fax","030-0076545"},
}));
}
[Test]
public void Can_serialize_Employee_to_StringDictionary()
{
Assert.That(NorthwindData.Employees[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","1"},
{"LastName","Davolio"},
{"FirstName","Nancy"},
{"Title","Sales Representative"},
{"TitleOfCourtesy","Ms."},
{"BirthDate","1948-12-08"},
{"HireDate","1992-05-01"},
{"Address","507 - 20th Ave. E. Apt. 2A"},
{"City","Seattle"},
{"Region","WA"},
{"PostalCode","98122"},
{"Country","USA"},
{"HomePhone","(206) 555-9857"},
{"Extension","5467"},
{"Notes","Education includes a BA in psychology from Colorado State University in 1970. She also completed 'The Art of the Cold Call.' Nancy is a member of Toastmasters International."},
{"ReportsTo","2"},
{"PhotoPath","http://accweb/emmployees/davolio.bmp"},
}));
}
[Test]
public void Can_serialize_EmployeeTerritory_to_StringDictionary()
{
Assert.That(NorthwindData.EmployeeTerritories[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","1/06897"},
{"EmployeeId","1"},
{"TerritoryId","06897"},
}));
}
[Test]
public void Can_serialize_OrderDetail_to_StringDictionary()
{
Assert.That(NorthwindData.OrderDetails[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","10248/11"},
{"OrderId","10248"},
{"ProductId","11"},
{"UnitPrice","14"},
{"Quantity","12"},
{"Discount","0"},
}));
}
[Test]
public void Can_serialize_Order_to_StringDictionary()
{
Assert.That(NorthwindData.Orders[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","10248"},
{"CustomerId","VINET"},
{"EmployeeId","5"},
{"OrderDate","1996-07-04"},
{"RequiredDate","1996-08-01"},
{"ShippedDate","1996-07-16"},
{"ShipVia","3"},
{"Freight","32.38"},
{"ShipName","Vins et alcools Chevalier"},
{"ShipAddress","59 rue de l'Abbaye"},
{"ShipCity","Reims"},
{"ShipPostalCode","51100"},
{"ShipCountry","France"},
}));
}
[Test]
public void Can_serialize_Product_to_StringDictionary()
{
Console.WriteLine(NorthwindData.Products[0].ToStringDictionary());
Assert.That(NorthwindData.Products[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","1"},
{"ProductName","Chai"},
{"SupplierId","1"},
{"CategoryId","1"},
{"QuantityPerUnit","10 boxes x 20 bags"},
{"UnitPrice","18"},
{"UnitsInStock","39"},
{"UnitsOnOrder","0"},
{"ReorderLevel","10"},
{"Discontinued","False"},
}));
}
[Test]
public void Can_serialize_Region_to_StringDictionary()
{
Assert.That(NorthwindData.Regions[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","1"},
{"RegionDescription","Eastern"},
}));
}
[Test]
public void Can_serialize_Shipper_to_StringDictionary()
{
Assert.That(NorthwindData.Shippers[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","1"},
{"CompanyName","Speedy Express"},
{"Phone","(503) 555-9831"},
}));
}
[Test]
public void Can_serialize_Supplier_to_StringDictionary()
{
Assert.That(NorthwindData.Suppliers[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","1"},
{"CompanyName","Exotic Liquids"},
{"ContactName","Charlotte Cooper"},
{"ContactTitle","Purchasing Manager"},
{"Address","49 Gilbert St."},
{"City","London"},
{"PostalCode","EC1 4SD"},
{"Country","UK"},
{"Phone","(171) 555-2222"},
}));
}
[Test]
public void Can_serialize_Territory_to_StringDictionary()
{
Assert.That(NorthwindData.Territories[0].ToStringDictionary().EquivalentTo(
new Dictionary<string, string>
{
{"Id","01581"},
{"TerritoryDescription","Westboro"},
{"RegionId","1"},
}));
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using OmniSharp.Cake.Services.RequestHandlers.Buffer;
using OmniSharp.Cake.Services.RequestHandlers.Refactoring.V2;
using OmniSharp.Mef;
using OmniSharp.Models;
using OmniSharp.Models.UpdateBuffer;
using OmniSharp.Models.V2;
using OmniSharp.Models.V2.CodeActions;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Cake.Tests
{
public class CodeActionsV2Facts : AbstractTestFixture
{
public CodeActionsV2Facts(ITestOutputHelper output)
: base(output)
{
}
[Fact]
public async Task Can_get_code_actions_from_roslyn()
{
const string code = "var regex = new Reg[||]ex();";
var refactorings = await FindRefactoringNamesAsync(code);
Assert.Contains("using System.Text.RegularExpressions;", refactorings);
}
[Fact]
public async Task Can_get_ranged_code_action()
{
const string code =
@"public class Class1
{
public void Whatever()
{
[|Console.Write(""should be using System;"");|]
}
}";
var refactorings = await FindRefactoringNamesAsync(code);
Assert.Contains("Extract Method", refactorings);
}
[Fact]
public async Task Returns_ordered_code_actions()
{
const string code =
@"public class Class1
{
public void Whatever()
{
[|Regex.Match(""foo"", ""bar"");|]
}
}";
var refactorings = await FindRefactoringNamesAsync(code);
var expected = new List<string>
{
"using System.Text.RegularExpressions;",
"System.Text.RegularExpressions.Regex",
"Extract Method"
};
Assert.Equal(expected, refactorings);
}
[Fact]
public async Task Can_extract_method()
{
const string code =
@"public class Class1
{
public void Whatever()
{
[|Console.Write(""should be using System;"");|]
}
}";
var expected = new LinePositionSpanTextChange
{
NewText = "NewMethod();\n }\n\n private static void NewMethod()\n {\n ",
StartLine = 4,
StartColumn = 8,
EndLine = 4,
EndColumn = 8
};
var response = await RunRefactoringAsync(code, "Extract Method");
var modifiedFile = response.Changes.FirstOrDefault() as ModifiedFileResponse;
Assert.Single(response.Changes);
Assert.NotNull(modifiedFile);
Assert.Single(modifiedFile.Changes);
Assert.Equal(expected, modifiedFile.Changes.FirstOrDefault());
}
[Fact]
public async Task Should_Not_Find_Rename_File()
{
const string code =
@"public class Class[||]1
{
public void Whatever()
{
Console.Write(""should be using System;"");
}
}";
var refactorings = await FindRefactoringNamesAsync(code);
Assert.Empty(refactorings.Where(x => x.StartsWith("Rename file to")));
}
private async Task<RunCodeActionResponse> RunRefactoringAsync(string code, string refactoringName)
{
var refactorings = await FindRefactoringsAsync(code);
Assert.Contains(refactoringName, refactorings.Select(a => a.Name));
var identifier = refactorings.First(action => action.Name.Equals(refactoringName)).Identifier;
return await RunRefactoringsAsync(code, identifier);
}
private async Task<IEnumerable<string>> FindRefactoringNamesAsync(string code)
{
var codeActions = await FindRefactoringsAsync(code);
return codeActions.Select(a => a.Name);
}
private async Task<IEnumerable<OmniSharpCodeAction>> FindRefactoringsAsync(string code)
{
using (var testProject = await TestAssets.Instance.GetTestProjectAsync("CakeProject", shadowCopy: false))
using (var host = CreateOmniSharpHost(testProject.Directory))
{
var testFile = new TestFile(Path.Combine(testProject.Directory, "build.cake"), code);
var requestHandler = GetGetCodeActionsHandler(host);
var span = testFile.Content.GetSpans().Single();
var range = testFile.Content.GetRangeFromSpan(span);
var request = new GetCodeActionsRequest
{
Line = range.Start.Line,
Column = range.Start.Offset,
FileName = testFile.FileName,
Buffer = testFile.Content.Code,
Selection = GetSelection(range),
};
var updateBufferRequest = new UpdateBufferRequest
{
Buffer = request.Buffer,
Column = request.Column,
FileName = request.FileName,
Line = request.Line,
FromDisk = false
};
await GetUpdateBufferHandler(host).Handle(updateBufferRequest);
var response = await requestHandler.Handle(request);
return response.CodeActions;
}
}
private async Task<RunCodeActionResponse> RunRefactoringsAsync(string code, string identifier)
{
using (var testProject = await TestAssets.Instance.GetTestProjectAsync("CakeProject", shadowCopy: false))
using (var host = CreateOmniSharpHost(testProject.Directory))
{
var testFile = new TestFile(Path.Combine(testProject.Directory, "build.cake"), code);
var requestHandler = GetRunCodeActionsHandler(host);
var span = testFile.Content.GetSpans().Single();
var range = testFile.Content.GetRangeFromSpan(span);
var request = new RunCodeActionRequest
{
Line = range.Start.Line,
Column = range.Start.Offset,
Selection = GetSelection(range),
FileName = testFile.FileName,
Buffer = testFile.Content.Code,
Identifier = identifier,
WantsTextChanges = true,
WantsAllCodeActionOperations = true
};
var updateBufferRequest = new UpdateBufferRequest
{
Buffer = request.Buffer,
Column = request.Column,
FileName = request.FileName,
Line = request.Line,
FromDisk = false
};
await GetUpdateBufferHandler(host).Handle(updateBufferRequest);
return await requestHandler.Handle(request);
}
}
private static Range GetSelection(TextRange range)
{
if (range.IsEmpty)
{
return null;
}
return new Range
{
Start = new Point { Line = range.Start.Line, Column = range.Start.Offset },
End = new Point { Line = range.End.Line, Column = range.End.Offset }
};
}
private static GetCodeActionsHandler GetGetCodeActionsHandler(OmniSharpTestHost host)
{
return GetRequestHandler<GetCodeActionsHandler>(host, OmniSharpEndpoints.V2.GetCodeActions);
}
private static RunCodeActionsHandler GetRunCodeActionsHandler(OmniSharpTestHost host)
{
return GetRequestHandler<RunCodeActionsHandler>(host, OmniSharpEndpoints.V2.RunCodeAction);
}
private static UpdateBufferHandler GetUpdateBufferHandler(OmniSharpTestHost host)
{
return GetRequestHandler<UpdateBufferHandler>(host, OmniSharpEndpoints.UpdateBuffer);
}
private static TRequestHandler GetRequestHandler<TRequestHandler>(OmniSharpTestHost host, string endpoint) where TRequestHandler : IRequestHandler
{
return host.GetRequestHandler<TRequestHandler>(endpoint, Constants.LanguageNames.Cake);
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.Grains
{
internal class SimpleActivateDeactivateTestGrain : Grain, ISimpleActivateDeactivateTestGrain
{
private Logger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public override async Task OnActivateAsync()
{
logger = GetLogger();
logger.Info("OnActivateAsync");
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingActivate = true;
await watcher.RecordActivateCall(Data.ActivationId.ToString());
Assert.True(doingActivate, "Activate method still running");
doingActivate = false;
}
public override async Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingDeactivate = true;
await watcher.RecordDeactivateCall(Data.ActivationId.ToString());
Assert.True(doingDeactivate, "Deactivate method still running");
doingDeactivate = false;
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return TaskDone.Done;
}
}
internal class TailCallActivateDeactivateTestGrain : Grain, ITailCallActivateDeactivateTestGrain
{
private Logger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public override Task OnActivateAsync()
{
logger = GetLogger();
logger.Info("OnActivateAsync");
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingActivate = true;
return watcher.RecordActivateCall(Data.ActivationId.ToString())
.ContinueWith((Task t) =>
{
Assert.False(t.IsFaulted, "RecordActivateCall failed");
Assert.True(doingActivate, "Doing Activate");
doingActivate = false;
});
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingDeactivate = true;
return watcher.RecordDeactivateCall(Data.ActivationId.ToString())
.ContinueWith((Task t) =>
{
Assert.False(t.IsFaulted, "RecordDeactivateCall failed");
Assert.True(doingDeactivate, "Doing Deactivate");
doingDeactivate = false;
});
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return TaskDone.Done;
}
}
internal class LongRunningActivateDeactivateTestGrain : Grain, ILongRunningActivateDeactivateTestGrain
{
private Logger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public override async Task OnActivateAsync()
{
logger = GetLogger();
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Not doing Activate yet");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingActivate = true;
logger.Info("OnActivateAsync");
// Spawn Task to run on default .NET thread pool
var task = Task.Factory.StartNew(() =>
{
logger.Info("Started-OnActivateAsync-SubTask");
Assert.True(TaskScheduler.Current == TaskScheduler.Default,
"Running under default .NET Task scheduler");
Assert.True(doingActivate, "Still doing Activate in Sub-Task");
logger.Info("Finished-OnActivateAsync-SubTask");
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
await task;
logger.Info("Started-OnActivateAsync");
await watcher.RecordActivateCall(Data.ActivationId.ToString());
Assert.True(doingActivate, "Doing Activate");
logger.Info("OnActivateAsync-Sleep");
Thread.Sleep(TimeSpan.FromSeconds(1));
Assert.True(doingActivate, "Still doing Activate after Sleep");
logger.Info("Finished-OnActivateAsync");
doingActivate = false;
}
public override async Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
Assert.False(doingActivate, "Not doing Activate yet");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingDeactivate = true;
logger.Info("Started-OnDeactivateAsync");
await watcher.RecordDeactivateCall(Data.ActivationId.ToString());
Assert.True(doingDeactivate, "Doing Deactivate");
logger.Info("OnDeactivateAsync-Sleep");
Thread.Sleep(TimeSpan.FromSeconds(1));
logger.Info("Finished-OnDeactivateAsync");
doingDeactivate = false;
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return TaskDone.Done;
}
}
internal class TaskActionActivateDeactivateTestGrain : Grain, ITaskActionActivateDeactivateTestGrain
{
private Logger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public override Task OnActivateAsync()
{
logger = GetLogger();
var startMe =
new Task(
() =>
{
logger.Info("OnActivateAsync");
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Not doing Activate");
Assert.False(doingDeactivate, "Not doing Deactivate");
doingActivate = true;
});
// we want to use Task.ContinueWith with an async lambda, an explicitly typed variable is required to avoid
// writing code that doesn't do what i think it is doing.
Func<Task> asyncCont =
async () =>
{
logger.Info("Started-OnActivateAsync");
Assert.True(doingActivate, "Doing Activate");
Assert.False(doingDeactivate, "Not doing Deactivate");
try
{
logger.Info("Calling RecordActivateCall");
await watcher.RecordActivateCall(Data.ActivationId.ToString());
logger.Info("Returned from calling RecordActivateCall");
}
catch (Exception exc)
{
var msg = "RecordActivateCall failed with error " + exc;
logger.Error(0, msg);
Assert.True(false, msg);
}
Assert.True(doingActivate, "Doing Activate");
Assert.False(doingDeactivate, "Not doing Deactivate");
await Task.Delay(TimeSpan.FromSeconds(1));
doingActivate = false;
logger.Info("Finished-OnActivateAsync");
};
var awaitMe = startMe.ContinueWith(_ => asyncCont()).Unwrap();
startMe.Start();
return awaitMe;
}
public override Task OnDeactivateAsync()
{
Task.Factory.StartNew(() => logger.Info("OnDeactivateAsync"));
Assert.False(doingActivate, "Not doing Activate");
Assert.False(doingDeactivate, "Not doing Deactivate");
doingDeactivate = true;
logger.Info("Started-OnDeactivateAsync");
return watcher.RecordDeactivateCall(Data.ActivationId.ToString())
.ContinueWith((Task t) =>
{
Assert.False(t.IsFaulted, "RecordDeactivateCall failed");
Assert.True(doingDeactivate, "Doing Deactivate");
Thread.Sleep(TimeSpan.FromSeconds(1));
doingDeactivate = false;
})
.ContinueWith((Task t) => logger.Info("Finished-OnDeactivateAsync"),
TaskContinuationOptions.ExecuteSynchronously);
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return TaskDone.Done;
}
}
public class BadActivateDeactivateTestGrain : Grain, IBadActivateDeactivateTestGrain
{
private Logger logger;
public override Task OnActivateAsync()
{
logger = GetLogger();
logger.Info("OnActivateAsync");
throw new ApplicationException("Thrown from Application-OnActivateAsync");
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
throw new ApplicationException("Thrown from Application-OnDeactivateAsync");
}
public Task ThrowSomething()
{
logger.Info("ThrowSomething");
throw new InvalidOperationException("Exception should have been thrown from Activate");
}
public Task<long> GetKey()
{
logger.Info("GetKey");
//return this.GetPrimaryKeyLong();
throw new InvalidOperationException("Exception should have been thrown from Activate");
}
}
internal class BadConstructorTestGrain : Grain, IBadConstructorTestGrain
{
private Logger logger;
public BadConstructorTestGrain()
{
throw new ApplicationException("Thrown from Constructor");
}
public override Task OnActivateAsync()
{
logger = GetLogger();
logger.Info("OnActivateAsync");
throw new NotImplementedException("OnActivateAsync should not have been called");
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
throw new NotImplementedException("OnDeactivateAsync() should not have been called");
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
throw new NotImplementedException("DoSomething should not have been called");
}
}
internal class DeactivatingWhileActivatingTestGrain : Grain, IDeactivatingWhileActivatingTestGrain
{
private Logger logger;
public override Task OnActivateAsync()
{
logger = GetLogger();
logger.Info("OnActivateAsync");
this.DeactivateOnIdle();
return TaskDone.Done;
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return TaskDone.Done;
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
throw new NotImplementedException("DoSomething should not have been called");
}
}
internal class CreateGrainReferenceTestGrain : Grain, ICreateGrainReferenceTestGrain
{
private Logger logger;
//private IEchoGrain orleansManagedGrain;
private ITestGrain grain;
public override Task OnActivateAsync()
{
logger = GetLogger();
grain = GrainFactory.GetGrain<ITestGrain>(1);
logger.Info("OnActivateAsync");
grain = GrainFactory.GetGrain<ITestGrain>(1);
return TaskDone.Done;
}
public async Task<string> DoSomething()
{
logger.Info("DoSomething");
var guid = Guid.NewGuid();
await grain.SetLabel(guid.ToString());
var label = await grain.GetLabel();
if (string.IsNullOrEmpty(label))
{
throw new ArgumentException("Bad data: Null label returned");
}
return Data.ActivationId.ToString();
}
public async Task ForwardCall(IBadActivateDeactivateTestGrain otherGrain)
{
logger.Info("ForwardCall to " + otherGrain);
await otherGrain.ThrowSomething();
}
}
}
| |
/***************************************************************************
* AudioCdRipper.cs
*
* Copyright (C) 2005-2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using Banshee.Winforms;
using Banshee.Winforms.Controls;
using Banshee.Widgets;
using Banshee.Base;
using Banshee.AudioProfiles;
using Banshee.Configuration.Schema;
namespace Banshee.Base
{
public delegate void AudioCdRipperProgressHandler(object o, AudioCdRipperProgressArgs args);
public delegate void AudioCdRipperTrackFinishedHandler(object o, AudioCdRipperTrackFinishedArgs args);
public class AudioCdRipperProgressArgs : EventArgs
{
public int SecondsEncoded;
public int TotalSeconds;
public AudioCdTrackInfo Track;
}
public class AudioCdRipperTrackFinishedArgs : EventArgs
{
public AudioCdTrackInfo Track;
public int TrackNumber;
public SafeUri Uri;
}
public class AudioCdTrackRipper : IDisposable
{
private delegate void GstCdRipperProgressCallback(IntPtr transcoder, int seconds, IntPtr user_info);
private delegate void GstCdRipperFinishedCallback(IntPtr transcoder);
private delegate void GstCdRipperErrorCallback(IntPtr transcoder, IntPtr error, IntPtr debug);
private HandleRef handle;
private GstCdRipperProgressCallback progress_callback;
private GstCdRipperFinishedCallback finished_callback;
private GstCdRipperErrorCallback error_callback;
private string error_message;
private SafeUri output_uri;
private int track_number;
private AudioCdTrackInfo current_track;
public event AudioCdRipperProgressHandler Progress;
public event AudioCdRipperTrackFinishedHandler TrackFinished;
public event EventHandler Error;
public AudioCdTrackRipper(string device, int paranoiaMode, string encoderPipeline)
{
IntPtr ptr = gst_cd_ripper_new(device, paranoiaMode, encoderPipeline);
if(ptr == IntPtr.Zero) {
throw new ApplicationException(Catalog.GetString("Could not create CD Ripper"));
}
handle = new HandleRef(this, ptr);
progress_callback = new GstCdRipperProgressCallback(OnProgress);
gst_cd_ripper_set_progress_callback(handle, progress_callback);
finished_callback = new GstCdRipperFinishedCallback(OnFinished);
gst_cd_ripper_set_finished_callback(handle, finished_callback);
error_callback = new GstCdRipperErrorCallback(OnError);
gst_cd_ripper_set_error_callback(handle, error_callback);
}
public void Dispose()
{
gst_cd_ripper_free(handle);
}
public void RipTrack(AudioCdTrackInfo track, int trackNumber, SafeUri outputUri)
{
error_message = null;
RipTrack_010(track, trackNumber, outputUri);
}
private void RipTrack_010(AudioCdTrackInfo track, int trackNumber, SafeUri outputUri)
{
current_track = track;
track_number = trackNumber;
output_uri = outputUri;
gst_cd_ripper_rip_track(handle, outputUri.AbsoluteUri, trackNumber,
track.Artist, track.Album, track.Title, track.Genre,
(int)track.TrackNumber, (int)track.TrackCount, IntPtr.Zero);
track = null;
}
private void OnTrackFinished(AudioCdTrackInfo track, int trackNumber, SafeUri outputUri)
{
track.IsRipped = true;
track.Uri = outputUri;
AudioCdRipperTrackFinishedHandler handler = TrackFinished;
if(handler != null) {
AudioCdRipperTrackFinishedArgs args = new AudioCdRipperTrackFinishedArgs();
args.Track = track;
args.TrackNumber = trackNumber;
args.Uri = outputUri;
handler(this, args);
}
}
public void Cancel()
{
gst_cd_ripper_cancel(handle);
}
public string ErrorMessage {
get {
return error_message;
}
}
private void OnProgress(IntPtr ripper, int seconds, IntPtr user_info)
{
AudioCdRipperProgressHandler handler = Progress;
if(handler == null)
return;
AudioCdRipperProgressArgs args = new AudioCdRipperProgressArgs();
args.TotalSeconds = (int)current_track.Duration.TotalSeconds;
args.SecondsEncoded = seconds;
args.Track = current_track;
handler(this, args);
}
private void OnFinished(IntPtr ripper)
{
OnTrackFinished(current_track, track_number, output_uri);
}
private void OnError(IntPtr ripper, IntPtr error, IntPtr debug)
{
error_message = error.ToString();
if(debug != IntPtr.Zero) {
string debug_string = debug.ToString();
if(debug_string != null && debug_string != String.Empty) {
error_message += ": " + debug_string;
}
}
if(Error != null) {
Error(this, new EventArgs());
}
}
[DllImport("libbanshee")]
private static extern IntPtr gst_cd_ripper_new(string device,
int paranoia_mode, string encoder_pipeline);
[DllImport("libbanshee")]
private static extern void gst_cd_ripper_free(HandleRef ripper);
[DllImport("libbanshee")]
private static extern bool gst_cd_ripper_rip_track(HandleRef ripper,
string uri, int track_number, string md_artist, string md_album,
string md_title, string md_genre, int md_track_number,
int md_track_count, IntPtr user_info);
[DllImport("libbanshee")]
private static extern void gst_cd_ripper_set_progress_callback(
HandleRef ripper, GstCdRipperProgressCallback cb);
[DllImport("libbanshee")]
private static extern void gst_cd_ripper_cancel(HandleRef ripper);
[DllImport("libbanshee")]
private static extern void gst_cd_ripper_set_error_callback(
HandleRef ripper, GstCdRipperErrorCallback cb);
[DllImport("libbanshee")]
private static extern void gst_cd_ripper_set_finished_callback(
HandleRef ripper, GstCdRipperFinishedCallback cb);
}
public class AudioCdRipper
{
private Queue tracks = new Queue();
private AudioCdTrackRipper ripper;
private string device;
private int currentIndex = 0;
private int overallProgress = 0;
private string status;
private int total_tracks;
// speed calculations
private int currentSeconds = 0;
private int lastPollSeconds = 0;
private uint pollDelay = 1000;
private long totalCount;
private uint timeout_id;
private int current = 1;
private Profile profile;
public event HaveTrackInfoHandler HaveTrackInfo;
public event EventHandler Finished;
private ActiveUserEvent user_event;
[DllImport("libc")]
private static extern int ioctl(int device, IoctlOperation request, bool lockdoor);
private enum IoctlOperation {
LockDoor = 0x5329
}
private static bool LockDrive(string device, bool lockdoor)
{
using(UnixStream stream = (new UnixFileInfo(device)).Open(
Mono.Unix.Native.OpenFlags.O_RDONLY |
Mono.Unix.Native.OpenFlags.O_NONBLOCK)) {
return ioctl(stream.Handle, IoctlOperation.LockDoor, lockdoor) == 0;
}
}
private void LockDrive()
{
lock(this) {
if(!LockDrive(device, true)) {
LogCore.Instance.PushWarning("Could not lock CD-ROM drive", device, false);
}
}
}
private void UnlockDrive()
{
lock(this) {
if(!LockDrive(device, false)) {
LogCore.Instance.PushWarning("Could not unlock CD-ROM drive", device, false);
}
}
}
public AudioCdRipper()
{
user_event = new ActiveUserEvent(Catalog.GetString("Importing CD"));
user_event.Icon = IconThemeUtils.LoadIcon(ConfigureDefines.ICON_THEME_DIR+@"\cd-action-rip-24.png");
user_event.CancelRequested += OnCancelRequested;
}
public void QueueTrack(AudioCdTrackInfo track)
{
if(user_event.CancelMessage == null) {
user_event.CancelMessage = String.Format(Catalog.GetString(
"<i>{0}</i> is still being imported into the music library. Would you like to stop it?"
), track.Album);
}
if(device == null) {
device = track.Device;
} else if(device != track.Device) {
throw new ApplicationException(String.Format(Catalog.GetString(
"The device node '{0}' differs from the device node " +
"already set for previously queued tracks ({1})"),
track.Device, device));
}
tracks.Enqueue(track);
totalCount += (int)track.Duration.TotalSeconds;
}
public void Start()
{
current = 1;
user_event.Header = Catalog.GetString("Importing Audio CD");
user_event.Message = Catalog.GetString("Initializing Drive");
profile = Globals.AudioProfileManager.GetConfiguredActiveProfile("cd-importing",
new string [] { "audio/ogg", "audio/mp3", "audio/wav" });
try {
if(profile == null) {
throw new ApplicationException(Catalog.GetString("No encoder was found on your system."));
}
string encodePipeline = profile.Pipeline.GetProcessById("gstreamer");
LogCore.Instance.PushDebug("Ripping CD and Encoding with Pipeline", encodePipeline);
LockDrive();
int paranoiaMode = 0;
try {
if (ImportSchema.AudioCDErrorCorrection.Get()) {
paranoiaMode = 255;
LogCore.Instance.PushDebug("CD Error-correction enabled", "using full paranoia mode (255)");
}
} catch(Exception e){
Console.WriteLine(e);
}
ripper = new AudioCdTrackRipper(device, paranoiaMode, encodePipeline);
ripper.Progress += OnRipperProgress;
ripper.TrackFinished += OnTrackRipped;
ripper.Error += OnRipperError;
//timeout_id = GLib.Timeout.Add(pollDelay, OnTimeout);
total_tracks = tracks.Count;
RipNextTrack();
} catch(Exception e) {
LogCore.Instance.PushError(Catalog.GetString("Cannot Import CD"), e.Message);
user_event.Dispose();
OnFinished();
}
}
public void Cancel()
{
user_event.Dispose();
OnFinished();
}
private void RipNextTrack()
{
if(tracks.Count <= 0) {
return;
}
AudioCdTrackInfo track = tracks.Dequeue() as AudioCdTrackInfo;
user_event.Header = String.Format(Catalog.GetString("Importing {0} of {1}"), current++, QueueSize);
status = String.Format("{0} - {1}", track.Artist, track.Title);
user_event.Message = status;
SafeUri uri = new SafeUri(FileNamePattern.BuildFull(track, profile.OutputFileExtension));
ripper.RipTrack(track, track.TrackIndex, uri);
}
private void OnTrackRipped(object o, AudioCdRipperTrackFinishedArgs args)
{
overallProgress += (int)args.Track.Duration.TotalSeconds;
if(!user_event.IsCancelRequested) {
TrackInfo lti;
try {
lti = new LibraryTrackInfo(args.Uri, args.Track);
} catch(ApplicationException) {
lti = Globals.Library.TracksFnKeyed[Library.MakeFilenameKey(args.Uri)] as TrackInfo;
}
if(lti != null) {
HaveTrackInfoHandler handler = HaveTrackInfo;
if(handler != null) {
HaveTrackInfoArgs hargs = new HaveTrackInfoArgs();
hargs.TrackInfo = lti;
handler(this, hargs);
}
}
}
currentIndex++;
if(tracks.Count > 0 && !user_event.IsCancelRequested) {
RipNextTrack();
return;
}
if(timeout_id > 0) {
// GLib.Source.Remove(timeout_id);
}
ripper.Dispose();
user_event.Dispose();
OnFinished();
}
private void OnRipperError(object o, EventArgs args)
{
ripper.Dispose();
user_event.Dispose();
OnFinished();
LogCore.Instance.PushError(Catalog.GetString("Cannot Import CD"), ripper.ErrorMessage);
}
private void OnFinished()
{
UnlockDrive();
EventHandler handler = Finished;
if(handler != null) {
handler(this, new EventArgs());
}
}
private bool OnTimeout()
{
int diff = currentSeconds - lastPollSeconds;
lastPollSeconds = currentSeconds;
if(diff <= 0) {
user_event.Message = status;
return true;
}
user_event.Message = status + String.Format(" ({0}x)", diff);
return true;
}
private void OnRipperProgress(object o, AudioCdRipperProgressArgs args)
{
if(args.SecondsEncoded == 0) {
return;
}
user_event.Progress = (double)(args.SecondsEncoded + overallProgress) / (double)(totalCount);
currentSeconds = args.SecondsEncoded;
}
private void OnCancelRequested(object o, EventArgs args)
{
if(ripper != null) {
ripper.Cancel();
ripper.Dispose();
}
user_event.Dispose();
OnFinished();
}
public int QueueSize {
get {
return total_tracks;
}
}
}
}
| |
// 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.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace System.IO
{
// This abstract base class represents a reader that can read a sequential
// stream of characters. This is not intended for reading bytes -
// there are methods on the Stream class to read bytes.
// A subclass must minimally implement the Peek() and Read() methods.
//
// This class is intended for character input, not bytes.
// There are methods on the Stream class for reading bytes.
[Serializable]
public abstract partial class TextReader : MarshalByRefObject, IDisposable
{
public static readonly TextReader Null = new NullTextReader();
protected TextReader() { }
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
// Returns the next available character without actually reading it from
// the input stream. The current position of the TextReader is not changed by
// this operation. The returned value is -1 if no further characters are
// available.
//
// This default method simply returns -1.
//
[Pure]
public virtual int Peek()
{
return -1;
}
// Reads the next character from the input stream. The returned value is
// -1 if no further characters are available.
//
// This default method simply returns -1.
//
public virtual int Read()
{
return -1;
}
// Reads a block of characters. This method will read up to
// count characters from this TextReader into the
// buffer character array starting at position
// index. Returns the actual number of characters read.
//
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
int n = 0;
do
{
int ch = Read();
if (ch == -1)
{
break;
}
buffer[index + n++] = (char)ch;
} while (n < count);
return n;
}
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = Read(chars, 0, chars.Length)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
// Blocking version of read. Returns only when count
// characters have been read or the end of the file was reached.
//
public virtual int ReadBlock(char[] buffer, int index, int count)
{
int i, n = 0;
do
{
n += (i = Read(buffer, index + n, count - n));
} while (i > 0 && n < count);
return n;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the input stream has been reached.
//
public virtual string ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1) break;
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
Read();
}
return sb.ToString();
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
#region Task based Async APIs
public virtual Task<string> ReadLineAsync()
{
return Task<String>.Factory.StartNew(state =>
{
return ((TextReader)state).ReadLine();
},
this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public async virtual Task<string> ReadToEndAsync()
{
char[] chars = new char[4096];
int len;
StringBuilder sb = new StringBuilder(4096);
while ((len = await ReadAsyncInternal(chars, 0, chars.Length).ConfigureAwait(false)) != 0)
{
sb.Append(chars, 0, len);
}
return sb.ToString();
}
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncInternal(buffer, index, count);
}
internal virtual Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - index >= count);
var tuple = new Tuple<TextReader, char[], int, int>(this, buffer, index, count);
return Task<int>.Factory.StartNew(state =>
{
var t = (Tuple<TextReader, char[], int, int>)state;
return t.Item1.Read(t.Item2, t.Item3, t.Item4);
},
tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index): nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadBlockAsyncInternal(buffer, index, count);
}
private async Task<int> ReadBlockAsyncInternal(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length - index >= count);
int i, n = 0;
do
{
i = await ReadAsyncInternal(buffer, index + n, count - n).ConfigureAwait(false);
n += i;
} while (i > 0 && n < count);
return n;
}
#endregion
[Serializable]
private sealed class NullTextReader : TextReader
{
public NullTextReader() { }
public override int Read(char[] buffer, int index, int count)
{
return 0;
}
public override string ReadLine()
{
return null;
}
}
public static TextReader Synchronized(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
return reader is SyncTextReader ? reader : new SyncTextReader(reader);
}
[Serializable]
internal sealed class SyncTextReader : TextReader
{
internal readonly TextReader _in;
internal SyncTextReader(TextReader t)
{
_in = t;
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override void Close() => _in.Close();
[MethodImpl(MethodImplOptions.Synchronized)]
protected override void Dispose(bool disposing)
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_in).Dispose();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Peek() => _in.Peek();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read() => _in.Read();
[MethodImpl(MethodImplOptions.Synchronized)]
public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadLine() => _in.ReadLine();
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ReadToEnd() => _in.ReadToEnd();
//
// On SyncTextReader all APIs should run synchronously, even the async ones.
//
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadLineAsync() => Task.FromResult(ReadLine());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd());
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(ReadBlock(buffer, index, count));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
return Task.FromResult(Read(buffer, index, count));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using Robust.Shared.Utility;
namespace Content.Benchmarks
{
[SimpleJob]
public sealed class ComponentFetchBenchmark
{
[Params(5000)] public int NEnt { get; set; }
private readonly Dictionary<(EntityUid, Type), BComponent>
_componentsFlat = new();
private readonly Dictionary<Type, Dictionary<EntityUid, BComponent>> _componentsPart =
new();
private UniqueIndex<Type, BComponent> _allComponents = new();
private readonly List<EntityUid> _lookupEntities = new();
[GlobalSetup]
public void Setup()
{
var random = new Random();
_componentsPart[typeof(BComponent1)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponent2)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponent3)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponent4)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponentLookup)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponent6)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponent7)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponent8)] = new Dictionary<EntityUid, BComponent>();
_componentsPart[typeof(BComponent9)] = new Dictionary<EntityUid, BComponent>();
for (var i = 0u; i < NEnt; i++)
{
var eId = new EntityUid(i);
if (random.Next(1) == 0)
{
_lookupEntities.Add(eId);
}
var comps = new List<BComponent>
{
new BComponent1(),
new BComponent2(),
new BComponent3(),
new BComponent4(),
new BComponent6(),
new BComponent7(),
new BComponent8(),
new BComponent9(),
};
if (random.Next(1000) == 0)
{
comps.Add(new BComponentLookup());
}
foreach (var comp in comps)
{
comp.Uid = eId;
var type = comp.GetType();
_componentsPart[type][eId] = comp;
_componentsFlat[(eId, type)] = comp;
_allComponents.Add(type, comp);
}
}
}
// These two benchmarks are find "needles in haystack" components.
// We try to look up a component that 0.1% of entities have on 1% of entities.
// Examples of this in the engine are VisibilityComponent lookups during PVS.
[Benchmark]
public void FindPart()
{
foreach (var entityUid in _lookupEntities)
{
var d = _componentsPart[typeof(BComponentLookup)];
d.TryGetValue(entityUid, out _);
}
}
[Benchmark]
public void FindFlat()
{
foreach (var entityUid in _lookupEntities)
{
_componentsFlat.TryGetValue((entityUid, typeof(BComponentLookup)), out _);
}
}
// Iteration benchmarks:
// We try to iterate every instance of a single component (BComponent1) and see which is faster.
[Benchmark]
public void IterPart()
{
var list = _componentsPart[typeof(BComponent1)];
var arr = new BComponent[list.Count];
var i = 0;
foreach (var c in list.Values)
{
arr[i++] = c;
}
}
[Benchmark]
public void IterFlat()
{
var list = _allComponents[typeof(BComponent1)];
var arr = new BComponent[list.Count];
var i = 0;
foreach (var c in list)
{
arr[i++] = c;
}
}
// We do the same as the iteration benchmarks but re-fetch the component every iteration.
// This is what entity systems mostly do via entity queries because crappy code.
[Benchmark]
public void IterFetchPart()
{
var list = _componentsPart[typeof(BComponent1)];
var arr = new BComponent[list.Count];
var i = 0;
foreach (var c in list.Values)
{
var eId = c.Uid;
var d = _componentsPart[typeof(BComponent1)];
arr[i++] = d[eId];
}
}
[Benchmark]
public void IterFetchFlat()
{
var list = _allComponents[typeof(BComponent1)];
var arr = new BComponent[list.Count];
var i = 0;
foreach (var c in list)
{
var eId = c.Uid;
arr[i++] = _componentsFlat[(eId, typeof(BComponent1))];
}
}
// Same as the previous benchmarks but with BComponentLookup instead.
// Which is only on 1% of entities.
[Benchmark]
public void IterFetchPartRare()
{
var list = _componentsPart[typeof(BComponentLookup)];
var arr = new BComponent[list.Count];
var i = 0;
foreach (var c in list.Values)
{
var eId = c.Uid;
var d = _componentsPart[typeof(BComponentLookup)];
arr[i++] = d[eId];
}
}
[Benchmark]
public void IterFetchFlatRare()
{
var list = _allComponents[typeof(BComponentLookup)];
var arr = new BComponent[list.Count];
var i = 0;
foreach (var c in list)
{
var eId = c.Uid;
arr[i++] = _componentsFlat[(eId, typeof(BComponentLookup))];
}
}
private readonly struct EntityUid : IEquatable<EntityUid>
{
public readonly uint Value;
public EntityUid(uint value)
{
Value = value;
}
public bool Equals(EntityUid other)
{
return Value == other.Value;
}
public override bool Equals(object obj)
{
return obj is EntityUid other && Equals(other);
}
public override int GetHashCode()
{
return (int) Value;
}
public static bool operator ==(EntityUid left, EntityUid right)
{
return left.Equals(right);
}
public static bool operator !=(EntityUid left, EntityUid right)
{
return !left.Equals(right);
}
}
private abstract class BComponent
{
public EntityUid Uid;
}
private sealed class BComponent1 : BComponent
{
}
private sealed class BComponent2 : BComponent
{
}
private sealed class BComponent3 : BComponent
{
}
private sealed class BComponent4 : BComponent
{
}
private sealed class BComponentLookup : BComponent
{
}
private sealed class BComponent6 : BComponent
{
}
private sealed class BComponent7 : BComponent
{
}
private sealed class BComponent8 : BComponent
{
}
private sealed class BComponent9 : BComponent
{
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// Containing all information originated from
/// the parameters of <see cref="NewCimInstanceCommand"/>
/// </summary>
internal class CimNewCimInstanceContext : XOperationContextBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="methodName"></param>
/// <param name="propertyName"></param>
/// <param name="qualifierName"></param>
internal CimNewCimInstanceContext(
CimSessionProxy theProxy,
string theNamespace)
{
this.proxy = theProxy;
this.nameSpace = theNamespace;
}
}
/// <summary>
/// <para>
/// Implements operations of new-ciminstance cmdlet.
/// </para>
/// </summary>
internal sealed class CimNewCimInstance : CimAsyncOperation
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
public CimNewCimInstance()
: base()
{
}
/// <summary>
/// <para>
/// Base on parametersetName to create ciminstances,
/// either remotely or locally
/// </para>
/// </summary>
/// <param name="cmdlet"><see cref="GetCimInstanceCommand"/> object.</param>
public void NewCimInstance(NewCimInstanceCommand cmdlet)
{
DebugHelper.WriteLogEx();
string nameSpace;
CimInstance cimInstance = null;
try
{
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.ClassNameSessionSet:
{
nameSpace = ConstValue.GetNamespace(cmdlet.Namespace);
cimInstance = CreateCimInstance(cmdlet.ClassName,
nameSpace,
cmdlet.Key,
cmdlet.Property,
cmdlet);
}
break;
case CimBaseCommand.ResourceUriSessionSet:
case CimBaseCommand.ResourceUriComputerSet:
{
nameSpace = cmdlet.Namespace; // passing null is ok for resourceUri set
cimInstance = CreateCimInstance("DummyClass",
nameSpace,
cmdlet.Key,
cmdlet.Property,
cmdlet);
}
break;
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.CimClassSessionSet:
{
nameSpace = ConstValue.GetNamespace(cmdlet.CimClass.CimSystemProperties.Namespace);
cimInstance = CreateCimInstance(cmdlet.CimClass,
cmdlet.Property,
cmdlet);
}
break;
default:
return;
}
}
catch (ArgumentNullException e)
{
cmdlet.ThrowTerminatingError(e, action);
return;
}
catch (ArgumentException e)
{
cmdlet.ThrowTerminatingError(e, action);
return;
}
// return if create client only ciminstance
if (cmdlet.ClientOnly)
{
cmdlet.CmdletOperation.WriteObject(cimInstance, null);
return;
}
string target = cimInstance.ToString();
if (!cmdlet.ShouldProcess(target, action))
{
return;
}
// create ciminstance on server
List<CimSessionProxy> proxys = new List<CimSessionProxy>();
switch (cmdlet.ParameterSetName)
{
case CimBaseCommand.ClassNameComputerSet:
case CimBaseCommand.CimClassComputerSet:
case CimBaseCommand.ResourceUriComputerSet:
{
IEnumerable<string> computerNames = ConstValue.GetComputerNames(
cmdlet.ComputerName);
foreach (string computerName in computerNames)
{
proxys.Add(CreateSessionProxy(computerName, cmdlet));
}
}
break;
case CimBaseCommand.CimClassSessionSet:
case CimBaseCommand.ClassNameSessionSet:
case CimBaseCommand.ResourceUriSessionSet:
foreach (CimSession session in cmdlet.CimSession)
{
proxys.Add(CreateSessionProxy(session, cmdlet));
}
break;
}
foreach (CimSessionProxy proxy in proxys)
{
proxy.ContextObject = new CimNewCimInstanceContext(proxy, nameSpace);
proxy.CreateInstanceAsync(nameSpace, cimInstance);
}
}
#region Get CimInstance after creation (on server)
/// <summary>
/// <para>
/// Get full <see cref="CimInstance"/> from server based on the key
/// </para>
/// </summary>
/// <param name="cimInstance"></param>
internal void GetCimInstance(CimInstance cimInstance, XOperationContextBase context)
{
DebugHelper.WriteLogEx();
CimNewCimInstanceContext newCimInstanceContext = context as CimNewCimInstanceContext;
if (newCimInstanceContext == null)
{
DebugHelper.WriteLog("Invalid (null) CimNewCimInstanceContext", 1);
return;
}
CimSessionProxy proxy = CreateCimSessionProxy(newCimInstanceContext.Proxy);
string nameSpace = (cimInstance.CimSystemProperties.Namespace == null) ? newCimInstanceContext.Namespace : cimInstance.CimSystemProperties.Namespace;
proxy.GetInstanceAsync(nameSpace, cimInstance);
}
#endregion
#region private methods
/// <summary>
/// <para>
/// Set <see cref="CimSessionProxy"/> properties
/// </para>
/// </summary>
/// <param name="proxy"></param>
/// <param name="cmdlet"></param>
private void SetSessionProxyProperties(
ref CimSessionProxy proxy,
NewCimInstanceCommand cmdlet)
{
proxy.OperationTimeout = cmdlet.OperationTimeoutSec;
if(cmdlet.ResourceUri != null)
{
proxy.ResourceUri = cmdlet.ResourceUri;
}
}
/// <summary>
/// <para>
/// Create <see cref="CimSessionProxy"/> and set properties
/// </para>
/// </summary>
/// <param name="computerName"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
string computerName,
NewCimInstanceCommand cmdlet)
{
CimSessionProxy proxy = new CimSessionProxyNewCimInstance(computerName, this);
this.SubscribeEventAndAddProxytoCache(proxy);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> and set properties.
/// </summary>
/// <param name="session"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
private CimSessionProxy CreateSessionProxy(
CimSession session,
NewCimInstanceCommand cmdlet)
{
CimSessionProxy proxy = new CimSessionProxyNewCimInstance(session, this);
this.SubscribeEventAndAddProxytoCache(proxy);
SetSessionProxyProperties(ref proxy, cmdlet);
return proxy;
}
/// <summary>
/// <para>
/// Create <see cref="CimInstance"/> with given properties.
/// </para>
/// </summary>
/// <param name="className"></param>
/// <param name="key"></param>
/// <param name="properties"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">See CimProperty.Create.</exception>
/// <exception cref="ArgumentException">CimProperty.Create.</exception>
private CimInstance CreateCimInstance(
string className,
string cimNamespace,
IEnumerable<string> key,
IDictionary properties,
NewCimInstanceCommand cmdlet)
{
CimInstance cimInstance = new CimInstance(className,cimNamespace);
if (properties == null)
{
return cimInstance;
}
List<string> keys = new List<string>();
if (key != null)
{
foreach (string keyName in key)
{
keys.Add(keyName);
}
}
IDictionaryEnumerator enumerator = properties.GetEnumerator();
while (enumerator.MoveNext())
{
CimFlags flag = CimFlags.None;
string propertyName = enumerator.Key.ToString().Trim();
if (keys.Contains(propertyName, StringComparer.OrdinalIgnoreCase))
{
flag = CimFlags.Key;
}
object propertyValue = GetBaseObject(enumerator.Value);
DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag);
PSReference cimReference = propertyValue as PSReference;
if( cimReference != null )
{
CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag);
cimInstance.CimInstanceProperties.Add(newProperty);
}
else
{
CimProperty newProperty = CimProperty.Create(
propertyName,
propertyValue,
flag);
cimInstance.CimInstanceProperties.Add(newProperty);
}
}
return cimInstance;
}
/// <summary>
/// <para>
/// Create <see cref="CimInstance"/> with given properties.
/// </para>
/// </summary>
/// <param name="cimClass"></param>
/// <param name="properties"></param>
/// <param name="cmdlet"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">See CimProperty.Create.</exception>
/// <exception cref="ArgumentException">CimProperty.Create.</exception>
private CimInstance CreateCimInstance(
CimClass cimClass,
IDictionary properties,
NewCimInstanceCommand cmdlet)
{
CimInstance cimInstance = new CimInstance(cimClass);
if (properties == null)
{
return cimInstance;
}
List<string> notfoundProperties = new List<string>();
foreach (string property in properties.Keys)
{
if (cimInstance.CimInstanceProperties[property] == null)
{
notfoundProperties.Add(property);
cmdlet.ThrowInvalidProperty(notfoundProperties, cmdlet.CimClass.CimSystemProperties.ClassName, @"Property", action, properties);
return null;
}
object propertyValue = GetBaseObject(properties[property]);
cimInstance.CimInstanceProperties[property].Value = propertyValue;
}
return cimInstance;
}
#endregion
#region const strings
/// <summary>
/// Action.
/// </summary>
private const string action = @"New-CimInstance";
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Test class using UnitTestDriver that ensures all the public ctor of Task, Future and
// promise are properly working
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using Xunit;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public sealed class TaskCreateTests
{
#region Test Methods
[Fact]
public static void TaskCreateTest0()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest1()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest2()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest3()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest4()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest5()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.InvalidTaskOption,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest6()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullAction,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest7()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullTaskManager,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest8()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest9()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest10()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest11()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest12()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest13()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest14()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest15()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest16()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest17()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest18()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest19()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest20()
{
TestParameters parameters = new TestParameters(TaskType.FutureT)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest21()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.InvalidTaskOption,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest22()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullAction,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest23()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullTaskManager,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest24()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest25()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest26()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest27()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest28()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest29()
{
TestParameters parameters = new TestParameters(TaskType.Future)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest30()
{
TestParameters parameters = new TestParameters(TaskType.Promise)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest31()
{
TestParameters parameters = new TestParameters(TaskType.Promise)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest32()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest33()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest34()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest35()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest36()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.CreateTask();
}
[Fact]
public static void TaskCreateTest37()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.InvalidTaskOption,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest38()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.MultipleTaskStart,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest39()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullAction,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest40()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.NullTaskManager,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest41()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.StartOnContinueWith,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest42()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.StartOnPromise,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.ExceptionTests();
}
[Fact]
public static void TaskCreateTest43()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest44()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest45()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest46()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest47()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest48()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartNewTask();
}
[Fact]
public static void TaskCreateTest49()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest50()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = false,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest51()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = false,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest52()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = false,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest53()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = false,
HasActionState = true,
HasTaskManager = false,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
[Fact]
public static void TaskCreateTest54()
{
TestParameters parameters = new TestParameters(TaskType.Task)
{
HasCancellationToken = true,
HasActionState = true,
HasTaskManager = true,
HasTaskOption = true,
ExceptionTestsAction = ExceptionTestsAction.None,
};
TaskCreateTest test = new TaskCreateTest(parameters);
test.StartTask();
}
#endregion
internal class TestParameters
{
internal readonly TaskType TaskType;
internal bool HasTaskManager;
internal bool HasActionState;
internal bool HasTaskOption;
internal bool HasCancellationToken;
internal ExceptionTestsAction ExceptionTestsAction;
internal TestParameters(TaskType taskType)
{
TaskType = taskType;
}
}
/// <summary>
/// Class that verifies that all the public constructors of Task, future, promise and futureT are working correctly
/// The test creates the test object (Task, Future, promise) using various ctor and ensures that they were
/// created and can be started. All the negative cases (expectional cases are also covered in this test set).
/// </summary>
internal sealed class TaskCreateTest
{
#region Member Variables
//Bunch of constants that is used to simulate work done by TPL Task (does some funky maths
// (1 + 1/(2*2) + 1/(3*3) + ... + 1/(1000000*1000000) and verifies that the result is
//equals to Math.Pow (Math.PI, 2) / 6) aka not important from TPL test perspective
private const int ZETA_SEED = 1000000;
/// <summary>
/// Used to save the results that is returned by the Task upon completion (used to verify that task ran successsfully)
/// </summary>
private double _result;
/// <summary>
/// Used to store the Task that is under test. initialized using method CreateTaskHelper()
/// </summary>
private Task _task;
/// <summary>
/// Used to differentiate what type of task to test
/// </summary>
private readonly TaskType _taskType = TaskType.Task;
private readonly bool _hasTaskManager;
private readonly bool _hasActionState;
private readonly bool _hasCancellationToken;
private readonly bool _hasTaskOption;
private readonly ExceptionTestsAction _exceptionTestsAction;
/// <summary>
/// Need a cancellationTokenSource to test the APIs that accept a cancellationTokens
/// </summary>
private CancellationTokenSource _cts;
#endregion
#region Constructor
public TaskCreateTest(TestParameters parameters)
{
_taskType = parameters.TaskType;
_hasTaskManager = parameters.HasTaskManager;
_hasActionState = parameters.HasActionState;
_hasTaskOption = parameters.HasTaskOption;
_hasCancellationToken = parameters.HasCancellationToken;
_exceptionTestsAction = parameters.ExceptionTestsAction;
}
#endregion
#region Test Methods (These are the ones that are actually invoked)
/// <summary>
/// Test that creates a Task, Future and Promise using various Ctor and ensures that the task was created successfully
/// </summary>
/// <returns>indicates whether test passed or failed (invoking ctor was success or not)</returns>
internal void CreateTask()
{
//Using the parameters specified in the XML input file create a Task, Future or promise
_task = CreateTaskHelper();
// Checks whether the task was created, initialized with specified action
Assert.NotNull(_task);
// If token was set on the Task, we should be able to cancel the Task
if (_cts != null)
{
_cts.Cancel();
if (!_task.IsCanceled || _task.Status != TaskStatus.Canceled)
Assert.True(false, string.Format("Task Token doesn't matched TokenSource's Token"));
}
}
/// <summary>
/// Tests to ensure that TaskTypes can be created, started and they run to completion successfully
/// </summary>
/// <returns></returns>
internal void StartTask()
{
// It is not allowed to Start Task multiple times, so this test will not try to do that
// instead it is part of exception testing
Debug.WriteLine("Testing Start() on Task, HasTaskManager={0}", _hasTaskManager);
_task = CreateTaskHelper();
if (_hasTaskManager)
_task.Start(TaskScheduler.Default);
else
_task.Start();
_task.Wait();
// Verification
CheckResult();
}
/// <summary>
/// Tests to ensure that TaskTypes can be created using the StartNew static TaskFactory method
/// </summary>
/// <returns></returns>
internal void StartNewTask()
{
CancellationTokenSource cts = new CancellationTokenSource();
Debug.WriteLine("Start new Task, HasActionState={0}, HasTaskOption={1}, HasTaskManager={2}, TaskType={3}, HasCancellationToken={4}",
_hasActionState, _hasTaskOption, _hasTaskManager, _taskType, _hasCancellationToken);
if (!_hasActionState)
{
if (_hasTaskManager && _hasTaskOption && _hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWork, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, TaskCreationOptions.None);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWork, TaskCreationOptions.None);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork, TaskCreationOptions.None);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, cts.Token);
break;
case TaskType.FutureT:
_task = (Task<double>)Task<double>.Factory.StartNew(FutureWork, cts.Token);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork, cts.Token);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work);
break;
case TaskType.FutureT:
_task = (Task<double>)Task<double>.Factory.StartNew(FutureWork);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWork);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
}
else
{
if (_hasTaskManager && _hasTaskOption && _hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(WorkWithState, ZETA_SEED, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED, cts.Token, TaskCreationOptions.None, TaskScheduler.Default);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(WorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(Work, cts.Token);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED, cts.Token);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED, cts.Token);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
_task = Task.Factory.StartNew(WorkWithState, ZETA_SEED);
break;
case TaskType.FutureT:
_task = Task<double>.Factory.StartNew(FutureWorkWithState, ZETA_SEED);
break;
case TaskType.Future:
_task = Task.Factory.StartNew<double>(FutureWorkWithState, ZETA_SEED);
break;
default:
throw new NotSupportedException("DOes not support this type: " + _taskType);
}
}
}
_task.Wait();
CheckResult();
}
/// <summary>
/// Test to ensure that exceptions are thrown for invalid ctor parameters
/// </summary>
/// <returns></returns>
internal void ExceptionTests()
{
switch (_exceptionTestsAction)
{
case ExceptionTestsAction.NullAction:
Debug.WriteLine("Test passing null Action/Func to Constructor and StartNew() of {0}", _taskType);
if (_taskType != TaskType.Promise)
{
//
// For Constructor
//
if (_taskType != TaskType.Future)
{
try
{
if (_taskType == TaskType.Task)
_task = new Task(null);
else if (_taskType == TaskType.FutureT)
_task = new Task<double>(null);
Assert.True(false, string.Format("Able to pass null Action/Func to Constructor of {0}, when expecting exception", _taskType));
}
catch (ArgumentNullException)
{
Debug.WriteLine("Exception throws as expected when trying to pass null Action/Func to Constructor of {0}", _taskType);
}
}
//
// For StartNew
//
try
{
Action o = null;
Func<double> o2 = null;
if (_taskType == TaskType.Task)
_task = Task.Factory.StartNew(o);
else if (_taskType == TaskType.FutureT)
_task = Task<double>.Factory.StartNew(o2);
else if (_taskType == TaskType.Future)
_task = Task.Factory.StartNew<double>(o2);
Assert.True(false, string.Format("Able to pass null Action/Func to StartNew() of {0}, when expecting exception", _taskType));
}
catch (ArgumentNullException)
{
Debug.WriteLine("Exception throws as expected when trying to pass null Action/Func to StartNew() of {0}", _taskType);
}
}
break;
case ExceptionTestsAction.InvalidTaskOption:
int invalidOption = 9999; //Used to create Invalid TaskCreationOption
Debug.WriteLine("Test passing invalid TaskCreationOptions {0} to Constructor and StartNew() of {1}", invalidOption, _taskType);
if (_taskType != TaskType.Promise)
{
//
// For Constructor
//
if (_taskType != TaskType.Future)
{
try
{
if (_taskType == TaskType.Task)
_task = new Task(Work, (TaskCreationOptions)invalidOption);
else if (_taskType == TaskType.FutureT)
_task = new Task<double>(FutureWork, (TaskCreationOptions)invalidOption);
Assert.True(false, string.Format("Able to pass invalid TaskCreationOptions to Constructor of {0}, when expecting exception", _taskType));
}
catch (ArgumentOutOfRangeException)
{
Debug.WriteLine("Exception throws as expected when trying to pass invalid TaskCreationOptions to Constructor of {0}", _taskType);
}
}
//
// For StartNew
//
try
{
if (_taskType == TaskType.Task)
_task = Task.Factory.StartNew(Work, (TaskCreationOptions)invalidOption);
else if (_taskType == TaskType.FutureT)
_task = Task<double>.Factory.StartNew(FutureWork, (TaskCreationOptions)invalidOption);
else if (_taskType == TaskType.Future)
_task = Task.Factory.StartNew<double>(FutureWork, (TaskCreationOptions)invalidOption);
Assert.True(false, string.Format("Able to pass invalid TaskCreationOptions to StartNew() of {0}, when expecting exception", _taskType));
}
catch (ArgumentOutOfRangeException)
{
Debug.WriteLine("Exception throws as expected when trying to pass invalid TaskCreationOptions to StartNew() of {0}", _taskType);
}
}
break;
case ExceptionTestsAction.NullTaskManager:
Debug.WriteLine("Test passing null TaskManager to Start() and StartNew() on {0}", _taskType);
TMExceptionTestHelper(null, "null");
break;
case ExceptionTestsAction.MultipleTaskStart:
Debug.WriteLine("Testing multiple Start() on {0}", _taskType);
try
{
_task = CreateTaskHelper();
_task.Start();
_task.Start();
Assert.True(false, string.Format("Able to Start {0} multiple times, when expecting exception", _taskType));
}
catch (InvalidOperationException)
{
Debug.WriteLine("Exception throws as expected when trying to Start {0} multiple times", _taskType);
}
break;
case ExceptionTestsAction.StartOnPromise:
Debug.WriteLine("Testing Start() on Promise");
try
{
TaskCompletionSource<double> f = new TaskCompletionSource<double>();
f.Task.Start();
Assert.True(false, string.Format("Able to Start a Promise, when expecting exception"));
}
catch (System.InvalidOperationException)
{
Debug.WriteLine("Exception throws as expected when trying to Start a Promise");
}
break;
case ExceptionTestsAction.StartOnContinueWith:
Debug.WriteLine("Testing Start() on ContinueWith Task");
try
{
Task t = CreateTaskHelper().ContinueWith(delegate { Work(); });
t.Start();
Assert.True(false, string.Format("Able to start task manually on ContinueWith Task, when expecting exception"));
}
catch (InvalidOperationException)
{
Debug.WriteLine("Exception throws as expected when trying to start ContinueWith Task manually");
}
break;
default:
Assert.True(false, string.Format("Invalid Exception Test Action given, {0}", _exceptionTestsAction));
break;
}
}
#endregion
#region Helper Methods
private void TMExceptionTestHelper(TaskScheduler tm, string tmInvalidMessage)
{
if (_taskType != TaskType.Promise)
{
//
// For Start()
//
if (_taskType != TaskType.Future)
{
try
{
_task = CreateTaskHelper();
_task.Start(tm);
Assert.True(false, string.Format("Able to pass {0} TaskManager to Start() on {1}, when expecting exception", tmInvalidMessage, _taskType));
}
catch (ArgumentNullException)
{
if (tmInvalidMessage.Equals("null", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception ArgumentNullException throws as expected when trying to pass {0} TaskManager to Start() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
catch (InvalidOperationException)
{
if (tmInvalidMessage.Equals("disposed", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception InvalidOperationException throws as expected when trying to pass {0} TaskManager to Start() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
}
//
// For StartNew()
//
try
{
CancellationToken token = new CancellationToken();
if (_taskType == TaskType.Task)
_task = Task.Factory.StartNew(Work, token, TaskCreationOptions.None, tm);
else if (_taskType == TaskType.FutureT)
_task = Task<double>.Factory.StartNew(FutureWork, token, TaskCreationOptions.None, tm);
else if (_taskType == TaskType.Future)
_task = Task.Factory.StartNew<double>(FutureWork, token, TaskCreationOptions.None, tm);
Assert.True(false, string.Format("Able to pass {0} TaskManager to StartNew() on {1}, when expecting exception", tmInvalidMessage, _taskType));
}
catch (ArgumentNullException)
{
if (tmInvalidMessage.Equals("null", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception ArgumentNullException throws as expected when trying to pass {0} TaskManager to StartNew() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
catch (InvalidOperationException)
{
if (tmInvalidMessage.Equals("disposed", StringComparison.OrdinalIgnoreCase))
Debug.WriteLine("Exception InvalidOperationException throws as expected when trying to pass {0} TaskManager to StartNew() on {1}", tmInvalidMessage, _taskType);
else
throw;
}
}
}
/// <summary>
/// Helper function that creates Task/Future based on test parameters
/// </summary>
/// <returns></returns>
private Task CreateTaskHelper()
{
CancellationToken token = CancellationToken.None;
Task newTask;
Debug.WriteLine("Creating Task, HasActionState={0}, HasTaskOption={1}, TaskType={2}", _hasActionState, _hasTaskOption, _taskType);
if (_taskType == TaskType.Promise)
{
if (_hasTaskOption && _hasActionState)
newTask = (new TaskCompletionSource<double>(new object(), TaskCreationOptions.None)).Task;
else if (_hasTaskOption)
newTask = (new TaskCompletionSource<double>(TaskCreationOptions.None)).Task;
else if (_hasActionState)
newTask = (new TaskCompletionSource<double>(new object())).Task;
else
newTask = (new TaskCompletionSource<double>()).Task;
}
else
{
if (!_hasActionState)
{
if (_hasTaskOption && _hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work, token, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork, token, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work, token);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork, token);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(Work);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWork);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
}
else
{
if (_hasTaskOption && _hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED, token, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED, token, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasTaskOption)
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED, TaskCreationOptions.None);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else if (_hasCancellationToken)
{
_cts = new CancellationTokenSource();
token = _cts.Token;
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED, token);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED, token);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
else
{
switch (_taskType)
{
case TaskType.Task:
newTask = new Task(WorkWithState, ZETA_SEED);
break;
case TaskType.FutureT:
newTask = new Task<double>(FutureWorkWithState, ZETA_SEED);
break;
default:
throw new ArgumentException("Cannot create an instance of static type: " + _taskType);
}
}
}
}
return newTask;
}
private void Work()
{
WorkWithState(ZETA_SEED);
}
private void WorkWithState(object o)
{
// There is a rare case when the main thread (that does the assignment of Task to task) is not
//executed before the delegate is invoked. This spinwait guards against such cases
while (_task == null)
{
SpinWait.SpinUntil(() => false, 100);
}
if (TaskScheduler.Current == TaskScheduler.Default
&& _task.CreationOptions == TaskCreationOptions.None)
{
//The Workloads are defined in the common folder
_result = ZetaSequence((int)o);
}
}
private double FutureWork()
{
return FutureWorkWithState(ZETA_SEED);
}
private double FutureWorkWithState(object o)
{
// Waiting until the task is assigned on StartNew scenario
while (_task == null)
{
SpinWait.SpinUntil(() => false, 100);
}
if (TaskScheduler.Current == TaskScheduler.Default
&& _task.CreationOptions == TaskCreationOptions.None)
{
return ZetaSequence((int)o);
}
else
{
return 0;
}
}
/// <summary>
/// Method used to verify that task was created
/// </summary>
/// <returns></returns>
private bool IsTaskCreated()
{
return _task != null;
}
public static double ZetaSequence(int n)
{
double result = 0;
for (int i = 1; i < n; i++)
{
result += 1.0 / ((double)i * (double)i);
}
return result;
}
/// <summary>
/// Method used to verify that task returns the expected result (which means task ran successfully)
/// </summary>
/// <returns></returns>
private void CheckResult()
{
double actualResult = 0;
switch (_taskType)
{
case TaskType.Task:
actualResult = _result;
break;
case TaskType.FutureT:
case TaskType.Future:
actualResult = ((Task<double>)_task).Result;
break;
default:
throw new NotSupportedException("Mismatch type, " + _taskType + " doesn't have value that can be verified");
}
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
if (actualResult > minLimit && actualResult < maxLimit)
Debug.WriteLine("Result matched");
else
Assert.True(false, string.Format("Result mismatched, expecting to lie between {0} and {1} but got {2}", minLimit, maxLimit, actualResult));
}
#endregion
}
/// <summary>
/// Type of Task types to test for
/// </summary>
internal enum TaskType
{
Task,
Future,
FutureT,
Promise
}
/// <summary>
/// Types of exception test actions to test for
/// </summary>
internal enum ExceptionTestsAction
{
None,
NullAction,
InvalidTaskOption,
NullTaskManager,
MultipleTaskStart,
StartOnPromise,
StartOnContinueWith
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3053
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by wsdl, Version=2.0.50727.42.
//
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.ResultObjects;
namespace WebsitePanel.EnterpriseServer {
using System.Diagnostics;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="esOCSSoap", Namespace="http://tempuri.org/")]
public partial class esOCS : Microsoft.Web.Services3.WebServicesClientProtocol {
private System.Threading.SendOrPostCallback CreateOCSUserOperationCompleted;
private System.Threading.SendOrPostCallback DeleteOCSUserOperationCompleted;
private System.Threading.SendOrPostCallback GetOCSUsersPagedOperationCompleted;
private System.Threading.SendOrPostCallback GetOCSUserCountOperationCompleted;
private System.Threading.SendOrPostCallback GetUserGeneralSettingsOperationCompleted;
private System.Threading.SendOrPostCallback SetUserGeneralSettingsOperationCompleted;
/// <remarks/>
public esOCS() {
this.Url = "http://localhost/WebsitePanelEnterpriseServer/esOCS.asmx";
}
/// <remarks/>
public event CreateOCSUserCompletedEventHandler CreateOCSUserCompleted;
/// <remarks/>
public event DeleteOCSUserCompletedEventHandler DeleteOCSUserCompleted;
/// <remarks/>
public event GetOCSUsersPagedCompletedEventHandler GetOCSUsersPagedCompleted;
/// <remarks/>
public event GetOCSUserCountCompletedEventHandler GetOCSUserCountCompleted;
/// <remarks/>
public event GetUserGeneralSettingsCompletedEventHandler GetUserGeneralSettingsCompleted;
/// <remarks/>
public event SetUserGeneralSettingsCompletedEventHandler SetUserGeneralSettingsCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/CreateOCSUser", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public OCSUserResult CreateOCSUser(int itemId, int accountId) {
object[] results = this.Invoke("CreateOCSUser", new object[] {
itemId,
accountId});
return ((OCSUserResult)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginCreateOCSUser(int itemId, int accountId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("CreateOCSUser", new object[] {
itemId,
accountId}, callback, asyncState);
}
/// <remarks/>
public OCSUserResult EndCreateOCSUser(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((OCSUserResult)(results[0]));
}
/// <remarks/>
public void CreateOCSUserAsync(int itemId, int accountId) {
this.CreateOCSUserAsync(itemId, accountId, null);
}
/// <remarks/>
public void CreateOCSUserAsync(int itemId, int accountId, object userState) {
if ((this.CreateOCSUserOperationCompleted == null)) {
this.CreateOCSUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateOCSUserOperationCompleted);
}
this.InvokeAsync("CreateOCSUser", new object[] {
itemId,
accountId}, this.CreateOCSUserOperationCompleted, userState);
}
private void OnCreateOCSUserOperationCompleted(object arg) {
if ((this.CreateOCSUserCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.CreateOCSUserCompleted(this, new CreateOCSUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/DeleteOCSUser", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public ResultObject DeleteOCSUser(int itemId, string instanceId) {
object[] results = this.Invoke("DeleteOCSUser", new object[] {
itemId,
instanceId});
return ((ResultObject)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginDeleteOCSUser(int itemId, string instanceId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("DeleteOCSUser", new object[] {
itemId,
instanceId}, callback, asyncState);
}
/// <remarks/>
public ResultObject EndDeleteOCSUser(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((ResultObject)(results[0]));
}
/// <remarks/>
public void DeleteOCSUserAsync(int itemId, string instanceId) {
this.DeleteOCSUserAsync(itemId, instanceId, null);
}
/// <remarks/>
public void DeleteOCSUserAsync(int itemId, string instanceId, object userState) {
if ((this.DeleteOCSUserOperationCompleted == null)) {
this.DeleteOCSUserOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteOCSUserOperationCompleted);
}
this.InvokeAsync("DeleteOCSUser", new object[] {
itemId,
instanceId}, this.DeleteOCSUserOperationCompleted, userState);
}
private void OnDeleteOCSUserOperationCompleted(object arg) {
if ((this.DeleteOCSUserCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.DeleteOCSUserCompleted(this, new DeleteOCSUserCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetOCSUsersPaged", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public OCSUsersPagedResult GetOCSUsersPaged(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int maximumRows) {
object[] results = this.Invoke("GetOCSUsersPaged", new object[] {
itemId,
sortColumn,
sortDirection,
name,
email,
startRow,
maximumRows});
return ((OCSUsersPagedResult)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetOCSUsersPaged(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetOCSUsersPaged", new object[] {
itemId,
sortColumn,
sortDirection,
name,
email,
startRow,
maximumRows}, callback, asyncState);
}
/// <remarks/>
public OCSUsersPagedResult EndGetOCSUsersPaged(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((OCSUsersPagedResult)(results[0]));
}
/// <remarks/>
public void GetOCSUsersPagedAsync(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int maximumRows) {
this.GetOCSUsersPagedAsync(itemId, sortColumn, sortDirection, name, email, startRow, maximumRows, null);
}
/// <remarks/>
public void GetOCSUsersPagedAsync(int itemId, string sortColumn, string sortDirection, string name, string email, int startRow, int maximumRows, object userState) {
if ((this.GetOCSUsersPagedOperationCompleted == null)) {
this.GetOCSUsersPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetOCSUsersPagedOperationCompleted);
}
this.InvokeAsync("GetOCSUsersPaged", new object[] {
itemId,
sortColumn,
sortDirection,
name,
email,
startRow,
maximumRows}, this.GetOCSUsersPagedOperationCompleted, userState);
}
private void OnGetOCSUsersPagedOperationCompleted(object arg) {
if ((this.GetOCSUsersPagedCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetOCSUsersPagedCompleted(this, new GetOCSUsersPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetOCSUserCount", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public IntResult GetOCSUserCount(int itemId, string name, string email) {
object[] results = this.Invoke("GetOCSUserCount", new object[] {
itemId,
name,
email});
return ((IntResult)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetOCSUserCount(int itemId, string name, string email, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetOCSUserCount", new object[] {
itemId,
name,
email}, callback, asyncState);
}
/// <remarks/>
public IntResult EndGetOCSUserCount(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((IntResult)(results[0]));
}
/// <remarks/>
public void GetOCSUserCountAsync(int itemId, string name, string email) {
this.GetOCSUserCountAsync(itemId, name, email, null);
}
/// <remarks/>
public void GetOCSUserCountAsync(int itemId, string name, string email, object userState) {
if ((this.GetOCSUserCountOperationCompleted == null)) {
this.GetOCSUserCountOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetOCSUserCountOperationCompleted);
}
this.InvokeAsync("GetOCSUserCount", new object[] {
itemId,
name,
email}, this.GetOCSUserCountOperationCompleted, userState);
}
private void OnGetOCSUserCountOperationCompleted(object arg) {
if ((this.GetOCSUserCountCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetOCSUserCountCompleted(this, new GetOCSUserCountCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetUserGeneralSettings", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public OCSUser GetUserGeneralSettings(int itemId, string instanceId) {
object[] results = this.Invoke("GetUserGeneralSettings", new object[] {
itemId,
instanceId});
return ((OCSUser)(results[0]));
}
/// <remarks/>
public System.IAsyncResult BeginGetUserGeneralSettings(int itemId, string instanceId, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("GetUserGeneralSettings", new object[] {
itemId,
instanceId}, callback, asyncState);
}
/// <remarks/>
public OCSUser EndGetUserGeneralSettings(System.IAsyncResult asyncResult) {
object[] results = this.EndInvoke(asyncResult);
return ((OCSUser)(results[0]));
}
/// <remarks/>
public void GetUserGeneralSettingsAsync(int itemId, string instanceId) {
this.GetUserGeneralSettingsAsync(itemId, instanceId, null);
}
/// <remarks/>
public void GetUserGeneralSettingsAsync(int itemId, string instanceId, object userState) {
if ((this.GetUserGeneralSettingsOperationCompleted == null)) {
this.GetUserGeneralSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetUserGeneralSettingsOperationCompleted);
}
this.InvokeAsync("GetUserGeneralSettings", new object[] {
itemId,
instanceId}, this.GetUserGeneralSettingsOperationCompleted, userState);
}
private void OnGetUserGeneralSettingsOperationCompleted(object arg) {
if ((this.GetUserGeneralSettingsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.GetUserGeneralSettingsCompleted(this, new GetUserGeneralSettingsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/SetUserGeneralSettings", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void SetUserGeneralSettings(int itemId, string instanceId, bool enabledForFederation, bool enabledForPublicIMConnectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence) {
this.Invoke("SetUserGeneralSettings", new object[] {
itemId,
instanceId,
enabledForFederation,
enabledForPublicIMConnectivity,
archiveInternalCommunications,
archiveFederatedCommunications,
enabledForEnhancedPresence});
}
/// <remarks/>
public System.IAsyncResult BeginSetUserGeneralSettings(int itemId, string instanceId, bool enabledForFederation, bool enabledForPublicIMConnectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("SetUserGeneralSettings", new object[] {
itemId,
instanceId,
enabledForFederation,
enabledForPublicIMConnectivity,
archiveInternalCommunications,
archiveFederatedCommunications,
enabledForEnhancedPresence}, callback, asyncState);
}
/// <remarks/>
public void EndSetUserGeneralSettings(System.IAsyncResult asyncResult) {
this.EndInvoke(asyncResult);
}
/// <remarks/>
public void SetUserGeneralSettingsAsync(int itemId, string instanceId, bool enabledForFederation, bool enabledForPublicIMConnectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence) {
this.SetUserGeneralSettingsAsync(itemId, instanceId, enabledForFederation, enabledForPublicIMConnectivity, archiveInternalCommunications, archiveFederatedCommunications, enabledForEnhancedPresence, null);
}
/// <remarks/>
public void SetUserGeneralSettingsAsync(int itemId, string instanceId, bool enabledForFederation, bool enabledForPublicIMConnectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence, object userState) {
if ((this.SetUserGeneralSettingsOperationCompleted == null)) {
this.SetUserGeneralSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetUserGeneralSettingsOperationCompleted);
}
this.InvokeAsync("SetUserGeneralSettings", new object[] {
itemId,
instanceId,
enabledForFederation,
enabledForPublicIMConnectivity,
archiveInternalCommunications,
archiveFederatedCommunications,
enabledForEnhancedPresence}, this.SetUserGeneralSettingsOperationCompleted, userState);
}
private void OnSetUserGeneralSettingsOperationCompleted(object arg) {
if ((this.SetUserGeneralSettingsCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.SetUserGeneralSettingsCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void CreateOCSUserCompletedEventHandler(object sender, CreateOCSUserCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class CreateOCSUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal CreateOCSUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public OCSUserResult Result {
get {
this.RaiseExceptionIfNecessary();
return ((OCSUserResult)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void DeleteOCSUserCompletedEventHandler(object sender, DeleteOCSUserCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class DeleteOCSUserCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal DeleteOCSUserCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public ResultObject Result {
get {
this.RaiseExceptionIfNecessary();
return ((ResultObject)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetOCSUsersPagedCompletedEventHandler(object sender, GetOCSUsersPagedCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetOCSUsersPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetOCSUsersPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public OCSUsersPagedResult Result {
get {
this.RaiseExceptionIfNecessary();
return ((OCSUsersPagedResult)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetOCSUserCountCompletedEventHandler(object sender, GetOCSUserCountCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetOCSUserCountCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetOCSUserCountCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public IntResult Result {
get {
this.RaiseExceptionIfNecessary();
return ((IntResult)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void GetUserGeneralSettingsCompletedEventHandler(object sender, GetUserGeneralSettingsCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class GetUserGeneralSettingsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal GetUserGeneralSettingsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public OCSUser Result {
get {
this.RaiseExceptionIfNecessary();
return ((OCSUser)(this.results[0]));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
public delegate void SetUserGeneralSettingsCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e);
}
| |
// 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.Collections.ObjectModel;
using System.IdentityModel.Policy;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security.Tokens;
using System.Threading.Tasks;
namespace System.ServiceModel.Security
{
// See SecurityProtocolFactory for contracts on subclasses etc
// SecureOutgoingMessage and VerifyIncomingMessage take message as
// ref parameters (instead of taking a message and returning a
// message) to reduce the likelihood that a caller will forget to
// do the rest of the processing with the modified message object.
// Especially, on the sender-side, not sending the modified
// message will result in sending it with an unencrypted body.
// Correspondingly, the async versions have out parameters instead
// of simple return values.
internal abstract class SecurityProtocol : ISecurityCommunicationObject
{
private static ReadOnlyCollection<SupportingTokenProviderSpecification> s_emptyTokenProviders;
private Dictionary<string, Collection<SupportingTokenProviderSpecification>> _mergedSupportingTokenProvidersMap;
private ChannelParameterCollection _channelParameters;
protected SecurityProtocol(SecurityProtocolFactory factory, EndpointAddress target, Uri via)
{
SecurityProtocolFactory = factory;
Target = target;
Via = via;
CommunicationObject = new WrapperSecurityCommunicationObject(this);
}
protected WrapperSecurityCommunicationObject CommunicationObject { get; }
public SecurityProtocolFactory SecurityProtocolFactory { get; }
public EndpointAddress Target { get; }
public Uri Via { get; }
public ICollection<SupportingTokenProviderSpecification> ChannelSupportingTokenProviderSpecification { get; private set; }
public Dictionary<string, ICollection<SupportingTokenProviderSpecification>> ScopedSupportingTokenProviderSpecification { get; private set; }
private static ReadOnlyCollection<SupportingTokenProviderSpecification> EmptyTokenProviders
{
get
{
if (s_emptyTokenProviders == null)
{
s_emptyTokenProviders = new ReadOnlyCollection<SupportingTokenProviderSpecification>(new List<SupportingTokenProviderSpecification>());
}
return s_emptyTokenProviders;
}
}
public ChannelParameterCollection ChannelParameters
{
get
{
return _channelParameters;
}
set
{
CommunicationObject.ThrowIfDisposedOrImmutable();
_channelParameters = value;
}
}
// ISecurityCommunicationObject members
public TimeSpan DefaultOpenTimeout
{
get { return ServiceDefaults.OpenTimeout; }
}
public TimeSpan DefaultCloseTimeout
{
get { return ServiceDefaults.CloseTimeout; }
}
public void OnClosed() { }
public void OnClosing() { }
public void OnFaulted() { }
public void OnOpened() { }
public void OnOpening() { }
internal IList<SupportingTokenProviderSpecification> GetSupportingTokenProviders(string action)
{
if (_mergedSupportingTokenProvidersMap != null && _mergedSupportingTokenProvidersMap.Count > 0)
{
if (action != null && _mergedSupportingTokenProvidersMap.ContainsKey(action))
{
return _mergedSupportingTokenProvidersMap[action];
}
else if (_mergedSupportingTokenProvidersMap.ContainsKey(MessageHeaders.WildcardAction))
{
return _mergedSupportingTokenProvidersMap[MessageHeaders.WildcardAction];
}
}
// return null if the token providers list is empty - this gets a perf benefit since calling Count is expensive for an empty
// ReadOnlyCollection
return (ChannelSupportingTokenProviderSpecification == EmptyTokenProviders) ? null : (IList<SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification;
}
protected InitiatorServiceModelSecurityTokenRequirement CreateInitiatorSecurityTokenRequirement()
{
InitiatorServiceModelSecurityTokenRequirement requirement = new InitiatorServiceModelSecurityTokenRequirement();
requirement.TargetAddress = Target;
requirement.Via = Via;
requirement.SecurityBindingElement = SecurityProtocolFactory.SecurityBindingElement;
requirement.SecurityAlgorithmSuite = SecurityProtocolFactory.OutgoingAlgorithmSuite;
requirement.MessageSecurityVersion = SecurityProtocolFactory.MessageSecurityVersion.SecurityTokenVersion;
if (_channelParameters != null)
{
requirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = _channelParameters;
}
return requirement;
}
private InitiatorServiceModelSecurityTokenRequirement CreateInitiatorSecurityTokenRequirement(SecurityTokenParameters parameters, SecurityTokenAttachmentMode attachmentMode)
{
InitiatorServiceModelSecurityTokenRequirement requirement = CreateInitiatorSecurityTokenRequirement();
parameters.InitializeSecurityTokenRequirement(requirement);
requirement.KeyUsage = SecurityKeyUsage.Signature;
requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Output;
requirement.Properties[ServiceModelSecurityTokenRequirement.SupportingTokenAttachmentModeProperty] = attachmentMode;
return requirement;
}
private void AddSupportingTokenProviders(SupportingTokenParameters supportingTokenParameters, bool isOptional, IList<SupportingTokenProviderSpecification> providerSpecList)
{
for (int i = 0; i < supportingTokenParameters.Endorsing.Count; ++i)
{
SecurityTokenRequirement requirement = CreateInitiatorSecurityTokenRequirement(supportingTokenParameters.Endorsing[i], SecurityTokenAttachmentMode.Endorsing);
try
{
if (isOptional)
{
requirement.IsOptionalToken = true;
}
SecurityTokenProvider provider = SecurityProtocolFactory.SecurityTokenManager.CreateSecurityTokenProvider(requirement);
if (provider == null)
{
continue;
}
SupportingTokenProviderSpecification providerSpec = new SupportingTokenProviderSpecification(provider, SecurityTokenAttachmentMode.Endorsing, supportingTokenParameters.Endorsing[i]);
providerSpecList.Add(providerSpec);
}
catch (Exception e)
{
if (!isOptional || Fx.IsFatal(e))
{
throw;
}
}
}
for (int i = 0; i < supportingTokenParameters.SignedEndorsing.Count; ++i)
{
SecurityTokenRequirement requirement = CreateInitiatorSecurityTokenRequirement(supportingTokenParameters.SignedEndorsing[i], SecurityTokenAttachmentMode.SignedEndorsing);
try
{
if (isOptional)
{
requirement.IsOptionalToken = true;
}
SecurityTokenProvider provider = SecurityProtocolFactory.SecurityTokenManager.CreateSecurityTokenProvider(requirement);
if (provider == null)
{
continue;
}
SupportingTokenProviderSpecification providerSpec = new SupportingTokenProviderSpecification(provider, SecurityTokenAttachmentMode.SignedEndorsing, supportingTokenParameters.SignedEndorsing[i]);
providerSpecList.Add(providerSpec);
}
catch (Exception e)
{
if (!isOptional || Fx.IsFatal(e))
{
throw;
}
}
}
for (int i = 0; i < supportingTokenParameters.SignedEncrypted.Count; ++i)
{
SecurityTokenRequirement requirement = CreateInitiatorSecurityTokenRequirement(supportingTokenParameters.SignedEncrypted[i], SecurityTokenAttachmentMode.SignedEncrypted);
try
{
if (isOptional)
{
requirement.IsOptionalToken = true;
}
SecurityTokenProvider provider = SecurityProtocolFactory.SecurityTokenManager.CreateSecurityTokenProvider(requirement);
if (provider == null)
{
continue;
}
SupportingTokenProviderSpecification providerSpec = new SupportingTokenProviderSpecification(provider, SecurityTokenAttachmentMode.SignedEncrypted, supportingTokenParameters.SignedEncrypted[i]);
providerSpecList.Add(providerSpec);
}
catch (Exception e)
{
if (!isOptional || Fx.IsFatal(e))
{
throw;
}
}
}
for (int i = 0; i < supportingTokenParameters.Signed.Count; ++i)
{
SecurityTokenRequirement requirement = CreateInitiatorSecurityTokenRequirement(supportingTokenParameters.Signed[i], SecurityTokenAttachmentMode.Signed);
try
{
if (isOptional)
{
requirement.IsOptionalToken = true;
}
SecurityTokenProvider provider = SecurityProtocolFactory.SecurityTokenManager.CreateSecurityTokenProvider(requirement);
if (provider == null)
{
continue;
}
SupportingTokenProviderSpecification providerSpec = new SupportingTokenProviderSpecification(provider, SecurityTokenAttachmentMode.Signed, supportingTokenParameters.Signed[i]);
providerSpecList.Add(providerSpec);
}
catch (Exception e)
{
if (!isOptional || Fx.IsFatal(e))
{
throw;
}
}
}
}
private async Task MergeSupportingTokenProvidersAsync(TimeSpan timeout)
{
if (ScopedSupportingTokenProviderSpecification.Count == 0)
{
_mergedSupportingTokenProvidersMap = null;
}
else
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
SecurityProtocolFactory.ExpectSupportingTokens = true;
_mergedSupportingTokenProvidersMap = new Dictionary<string, Collection<SupportingTokenProviderSpecification>>();
foreach (string action in ScopedSupportingTokenProviderSpecification.Keys)
{
ICollection<SupportingTokenProviderSpecification> scopedProviders = ScopedSupportingTokenProviderSpecification[action];
if (scopedProviders == null || scopedProviders.Count == 0)
{
continue;
}
Collection<SupportingTokenProviderSpecification> mergedProviders = new Collection<SupportingTokenProviderSpecification>();
foreach (SupportingTokenProviderSpecification spec in ChannelSupportingTokenProviderSpecification)
{
mergedProviders.Add(spec);
}
foreach (SupportingTokenProviderSpecification spec in scopedProviders)
{
await SecurityUtils.OpenTokenProviderIfRequiredAsync(spec.TokenProvider, timeoutHelper.RemainingTime());
if (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)
{
if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey)
{
SecurityProtocolFactory.ExpectKeyDerivation = true;
}
}
mergedProviders.Add(spec);
}
_mergedSupportingTokenProvidersMap.Add(action, mergedProviders);
}
}
}
public Task OpenAsync(TimeSpan timeout)
{
return ((IAsyncCommunicationObject)CommunicationObject).OpenAsync(timeout);
}
public virtual async Task OnOpenAsync(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (SecurityProtocolFactory.ActAsInitiator)
{
ChannelSupportingTokenProviderSpecification = new Collection<SupportingTokenProviderSpecification>();
ScopedSupportingTokenProviderSpecification = new Dictionary<string, ICollection<SupportingTokenProviderSpecification>>();
AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.EndpointSupportingTokenParameters, false, (IList<SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OptionalEndpointSupportingTokenParameters, true, (IList<SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
foreach (string action in SecurityProtocolFactory.SecurityBindingElement.OperationSupportingTokenParameters.Keys)
{
Collection<SupportingTokenProviderSpecification> providerSpecList = new Collection<SupportingTokenProviderSpecification>();
AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OperationSupportingTokenParameters[action], false, providerSpecList);
ScopedSupportingTokenProviderSpecification.Add(action, providerSpecList);
}
foreach (string action in SecurityProtocolFactory.SecurityBindingElement.OptionalOperationSupportingTokenParameters.Keys)
{
Collection<SupportingTokenProviderSpecification> providerSpecList;
ICollection<SupportingTokenProviderSpecification> existingList;
if (ScopedSupportingTokenProviderSpecification.TryGetValue(action, out existingList))
{
providerSpecList = ((Collection<SupportingTokenProviderSpecification>)existingList);
}
else
{
providerSpecList = new Collection<SupportingTokenProviderSpecification>();
ScopedSupportingTokenProviderSpecification.Add(action, providerSpecList);
}
AddSupportingTokenProviders(SecurityProtocolFactory.SecurityBindingElement.OptionalOperationSupportingTokenParameters[action], true, providerSpecList);
}
if (!ChannelSupportingTokenProviderSpecification.IsReadOnly)
{
if (ChannelSupportingTokenProviderSpecification.Count == 0)
{
ChannelSupportingTokenProviderSpecification = EmptyTokenProviders;
}
else
{
SecurityProtocolFactory.ExpectSupportingTokens = true;
foreach (SupportingTokenProviderSpecification tokenProviderSpec in ChannelSupportingTokenProviderSpecification)
{
SecurityUtils.OpenTokenProviderIfRequired(tokenProviderSpec.TokenProvider, timeoutHelper.RemainingTime());
if (tokenProviderSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || tokenProviderSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing)
{
if (tokenProviderSpec.TokenParameters.RequireDerivedKeys && !tokenProviderSpec.TokenParameters.HasAsymmetricKey)
{
SecurityProtocolFactory.ExpectKeyDerivation = true;
}
}
}
ChannelSupportingTokenProviderSpecification =
new ReadOnlyCollection<SupportingTokenProviderSpecification>((Collection<SupportingTokenProviderSpecification>)ChannelSupportingTokenProviderSpecification);
}
}
// create a merged map of the per operation supporting tokens
await MergeSupportingTokenProvidersAsync(timeoutHelper.RemainingTime());
}
}
public Task CloseAsync(bool aborted, TimeSpan timeout)
{
if (aborted)
{
CommunicationObject.Abort();
return Task.CompletedTask;
}
else
{
return ((IAsyncCommunicationObject)CommunicationObject).CloseAsync(timeout);
}
}
public virtual void OnAbort()
{
if (SecurityProtocolFactory.ActAsInitiator)
{
foreach (SupportingTokenProviderSpecification spec in ChannelSupportingTokenProviderSpecification)
{
SecurityUtils.AbortTokenProviderIfRequired(spec.TokenProvider);
}
foreach (string action in ScopedSupportingTokenProviderSpecification.Keys)
{
ICollection<SupportingTokenProviderSpecification> supportingProviders = ScopedSupportingTokenProviderSpecification[action];
foreach (SupportingTokenProviderSpecification spec in supportingProviders)
{
SecurityUtils.AbortTokenProviderIfRequired(spec.TokenProvider);
}
}
}
}
public virtual async Task OnCloseAsync(TimeSpan timeout)
{
if (SecurityProtocolFactory.ActAsInitiator)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
foreach (SupportingTokenProviderSpecification spec in ChannelSupportingTokenProviderSpecification)
{
await SecurityUtils.CloseTokenProviderIfRequiredAsync(spec.TokenProvider, timeoutHelper.RemainingTime());
}
foreach (string action in ScopedSupportingTokenProviderSpecification.Keys)
{
ICollection<SupportingTokenProviderSpecification> supportingProviders = ScopedSupportingTokenProviderSpecification[action];
foreach (SupportingTokenProviderSpecification spec in supportingProviders)
{
await SecurityUtils.CloseTokenProviderIfRequiredAsync(spec.TokenProvider, timeoutHelper.RemainingTime());
}
}
}
}
private static void SetSecurityHeaderId(SendSecurityHeader securityHeader, Message message)
{
SecurityMessageProperty messageProperty = message.Properties.Security;
if (messageProperty != null)
{
securityHeader.IdPrefix = messageProperty.SenderIdPrefix;
}
}
private void AddSupportingTokenSpecification(SecurityMessageProperty security, IList<SecurityToken> tokens, SecurityTokenAttachmentMode attachmentMode, IDictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>> tokenPoliciesMapping)
{
if (tokens == null || tokens.Count == 0)
{
return;
}
for (int i = 0; i < tokens.Count; ++i)
{
security.IncomingSupportingTokens.Add(new SupportingTokenSpecification(tokens[i], tokenPoliciesMapping[tokens[i]], attachmentMode));
}
}
protected void AddSupportingTokenSpecification(SecurityMessageProperty security, IList<SecurityToken> basicTokens, IList<SecurityToken> endorsingTokens, IList<SecurityToken> signedEndorsingTokens, IList<SecurityToken> signedTokens, IDictionary<SecurityToken, ReadOnlyCollection<IAuthorizationPolicy>> tokenPoliciesMapping)
{
AddSupportingTokenSpecification(security, basicTokens, SecurityTokenAttachmentMode.SignedEncrypted, tokenPoliciesMapping);
AddSupportingTokenSpecification(security, endorsingTokens, SecurityTokenAttachmentMode.Endorsing, tokenPoliciesMapping);
AddSupportingTokenSpecification(security, signedEndorsingTokens, SecurityTokenAttachmentMode.SignedEndorsing, tokenPoliciesMapping);
AddSupportingTokenSpecification(security, signedTokens, SecurityTokenAttachmentMode.Signed, tokenPoliciesMapping);
}
protected SendSecurityHeader CreateSendSecurityHeader(Message message, string actor, SecurityProtocolFactory factory)
{
return CreateSendSecurityHeader(message, actor, factory, true);
}
protected SendSecurityHeader CreateSendSecurityHeaderForTransportProtocol(Message message, string actor, SecurityProtocolFactory factory)
{
return CreateSendSecurityHeader(message, actor, factory, false);
}
private SendSecurityHeader CreateSendSecurityHeader(Message message, string actor, SecurityProtocolFactory factory, bool requireMessageProtection)
{
MessageDirection transferDirection = factory.ActAsInitiator ? MessageDirection.Input : MessageDirection.Output;
SendSecurityHeader sendSecurityHeader = factory.StandardsManager.CreateSendSecurityHeader(
message,
actor, true, false,
factory.OutgoingAlgorithmSuite, transferDirection);
sendSecurityHeader.Layout = factory.SecurityHeaderLayout;
sendSecurityHeader.RequireMessageProtection = requireMessageProtection;
SetSecurityHeaderId(sendSecurityHeader, message);
if (factory.AddTimestamp)
{
sendSecurityHeader.AddTimestamp(factory.TimestampValidityDuration);
}
sendSecurityHeader.StreamBufferManager = factory.StreamBufferManager;
return sendSecurityHeader;
}
internal void AddMessageSupportingTokens(Message message, ref IList<SupportingTokenSpecification> supportingTokens)
{
SecurityMessageProperty supportingTokensProperty = message.Properties.Security;
if (supportingTokensProperty != null && supportingTokensProperty.HasOutgoingSupportingTokens)
{
if (supportingTokens == null)
{
supportingTokens = new Collection<SupportingTokenSpecification>();
}
for (int i = 0; i < supportingTokensProperty.OutgoingSupportingTokens.Count; ++i)
{
SupportingTokenSpecification spec = supportingTokensProperty.OutgoingSupportingTokens[i];
if (spec.SecurityTokenParameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.SenderSideSupportingTokensMustSpecifySecurityTokenParameters));
}
supportingTokens.Add(spec);
}
}
}
internal async Task<IList<SupportingTokenSpecification>> TryGetSupportingTokensAsync(SecurityProtocolFactory factory, EndpointAddress target, Uri via, Message message, TimeSpan timeout)
{
IList<SupportingTokenSpecification> supportingTokens = null;
if (!factory.ActAsInitiator)
{
return null;
}
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(message));
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
IList<SupportingTokenProviderSpecification> supportingTokenProviders = GetSupportingTokenProviders(message.Headers.Action);
if (supportingTokenProviders != null && supportingTokenProviders.Count > 0)
{
supportingTokens = new Collection<SupportingTokenSpecification>();
for (int i = 0; i < supportingTokenProviders.Count; ++i)
{
SupportingTokenProviderSpecification spec = supportingTokenProviders[i];
SecurityToken supportingToken;
supportingToken = await spec.TokenProvider.GetTokenAsync(timeoutHelper.RemainingTime());
supportingTokens.Add(new SupportingTokenSpecification(supportingToken, EmptyReadOnlyCollection<IAuthorizationPolicy>.Instance, spec.SecurityTokenAttachmentMode, spec.TokenParameters));
}
}
// add any runtime supporting tokens
AddMessageSupportingTokens(message, ref supportingTokens);
return supportingTokens;
}
protected ReadOnlyCollection<SecurityTokenResolver> MergeOutOfBandResolvers(IList<SupportingTokenAuthenticatorSpecification> supportingAuthenticators, ReadOnlyCollection<SecurityTokenResolver> primaryResolvers)
{
Collection<SecurityTokenResolver> outOfBandResolvers = null;
if (supportingAuthenticators != null && supportingAuthenticators.Count > 0)
{
for (int i = 0; i < supportingAuthenticators.Count; ++i)
{
if (supportingAuthenticators[i].TokenResolver != null)
{
outOfBandResolvers = outOfBandResolvers ?? new Collection<SecurityTokenResolver>();
outOfBandResolvers.Add(supportingAuthenticators[i].TokenResolver);
}
}
}
if (outOfBandResolvers != null)
{
if (primaryResolvers != null)
{
for (int i = 0; i < primaryResolvers.Count; ++i)
{
outOfBandResolvers.Insert(0, primaryResolvers[i]);
}
}
return new ReadOnlyCollection<SecurityTokenResolver>(outOfBandResolvers);
}
else
{
return primaryResolvers ?? EmptyReadOnlyCollection<SecurityTokenResolver>.Instance;
}
}
protected void AddSupportingTokens(SendSecurityHeader securityHeader, IList<SupportingTokenSpecification> supportingTokens)
{
if (supportingTokens != null)
{
for (int i = 0; i < supportingTokens.Count; ++i)
{
SecurityToken token = supportingTokens[i].SecurityToken;
SecurityTokenParameters tokenParameters = supportingTokens[i].SecurityTokenParameters;
switch (supportingTokens[i].SecurityTokenAttachmentMode)
{
case SecurityTokenAttachmentMode.Signed:
securityHeader.AddSignedSupportingToken(token, tokenParameters);
break;
case SecurityTokenAttachmentMode.Endorsing:
securityHeader.AddEndorsingSupportingToken(token, tokenParameters);
break;
case SecurityTokenAttachmentMode.SignedEncrypted:
securityHeader.AddBasicSupportingToken(token, tokenParameters);
break;
case SecurityTokenAttachmentMode.SignedEndorsing:
securityHeader.AddSignedEndorsingSupportingToken(token, tokenParameters);
break;
default:
Fx.Assert("Unknown token attachment mode " + supportingTokens[i].SecurityTokenAttachmentMode.ToString());
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnknownTokenAttachmentMode, supportingTokens[i].SecurityTokenAttachmentMode.ToString())));
}
}
}
}
internal static async Task<SecurityToken> GetTokenAsync(SecurityTokenProvider provider, EndpointAddress target, TimeSpan timeout)
{
if (provider == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.TokenProviderCannotGetTokensForTarget, target)));
}
SecurityToken token = null;
try
{
token = await provider.GetTokenAsync(timeout);
}
catch (SecurityTokenException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.TokenProviderCannotGetTokensForTarget, target), exception));
}
catch (SecurityNegotiationException sne)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.TokenProviderCannotGetTokensForTarget, target), sne));
}
return token;
}
public abstract Task<Message> SecureOutgoingMessageAsync(Message message, TimeSpan timeout);
// subclasses that offer correlation should override this version
public virtual async Task<(SecurityProtocolCorrelationState, Message)> SecureOutgoingMessageAsync(Message message, TimeSpan timeout, SecurityProtocolCorrelationState correlationState)
{
return (null, await SecureOutgoingMessageAsync(message, timeout));
}
protected virtual void OnOutgoingMessageSecured(Message securedMessage)
{
}
protected virtual void OnSecureOutgoingMessageFailure(Message message)
{
}
public abstract void VerifyIncomingMessage(ref Message message, TimeSpan timeout);
// subclasses that offer correlation should override this version
public virtual SecurityProtocolCorrelationState VerifyIncomingMessage(ref Message message, TimeSpan timeout, params SecurityProtocolCorrelationState[] correlationStates)
{
VerifyIncomingMessage(ref message, timeout);
return null;
}
protected virtual void OnIncomingMessageVerified(Message verifiedMessage)
{
}
protected virtual void OnVerifyIncomingMessageFailure(Message message, Exception exception)
{
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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.Globalization;
using System.Linq;
using ASC.Collections;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core.Tenants;
using ASC.Projects.Core.DataInterfaces;
using ASC.Projects.Core.Domain;
namespace ASC.Projects.Data.DAO
{
internal class CachedSubtaskDao : SubtaskDao
{
private readonly HttpRequestDictionary<Subtask> _subtaskCache = new HttpRequestDictionary<Subtask>("subtask");
public CachedSubtaskDao(int tenantID) : base(tenantID)
{
}
public override void Delete(int id)
{
ResetCache(id);
base.Delete(id);
}
public override Subtask GetById(int id)
{
return _subtaskCache.Get(id.ToString(CultureInfo.InvariantCulture), () => GetBaseById(id));
}
private Subtask GetBaseById(int id)
{
return base.GetById(id);
}
public override Subtask Save(Subtask subtask)
{
if (subtask != null)
{
ResetCache(subtask.ID);
}
return base.Save(subtask);
}
private void ResetCache(int subtaskId)
{
_subtaskCache.Reset(subtaskId.ToString(CultureInfo.InvariantCulture));
}
}
class SubtaskDao : BaseDao, ISubtaskDao
{
private readonly Converter<object[], Subtask> converter;
public SubtaskDao(int tenantID) : base(tenantID)
{
converter = ToSubTask;
}
public List<Subtask> GetSubtasks(int taskid)
{
return Db.ExecuteList(CreateQuery().Where("task_id", taskid)).ConvertAll(converter);
}
public void GetSubtasksForTasks(ref List<Task> tasks)
{
var taskIds = tasks.Select(t => t.ID).ToArray();
var subtasks = Db.ExecuteList(CreateQuery().Where(Exp.In("task_id", taskIds)))//bug: there may be too large set of tasks
.ConvertAll(converter);
tasks = tasks.GroupJoin(subtasks, task => task.ID, subtask => subtask.Task, (task, subtaskCol) =>
{
task.SubTasks.AddRange(subtaskCol.ToList());
return task;
}).ToList();
}
public List<Subtask> GetSubtasks(Exp where)
{
return Db.ExecuteList(CreateQuery().Where(where)).ConvertAll(converter);
}
public virtual Subtask GetById(int id)
{
return Db.ExecuteList(CreateQuery().Where("id", id)).ConvertAll(converter).SingleOrDefault();
}
public List<Subtask> GetById(ICollection<int> ids)
{
return Db.ExecuteList(CreateQuery().Where(Exp.In("id", ids.ToArray()))).ConvertAll(converter);
}
public List<Subtask> GetUpdates(DateTime from, DateTime to)
{
return Db.ExecuteList(CreateQuery().Select("status_changed")
.Where(Exp.Between("create_on", from, to) |
Exp.Between("last_modified_on", from, to) |
Exp.Between("status_changed", from, to)))
.ConvertAll(x =>
{
var st = ToSubTask(x);
st.StatusChangedOn = Convert.ToDateTime(x.Last());
return st;
}).ToList();
}
public List<Subtask> GetByResponsible(Guid id, TaskStatus? status = null)
{
var query = CreateQuery().Where("responsible_id", id);
if (status.HasValue)
{
query.Where("status", status.Value);
}
return Db.ExecuteList(query).ConvertAll(converter);
}
public int GetSubtaskCount(int taskid, params TaskStatus[] statuses)
{
var query = Query(SubtasksTable)
.SelectCount()
.Where("task_id", taskid);
if (statuses != null && 0 < statuses.Length)
{
query.Where(Exp.In("status", statuses));
}
return Db.ExecuteScalar<int>(query);
}
public virtual Subtask Save(Subtask subtask)
{
var insert = Insert(SubtasksTable)
.InColumnValue("id", subtask.ID)
.InColumnValue("task_id", subtask.Task)
.InColumnValue("title", subtask.Title)
.InColumnValue("responsible_id", subtask.Responsible.ToString())
.InColumnValue("status", subtask.Status)
.InColumnValue("create_by", subtask.CreateBy.ToString())
.InColumnValue("create_on", TenantUtil.DateTimeToUtc(subtask.CreateOn))
.InColumnValue("last_modified_by", subtask.LastModifiedBy.ToString())
.InColumnValue("last_modified_on", TenantUtil.DateTimeToUtc(subtask.LastModifiedOn))
.InColumnValue("status_changed", TenantUtil.DateTimeToUtc(subtask.StatusChangedOn))
.Identity(1, 0, true);
subtask.ID = Db.ExecuteScalar<int>(insert);
return subtask;
}
public void CloseAllSubtasks(Task task)
{
Db.ExecuteNonQuery(
Update(SubtasksTable)
.Set("status", TaskStatus.Closed)
.Set("last_modified_by", CurrentUserID)
.Set("last_modified_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))
.Set("status_changed", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow()))
.Where("status", TaskStatus.Open)
.Where("task_id", task.ID));
}
public virtual void Delete(int id)
{
Db.ExecuteNonQuery(Delete(SubtasksTable).Where("id", id));
}
private SqlQuery CreateQuery()
{
return new SqlQuery(SubtasksTable)
.Select("id", "title", "responsible_id", "status", "create_by", "create_on", "last_modified_by", "last_modified_on", "task_id")
.OrderBy("status", true)
.OrderBy("(case status when 1 then create_on else status_changed end)", true)
.Where("tenant_id", Tenant);
}
private static Subtask ToSubTask(IList<object> r)
{
return new Subtask
{
ID = Convert.ToInt32(r[0]),
Title = (string)r[1],
Responsible = ToGuid(r[2]),
Status = (TaskStatus)Convert.ToInt32(r[3]),
CreateBy = ToGuid(r[4]),
CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[5])),
LastModifiedBy = ToGuid(r[6]),
LastModifiedOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[7])),
Task = Convert.ToInt32(r[8])
};
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field01.field01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field01.field01;
// <Title> Compound operator in field.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
char c = (char)2;
d.field *= c;
int i = 5;
d.field /= Method(i);
sbyte s = 3;
d.field %= t[s];
if (d.field != 1)
return 1;
MyDel md = Method;
dynamic dmd = new MyDel(Method);
d.field += md(2);
if (d.field != 3)
return 1;
d.field -= dmd(2);
if (d.field != 1)
return 1;
return (int)(d.field -= LongPro);
}
public long field = 10;
public static int Method(int i)
{
return i;
}
public dynamic this[object o]
{
get
{
return o;
}
}
public static long LongPro
{
protected get
{
return 1L;
}
set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field02.field02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field02.field02;
// <Title> Compound operator in field.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
dynamic c = (char)2;
dynamic c0 = c;
d.field *= c0;
c = 5;
d.field /= Method(c);
sbyte s = 3;
c = s;
d.field %= t[c];
if (d.field != 1)
return 1;
MyDel md = Method;
dynamic dmd = new MyDel(Method);
c = 2;
d.field += md(c);
if (d.field != 3)
return 1;
d.field -= dmd(2);
if (d.field != 1)
return 1;
return (int)(d.field -= d.LongPro);
}
public long field = 10;
public static int Method(int i)
{
return i;
}
public dynamic this[object o]
{
get
{
return o;
}
}
public long LongPro
{
protected get
{
return 1L;
}
set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field03.field03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.field03.field03;
public class Test
{
static public dynamic count1 = 1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
count1 = count1 + 1;
count1 += 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property01.property01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property01.property01;
// <Title> Compound operator in property.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
d.StringProp = "a";
d.StringProp += "b";
d.StringProp += t.StringProp;
d.StringProp += t.Method(1);
var temp = 10.1M;
d.StringProp += t[temp];
if (d.StringProp != "abab1" + temp.ToString())
return 1;
return 0;
}
public string StringProp
{
get;
set;
}
public int Method(int i)
{
return i;
}
public dynamic this[object o]
{
get
{
return o;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property02.property02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property02.property02;
// <Title> Compound operator in property.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
dynamic c = "a";
d.StringProp = c;
c = "b";
d.StringProp += c;
d.StringProp += d.StringProp;
c = 1;
d.StringProp += d.Method(c);
c = 10.1M;
d.StringProp += d[c];
if (d.StringProp != "abab1" + c.ToString())
return 1;
return 0;
}
public string StringProp
{
get;
set;
}
public int Method(int i)
{
return i;
}
public dynamic this[object o]
{
get
{
return o;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property03.property03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.property03.property03;
// <Title> Compound operator with property.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class C
{
public dynamic P
{
get;
set;
}
public static dynamic operator +(C lhs, int rhs)
{
lhs.P = lhs.P + rhs;
return lhs;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
C c = new C()
{
P = 0
}
;
c += 2;
return c.P == 2 ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.indexer01.indexer01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.indexer01.indexer01;
// <Title> Compound operator in indexer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
char c = (char)2;
d[null] *= c;
int i = 5;
d[1] /= Method(i);
sbyte s = 3;
d[default(long)] %= t[s, ""];
if (d[default(string)] != 1)
return 1;
MyDel md = Method;
dynamic dmd = new MyDel(Method);
d[default(dynamic)] += md(2);
if (d[12.34f] != 3)
return 1;
d[typeof(Test)] -= dmd(2);
if (d[""] != 1)
return 1;
return (int)(d[new Test()] -= LongPro);
}
private long _field = 10;
public long this[dynamic d]
{
get
{
return _field;
}
set
{
_field = value;
}
}
public static int Method(int i)
{
return i;
}
public dynamic this[object o, string m]
{
get
{
return o;
}
}
public static long LongPro
{
protected get
{
return 1L;
}
set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.indexer02.indexer02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.indexer02.indexer02;
// <Title> Compound operator in indexer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
dynamic d = t;
char c = (char)2;
dynamic c0 = c;
d[null] *= c0;
dynamic i = 5;
d[1] /= Method(i);
sbyte s = 3;
dynamic s0 = s;
d[default(long)] %= t[s0, ""];
if (d[default(string)] != 1)
return 1;
MyDel md = Method;
dynamic dmd = new MyDel(Method);
dynamic md0 = 2;
d[default(dynamic)] += md(md0);
if (d[12.34f] != 3)
return 1;
d[typeof(Test)] -= dmd(2);
if (d[""] != 1)
return 1;
return (int)(d[new Test()] -= LongPro);
}
private long _field = 10;
public long this[dynamic d]
{
get
{
return _field;
}
set
{
_field = value;
}
}
public static int Method(int i)
{
return i;
}
public dynamic this[object o, string m]
{
get
{
return o;
}
}
public static long LongPro
{
protected get
{
return 1L;
}
set
{
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order01.order01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order01.order01;
// <Title> Compound operator excute orders.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
dynamic t = new Test();
t.field *= t.field += t.field;
if (t.field != 200)
return 1;
return 0;
}
public long field = 10;
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order02.order02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order02.order02;
// <Title> Compound operator excute orders.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
dynamic t = new Test();
dynamic b = (byte)2;
t.MyPro = 7;
t.field = 8;
t.MyPro %= t.field >>= b;
if (t.MyPro != 1 || t.field != 2)
return 1;
return 0;
}
public byte field = 10;
public short myProvalue;
public short MyPro
{
internal get
{
return myProvalue;
}
set
{
myProvalue = value;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order03.order03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order03.order03;
// <Title> Compound operator excute orders.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
dynamic t = new Test();
dynamic b = (byte)2;
t[null] += t[b] *= t[""];
if (t[null] != 110)
return 1;
return 0;
}
public dynamic myvalue = 10;
public dynamic this[object o]
{
get
{
return myvalue;
}
set
{
this.myvalue = value;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order04.order04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order04.order04;
// <Title> Compound operator excute orders.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
MyDel md = new MyDel(Method);
t.field *= t.LongPro %= t[(sbyte)10] -= md(3);
if (t.field != 40 || t.LongPro != 4 || t[null] != 5)
return 1;
return 0;
}
public long field = 10;
public static int Method(int i)
{
return i;
}
private long _this0 = 8;
public long this[object o]
{
get
{
return _this0;
}
set
{
_this0 = value;
}
}
private long _longvalue = 9;
public long LongPro
{
protected get
{
return _longvalue;
}
set
{
_longvalue = value;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order05.order05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order05.order05;
// <Title> Compound operator excute orders.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
Test t = new Test();
MyDel md = new MyDel(Method);
t.field *= t.LongPro += t[(int)10] -= md(3);
if (t.field != 50 || t.LongPro != 5 || t[null] != 5)
return 1;
return 0;
}
public long field = 10;
public static int Method(int i)
{
return i;
}
private dynamic _this0 = 8;
public dynamic this[object o]
{
get
{
return _this0;
}
set
{
_this0 = value;
}
}
private long _longvalue = 0;
public long LongPro
{
protected get
{
return _longvalue;
}
set
{
_longvalue = value;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order06.order06
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.order06.order06;
// <Title> Compound operator excute orders.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public delegate int MyDel(int i);
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] ars)
{
dynamic t = new Test();
MyDel md = new MyDel(Method);
t.field *= t.LongPro += t[(int)10] -= md(3);
if (t.field != 50 || t.LongPro != 5 || t[null] != 5)
return 1;
return 0;
}
public long field = 10;
public static int Method(int i)
{
return i;
}
private dynamic _this0 = 8;
public dynamic this[object o]
{
get
{
return _this0;
}
set
{
_this0 = value;
}
}
private long _longvalue = 0;
public long LongPro
{
protected get
{
return _longvalue;
}
set
{
_longvalue = value;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context01.context01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context01.context01;
// <Title> Compound operator</Title>
// <Description>context
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var obj = new Test();
//
dynamic v1 = obj.Prop; //100
dynamic v2 = obj.Method((short)(v1 -= 80));
v1 += 80;
dynamic v3 = obj[v2 *= (s_field -= 6)];
v2 /= s_field;
dynamic val = 0;
for (int i = v2; i < checked(v1 += v3 -= v2); i++)
{
val += 1;
}
// System.Console.WriteLine("{0}, {1}, {2} {3}", v1, v2, v3, field);
dynamic ret = 7 == val;
//
v1 *= obj.Prop -= 15; // 120
v2 *= (s_field += 1.1);
v3 = obj[v2 %= (s_field *= 3.4)] + 100;
dynamic arr = new[]
{
v1 <<= (int)(v1 >>= 10), v2 *= v2 *= 2, v3 *= v1 * (v1 -= s_field)}
;
// System.Console.WriteLine("{0}, {1}, {2}", arr[0], arr[1], arr[2]);
ret &= 3400 == arr[0];
ret &= (468.18 - arr[1]) < Double.Epsilon;
ret &= (1326070373.2 - arr[2]) < Double.Epsilon;
v1 = 1.1f;
v2 = -2.2f;
v3 = 5.5f;
arr = new
{
a1 = v3 -= v1 += v2,
a2 = v1 *= v2 + 1,
a3 = v3 /= 1.1f
}
;
System.Console.WriteLine("{0}, {1}, {2}", (object)arr.a1, (object)arr.a2, (object)arr.a3);
ret &= (6.6 - arr.a1) < 0.0000001f; // delta ~ 0.00000009f
ret &= (1.23 - arr.a2) < Double.Epsilon;
ret &= (6 - arr.a3) < Double.Epsilon;
System.Console.WriteLine((object)ret);
return ret ? 0 : 1;
}
private static dynamic s_field = 10;
public dynamic Prop
{
get
{
return 100L;
}
set
{
}
}
public dynamic Method(short i)
{
return i;
}
public dynamic this[object o]
{
get
{
return o;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context02b.context02b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context02b.context02b;
// <Title> Compound operator</Title>
// <Description>context
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var obj = new Test();
bool ret = obj.RunTest();
return ret ? 0 : 1;
}
public struct MySt
{
public MySt(ulong? f)
{
field = f;
}
public ulong? field;
}
public dynamic RunTest()
{
dynamic[] darr = new[]
{
"X", "0", "Y"
}
;
List<dynamic> list = new List<dynamic>();
list.AddRange(darr);
bool ret = "X0X0Y" == Method()(list[0] += list[1], list[2]);
ret &= "YX" == this[list[2]](null, darr[0]);
var va = new List<dynamic>
{
new MySt(null), new MySt(3), new MySt(5), new MySt(7), new MySt(11), new MySt(13)}
;
var q =
from i in new[]
{
va[1].field *= 11, va[2].field *= va[2].field %= 19, va[3].field += va[4].field *= va[5].field
}
where (0 < (va[5].field += va[3].field -= 2))
select i;
dynamic idx = 0;
foreach (var v in q)
{
if (0 == idx)
{
ret &= (33 == v);
// System.Console.WriteLine("v1 {0}", v);
}
else if (idx == 1)
{
// System.Console.WriteLine("v2 {0}", v);
ret &= (25 == v);
}
else if (idx == 2)
{
// System.Console.WriteLine("v3 {0}", v);
ret &= (150 == v);
}
idx++;
}
return ret;
}
public delegate dynamic MyDel(dynamic p1, dynamic p2 = default(object), long p3 = 100);
public dynamic Method()
{
MyDel md = delegate (dynamic d, object o, long n)
{
d += d += o;
return d;
}
;
return md;
}
public dynamic this[dynamic o]
{
get
{
return new MyDel((x, y, z) =>
{
return o + y;
}
);
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context02c.context02c
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context02c.context02c;
// <Title> Compound operator</Title>
// <Description>context
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var obj = new Test();
bool ret = obj.RunTest();
return ret ? 0 : 1;
}
public struct MySt
{
public MySt(ulong? f)
{
field = f;
}
public ulong? field;
}
public dynamic RunTest()
{
dynamic[] darr = new[]
{
"X", "0", "Y"
}
;
List<dynamic> list = new List<dynamic>();
list.AddRange(darr);
bool ret = "X0YY" == Method()(list[0] += list[1], list[2]);
ret &= "YX" == this[list[2]](null, darr[0]);
var va = new List<dynamic>
{
new MySt(null), new MySt(3), new MySt(5), new MySt(7), new MySt(11), new MySt(13)}
;
var q =
from i in new[]
{
va[1].field *= 11, va[2].field *= va[2].field %= 19, va[3].field += va[4].field *= va[5].field
}
where (0 < (va[5].field += va[3].field -= 2))
select i;
dynamic idx = 0;
foreach (var v in q)
{
if (0 == idx)
{
ret &= (33 == v);
// System.Console.WriteLine("v1 {0}", v);
}
else if (idx == 1)
{
// System.Console.WriteLine("v2 {0}", v);
ret &= (25 == v);
}
else if (idx == 2)
{
// System.Console.WriteLine("v3 {0}", v);
ret &= (150 == v);
}
idx++;
}
return ret;
}
public delegate dynamic MyDel(dynamic p1, dynamic p2 = default(object), long p3 = 100);
public dynamic Method()
{
MyDel md = delegate (dynamic d, dynamic o, long n)
{
d += o += o;
return d;
}
;
return md;
}
public dynamic this[dynamic o]
{
get
{
return new MyDel((x, y, z) =>
{
return o + y;
}
);
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context03.context03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.context03.context03;
// <Title> Compound operator (Regression) </Title>
// <Description>context
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic[] da = new[]
{
"X", "Y"
}
;
var v = M()(da[0] += "Z");
return (v == "XZ") ? 0 : 1;
}
public delegate string MyDel(string s);
public static MyDel M()
{
return new MyDel(x =>
{
return x;
}
);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.bug741491array.bug741491array
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.bug741491array.bug741491array;
// <Title> Compound operator (Regression) </Title>
// <Description>LHS of compound op with dynamic array/index access
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
using System;
public class Test
{
public dynamic this[int i]
{
get
{
return 0;
}
set
{
}
}
public int this[int i, int j]
{
get
{
return i + j;
}
set
{
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
bool ret = true;
var x = new Test();
x[i: 0] += null; // [IL] stack overflow
x[i: 1] -= 1;
x[i: -0]++; // ICE
x[i: -1]--; // ICE
dynamic d = 3;
x[0, j: 1] += d;
x[i: 1, j: -1] -= d;
ret &= x.Test01();
ret &= x.Test02();
ret &= x.Test03();
return ret ? 0 : 1;
}
private bool Test01()
{
bool ret = true;
dynamic[] dary = new dynamic[]
{
100, 200, 300
}
;
dary[0]++;
ret &= 101 == dary[0];
dary[1]--;
ret &= 199 == dary[1];
if (!ret)
System.Console.WriteLine("Test01 fail - ++/--");
return ret;
}
private bool Test02()
{
bool ret = true;
dynamic[] dary = new dynamic[]
{
0, -1, 1
}
;
dary[0] += null;
dary[1] += 2;
ret &= 1 == dary[1];
dary[2] -= 1;
ret &= 0 == dary[2];
if (!ret)
System.Console.WriteLine("Test02 fail - +=/-=");
return ret;
}
private bool Test03()
{
bool ret = true;
int[] iary = new[]
{
-1, -2, -3
}
;
dynamic d = 3;
iary[0] += d;
ret &= 2 == iary[0];
iary[1] -= d;
ret &= -5 == iary[1];
if (!ret)
System.Console.WriteLine("Test03 fail - +=/-=");
return ret;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.using01.using01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.basic.using01.using01;
// <Title> Dynamic modification of a using variable </Title>
// <Description>
// Different from static behavior, no exception.
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
//<Expects Status=warning>\(13,16\).*CS0649</Expects>
using System;
public class TestClass
{
[Fact]
public void RunTest()
{
A.DynamicCSharpRunTest();
}
}
public struct A : IDisposable
{
public int X;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
using (dynamic a = new A())
{
a.X++; //no Exception here in dynamic call.
}
return 0;
}
public void Dispose()
{
}
}
}
| |
/*---------------------------------------------------------------------------
Copyright 2015 Microsoft
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.
File:
vHub.Interface.fs
Description:
Interface for vHub.
Author:
Jin Li, Partner Research Manager
Microsoft Research, One Microsoft Way
Email: jinl@microsoft.com, Tel. (425) 703-8451
Date:
May. 2015
---------------------------------------------------------------------------*/
using System;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using Prajna.Services.Vision.Data;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Diagnostics;
using Prajna.Service.CoreServices.Data;
namespace Prajna.AppLibrary
{
/// <summary>
/// State of a service
/// </summary>
public class ServiceState
{
/// <summary>
/// Whether the service is Live at last observation
/// </summary>
private Boolean Live;
/// <summary>
/// Last tick when the service state is updated
/// </summary>
private Int64 Ticks;
/// <summary>
/// If this time has passed, rechecked the liveness of the system
/// </summary>
[System.ComponentModel.DefaultValue(30000)]
public Int32 CheckForLivenessInMilliseconds { get; set; }
/// <summary>
/// Initialize an instance of the ServiceState. We always initialize the Liveness to false,
/// and the time of check to be one day old. This will trigger rechecking of the state.
/// </summary>
public ServiceState( )
{
Live = false;
Ticks = DateTime.UtcNow.Ticks - TimeSpan.TicksPerDay;
}
/// <summary>
/// Set the state of the liveness of service
/// </summary>
/// <param name="bLive">Boolean state of the liveness of a service </param>
private void SetState( Boolean bLive )
{
Live = bLive;
Ticks = DateTime.UtcNow.Ticks;
}
public Boolean State
{
get
{
return Live;
}
set
{
SetState(value);
}
}
public Boolean NeedsToCheck()
{
if (Live)
{
return false;
}
else
{
var ticksCur = DateTime.UtcNow.Ticks;
return ((ticksCur - Ticks) / TimeSpan.TicksPerMillisecond >= CheckForLivenessInMilliseconds);
}
}
}
/// <summary>
/// Information about a server
/// </summary>
public class OneServerInfo
{
/// <summary>
/// HostName
/// </summary>
[DataMember]
public String HostName { get; set; }
/// <summary>
/// Information of the Host.
/// </summary>
[DataMember]
public String HostInfo { get; set; }
}
/// <summary>
/// GatewayHttpInterface is the interface of the App Library. It is in charge of all communication function to the gateway.
/// </summary>
public class GatewayHttpInterface
{
/// <summary>
/// Page to check when validating internet connectivity
/// </summary>
private static String DefaultCheckPage = "http://bing.com/";
private static String DefaultWebInfoPage = "web/Info";
private static String CheckToken = "bing.com";
private static String StatusOK = "OK";
/// <summary>
/// Key to access local default Gateway
/// </summary>
public static String GatewayKey = "DefaultGateway";
/// <summary>
/// Key to access local default GatewayCollections
/// </summary>
public static String GatewayCollectionKey = "GatewayCollections";
/// <summary>
/// Key to access default service provider
/// </summary>
public static String ProviderKey = "DefaultProvider";
/// <summary>
/// Key to access default domain
/// </summary>
public static String DomainKey = "DefaultDomain";
///if the tutorial has run
public static String tutorialShown = "No";
/// <summary>
/// Gateway being used
/// </summary>
public String CurrentGateway { get; set; }
/// <summary>
/// Current Provider
/// </summary>
public RecogEngine CurrentProvider { get; set; }
/// <summary>
/// Information of Current Domain
/// </summary>
public RecogInstance CurrentDomain { get; set; }
/// <summary>
/// Current Schema used
/// </summary>
public Guid CurrentSchema { get; set; }
/// <summary>
/// Current Distribution used
/// </summary>
public Guid CurrentDistribution { get; set; }
/// <summary>
/// Current Aggregation used
/// </summary>
public Guid CurrentAggregation { get; set; }
/// <summary>
/// Public Customer ID that identified the application that accesses the gateway
/// </summary>
public Guid CustomerID { get; set; }
/// <summary>
/// A secret customer key that is used to identify the customer that accesses the gateway
/// </summary>
public String CustomerKey { get; set; }
/// <summary>
/// Current status of the gateway
/// </summary>
public ConcurrentDictionary<String, OneServerMonitoredStatus> GatewayCollection { get; set; }
private Int32 LastRtt { get; set; }
private String ServiceURI { get; set; }
private String GetTicks()
{
return System.DateTime.UtcNow.Ticks.ToString();
}
private String GetRtt()
{
return "0";
}
private ServiceState NetworkStatus;
private ServiceState GatewayStatus;
private ServiceState ProviderStatus;
private ServiceState InstanceStatus;
/// <summary>
/// Status Message
/// </summary>
public String ErrorMessage;
/// <summary>
/// Last thrown exception message, if any.
/// </summary>
public String ExceptionMessage;
/// <summary>
/// Encode type T to a bytearray via JSon serializer
/// </summary>
/// <typeparam name="T">type of value</typeparam>
/// <param name="value">object to be serialized</param>
/// <returns>output bytearray </returns>
public static byte[] EncodeToBytes<T>( T value)
{
using (var stream = new MemoryStream())
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
json.WriteObject(stream, value);
return stream.ToArray();
}
}
/// <summary>
/// Decode a JSON serialized byte array to an object
/// </summary>
/// <typeparam name="Ty">Type of the objedct</typeparam>
/// <param name="buf">Input bytearray </param>
/// <returns>Decoded object</returns>
public static Ty DecodeFromBytes<Ty>(byte[] buf)
{
if (Object.ReferenceEquals(buf, null) || buf.Length == 0)
{
return default(Ty);
}
else
{
using (var stream = new MemoryStream(buf, 0, buf.Length, false))
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Ty));
var obj = json.ReadObject(stream);
return (Ty)obj;
}
}
}
/// <summary>
/// Instantiate on a GatewayHttpInterface class with gateway, customerID and customerKey
/// </summary>
/// <param name="gateway">Gateway information</param>
/// <param name="customerID">Customer ID</param>
/// <param name="customerKey">Customer Key</param>
public GatewayHttpInterface( String gateway, Guid customerID, String customerKey )
{
NetworkStatus = new ServiceState();
GatewayStatus = new ServiceState();
ProviderStatus = new ServiceState();
InstanceStatus = new ServiceState();
ErrorMessage = StatusOK;
// Gateway should not contains http:
Contract.Assert(gateway.IndexOf(@"http:") < 0);
// Customer key should be at least 10 characters
Contract.Assert(customerKey.Length > 10);
// Customer key should not be zero length
this.CurrentGateway = gateway;
this.CustomerID = customerID;
this.CustomerKey = customerKey;
this.GatewayCollection = new ConcurrentDictionary<String, OneServerMonitoredStatus>(StringComparer.OrdinalIgnoreCase);
CurrentSchema = Guid.Empty;
CurrentDistribution = Guid.Empty;
CurrentAggregation = Guid.Empty;
this.LastRtt = 0;
}
/// <summary>
/// Form a service URI
/// ToDo: Implementation security feature of sending customerKey
/// </summary>
/// <param name="serviceString"></param>
/// <returns></returns>
private Uri FormServiceURI( String serviceString )
{
var sb = new StringBuilder(1024);
sb.Append( @"http://" );
sb.Append( this.CurrentGateway );
sb.Append( @"/Vhub/" );
sb.Append(serviceString);
sb.Append(@"/");
sb.Append( this.CustomerID );
sb.Append( @"/" );
var ticks = System.DateTime.UtcNow.Ticks;
sb.Append( ticks.ToString() );
sb.Append( @"/" );
sb.Append( this.LastRtt.ToString() );
sb.Append( @"/" );
sb.Append(this.CustomerKey);
return new Uri(sb.ToString());
}
private String ServiceInfoUrl()
{
var sb = new StringBuilder(1024);
sb.Append(@"http://");
sb.Append(this.CurrentGateway);
sb.Append(@"/");
sb.Append(DefaultWebInfoPage);
return sb.ToString();
}
/// <summary>
/// Retrieve a webpage
/// </summary>
/// <param name="uriString">URL</param>
/// <returns>content of the URL</returns>
public async Task<String> GetWebPage(String uriString)
{
using (var httpClient = new HttpClient())
{
var theUri = new Uri(uriString);
using (HttpResponseMessage response = await httpClient.GetAsync(theUri, HttpCompletionOption.ResponseContentRead))
using (HttpContent content = response.Content)
{
String result = await content.ReadAsStringAsync();
return result;
}
}
}
/// <summary>
/// Return internet Connection status.
/// </summary>
/// <param name="bForce">If true, the Internet connection state will be updated. Otherwise,the Internet connection state will be checked
/// if it hasn't been connected, and sometime has passed from the last state updated. </param>
/// <returns> Whether the Internet is connected. </returns>
public async Task<Boolean> CheckInternetConnection(Boolean bForce)
{
if ( bForce || NetworkStatus.NeedsToCheck())
{
try
{
var webResult = await GetWebPage(DefaultCheckPage);
if (String.IsNullOrEmpty(webResult))
{
NetworkStatus.State = false;
ErrorMessage = "Faulty Internet Connection, can't reach any extern site... ";
}
else if (webResult.IndexOf(CheckToken, StringComparison.OrdinalIgnoreCase) >= 0)
{
NetworkStatus.State = true;
}
else
{
NetworkStatus.State = false;
ErrorMessage = "Faulty Internet Connection, extern site return incorrection information... ";
}
}
catch (Exception ex )
{
NetworkStatus.State = false;
ExceptionMessage = ex.Message;
ErrorMessage = "Network is not connected... ";
}
}
return NetworkStatus.State;
}
/// <summary>
/// Return Current Gateway Liveness Status.
/// </summary>
/// <param name="bForce">If true, the Gateway state will always be updated. Otherwise, the Gateway state will be updated
/// if the gateway isn't alive, and sometime has passed from the last state updated. </param>
/// <returns> Whether the Gateway is live. </returns>
public async Task<Boolean> CheckGatewayStatus(Boolean bForce)
{
if (bForce || GatewayStatus.NeedsToCheck())
{
try
{
var webInfoPage = ServiceInfoUrl();
var webResult = await GetWebPage(webInfoPage);
if (String.IsNullOrEmpty(webResult))
{
GatewayStatus.State = false;
ErrorMessage = String.Format("Gateway {0} is faulty ... ", this.CurrentGateway);
}
else
{
GatewayStatus.State = true;
}
}
catch (Exception ex)
{
GatewayStatus.State = false;
ExceptionMessage = ex.Message;
ErrorMessage = String.Format("Gateway {0} is not online ... ", this.CurrentGateway);
}
if (!GatewayStatus.State)
{
var bNetwork = await CheckInternetConnection(true);
return false;
}
}
return GatewayStatus.State;
}
/// Calling a VHub WebGet service, exception needs to be handled by calling function
/// </summary>
/// <param name="serviceString">Service String sent to the gateway</param>
/// <returns>A Memory Stream that holds the returned object (usually Json coded) </returns>
private async Task<byte[]> ExecuteGetService( String serviceString )
{
try
{
using (var httpClient = new HttpClient())
{
var theUri = this.FormServiceURI(serviceString);
using (HttpResponseMessage response = await httpClient.GetAsync(theUri, HttpCompletionOption.ResponseContentRead))
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var byt = await content.ReadAsByteArrayAsync();
return byt;
}
}
else
{
throw new System.InvalidOperationException(
String.Format("Code: {0}, Reason:{1}", response.StatusCode,
response.ReasonPhrase));
}
}
}
catch (Exception e)
{
Debug.WriteLine("GatewayHttpInterface.ExecuteGetService fails when try to access service string {0}, with exception {1}", serviceString, e);
throw;
}
}
/// <summary>
/// Calling a VHub WebInvoke interface, exception needs to be handled by calling function
/// </summary>
/// <param name="serviceString">Service String sent to the gateway</param>
/// <param name="buf">additional content (e.g.,image) that will be sent via WebInvoke interface</param>
/// <returns>A Memory Stream that holds the returned object (usually Json coded)</returns>
public async Task<byte[]> ExecuteInvokeService(String serviceString, Byte[] buf)
{
try
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var theUri = this.FormServiceURI(serviceString);
ByteArrayContent inpContent = new ByteArrayContent(buf);
using (HttpResponseMessage response = await httpClient.PostAsync(theUri, inpContent))
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var byt = await content.ReadAsByteArrayAsync();
return byt;
}
}
else
{
throw new System.InvalidOperationException(
String.Format("Code: {0}, Reason:{1}", response.StatusCode,
response.ReasonPhrase));
}
}
}
catch (Exception e)
{
Debug.WriteLine("GatewayHttpInterface.ExecuteInvokeService fails when try to access service string {0}, with exception {1}", serviceString, e);
throw;
}
}
/// <summary>
/// GetService, allow redirect
/// </summary>
/// <param name="serviceString"></param>
/// <returns></returns>
private async Task<byte[]> GetService( String serviceString )
{
return await ExecuteGetService(serviceString);
}
/// <summary>
/// InvokeService, allow redirect
/// </summary>
/// <param name="serviceString">Service String sent to the gateway</param>
/// <param name="buf">additional content (e.g.,image) that will be sent via WebInvoke interface</param>
/// <returns></returns>
private async Task<byte[]> InvokeService(String serviceString, Byte[] buf)
{
return await ExecuteInvokeService(serviceString, buf);
}
private List<OneServerInfo> CurrentGatewayList()
{
var lst = new List<OneServerInfo>();
foreach ( var kv in this.GatewayCollection )
{
var serverInfo = new OneServerInfo();
var hostname = kv.Key;
var hostinfo = kv.Value;
serverInfo.HostName = hostname;
serverInfo.HostInfo = String.Format("Reliability={0:F2},Rtt={1}ms,Perf={2}ms",
(float)hostinfo.PeriodAlive / (float)hostinfo.PeriodMonitored,
hostinfo.RttInMs, hostinfo.PerfInMs);
lst.Add(serverInfo);
}
return lst;
}
/// <summary>
/// Get a list of gateways that are in service
/// </summary>
/// <returns>A list of gateways </returns>
public async Task<List<OneServerInfo>> GetActiveGateways()
{
try
{
var buf = await GetService("GetActiveGateways");
try
{
var result = DecodeFromBytes<OneServerMonitoredStatus[]>(buf);
foreach (var oneResult in result)
{
this.GatewayCollection[oneResult.HostName] = oneResult;
}
return CurrentGatewayList();
}
catch ( Exception ex )
{
ErrorMessage = String.Format("Failed to decode active gateway list from {0}", this.CurrentGateway);
ExceptionMessage = ex.Message;
throw (new HttpRequestException(ErrorMessage));
}
}
catch ( Exception ex)
{
var errorString = String.Format("Current gateway {0} is not functional...", this.CurrentGateway);
Debug.WriteLine(errorString);
ErrorMessage = String.Format("Failed to retrieve active gateway list from {0}", this.CurrentGateway);
ExceptionMessage = ex.Message;
}
// Forcing checking gateway
var bGateway = await this.CheckGatewayStatus(true);
throw (new HttpRequestException(ErrorMessage));
}
/// <summary>
/// Get all domains for a particular provider and schema
/// </summary>
/// <param name="providerID">provider </param>
/// <param name="schemaID">schema </param>
/// <returns></returns>
public async Task<Guid[]> GetAllDomainIDs( Guid providerID, Guid schemaID )
{
try
{
var buf = await GetService("GetAllServiceGuids/" + providerID.ToString() + "/" + schemaID.ToString());
try
{
var result = DecodeFromBytes<Guid[]>(buf);
return result;
}
catch( Exception ex)
{
ErrorMessage = String.Format("Failed to decode Domain ID from gateway {0}, with schema {1}", this.CurrentGateway, schemaID);
ExceptionMessage = ex.Message;
throw (new HttpRequestException(ErrorMessage));
}
}
catch (Exception ex)
{
var errorString = String.Format("Get GetAllDomainIDs fails, current gateway {0}, with exception {1}", this.CurrentGateway, ex);
Debug.WriteLine(errorString);
ErrorMessage = String.Format("Failed to retrieve domain ID from gateway {0}, schema {1}", this.CurrentGateway, schemaID);
ExceptionMessage = ex.Message;
}
// Forcing checking gateway
var bGateway = await this.CheckGatewayStatus(true);
throw (new HttpRequestException(ErrorMessage));
}
/// <summary>
/// Check if a certain provider is live on the gateway
/// </summary>
/// <param name="providerID">Provider ID to be checked</param>
/// <returns>Liveness state </returns>
public async Task<Boolean> CheckProviderStatus( Guid providerID )
{
try
{
var engineList = await GetActiveProviders();
Boolean bExist = false;
foreach( var engine in engineList)
{
if (engine.RecogEngineID == providerID)
{
bExist = true;
}
}
if (!bExist)
{
ErrorMessage = String.Format("Provider {0} is not live on gateway {1} ... ", providerID, this.CurrentGateway);
}
return bExist;
}
catch (Exception ex)
{
var errorString = String.Format("CheckProviderStatus fails, current gateway {0}...", this.CurrentGateway);
Debug.WriteLine(errorString);
ErrorMessage = errorString;
ExceptionMessage = ex.Message;
}
// Forcing checking gateway
var bGateway = await this.CheckGatewayStatus(true);
return false;
}
/// <summary>
/// Check if the default provider is live on the gateway
/// </summary>
/// <returns></returns>
public async Task<Boolean> CheckProviderStatus()
{
if ( Object.ReferenceEquals(this.CurrentProvider, null ))
{
return false;
}
else
{
return await CheckProviderStatus(this.CurrentProvider.RecogEngineID);
}
}
/// <summary>
/// Get the a list of providers registered on the current gateway
/// </summary>
/// <returns>A list of provider information </returns>
public async Task<RecogEngine[]> GetActiveProviders()
{
try
{
var buf = await GetService("GetActiveProviders" );
try
{
var result = DecodeFromBytes<RecogEngine[]>(buf);
return result;
}
catch (Exception ex)
{
var errorString = String.Format("GetActiveProviders fails to decode the provider list from current gateway {0}...", this.CurrentGateway);
Debug.WriteLine(errorString);
ErrorMessage = errorString;
ExceptionMessage = ex.Message;
}
throw (new HttpRequestException(ErrorMessage));
}
catch (Exception ex)
{
var errorString = String.Format("Get GetActiveProviders fails, current gateway {0}, with exception {1}", this.CurrentGateway, ex);
Debug.WriteLine(errorString);
ErrorMessage = String.Format("Failed to retrieve provider list from current gateway {0}", this.CurrentGateway);
ExceptionMessage = ex.Message;
}
// Forcing checking gateway
var bGateway = await this.CheckGatewayStatus(true);
throw (new HttpRequestException(ErrorMessage));
}
/// <summary>
/// TODO: Write Comment
/// </summary>
/// <returns></returns>
public async Task<RecogInstance[]> GetWorkingInstances()
{
try
{
var engineName = Guid.Empty.ToString();
if (!Object.ReferenceEquals(CurrentProvider, null))
engineName = CurrentProvider.RecogEngineName;
var buf = await GetService(@"GetWorkingInstances/" + engineName);
try
{
var result = DecodeFromBytes<RecogInstance[]>(buf);
return result;
}
catch ( Exception ex)
{
var errorString = String.Format("Fails to decode the instance list from current gateway {0}, with engine {1}", this.CurrentGateway, engineName);
Debug.WriteLine(errorString);
ErrorMessage = errorString;
ExceptionMessage = ex.Message;
throw (new HttpRequestException(ErrorMessage));
}
}
catch (Exception ex)
{
var errorString = String.Format("Exception occurs when retrieving the instance list from gateway {0}", this.CurrentGateway);
Debug.WriteLine(errorString);
ErrorMessage = errorString;
ExceptionMessage = ex.Message;
}
var bGateway = await this.CheckGatewayStatus(true);
throw (new HttpRequestException(ErrorMessage));
}
/// <summary>
/// Check if a certain provider is live on the gateway
/// </summary>
/// <param name="providerID">Provider ID to be checked</param>
/// <returns>Liveness state </returns>
public async Task<Boolean> CheckInstanceStatus()
{
try
{
var domainID = Guid.Empty;
if (!Object.ReferenceEquals(CurrentDomain, null))
{
domainID = CurrentDomain.ServiceID;
}
var instanceLists = await GetWorkingInstances();
Boolean bExist = false;
foreach (var instance in instanceLists)
{
if (instance.ServiceID == domainID)
{
bExist = true;
}
}
if (!bExist)
{
ErrorMessage = String.Format("Instance {0} is not live on gateway {1} ... ", domainID, this.CurrentGateway);
}
return bExist;
}
catch (Exception ex)
{
var errorString = String.Format("Fails to retrieve instance list from gateway {0}...", this.CurrentGateway);
Debug.WriteLine(errorString);
ErrorMessage = errorString;
ExceptionMessage = ex.Message;
}
// Forcing checking gateway
var bGateway = await this.CheckGatewayStatus(true);
return false;
}
/// <summary>
/// Classify the image (stored in buf).
/// </summary>
/// <param name="providerID"> Guid that identifies service provider. </param>
/// <param name="schemaID"> Guid that identifies schema in use. </param>
/// <param name="domainID"> Guid that identifies service domain. </param>
/// <param name="distributionID"> Guid that identifies the distribution policy to be used.</param>
/// <param name="aggregationID"> Guid that identifies the aggregation policy to be used.</param>
/// <param name="buf"> Byte array that is the encoded image to be recognized, in .JPG format. </param>
/// <returns> A RecogReply structure which encapsultes information returned by the recognizer. </returns>
public async Task<RecogReply> ProcessAsync(Guid providerID, Guid schemaID, Guid domainID, Guid distributionID, Guid aggregationID, Byte[] buf)
{
try
{
var returnedInfo = await InvokeService("Process/" + providerID.ToString() + "/" + schemaID.ToString() + domainID.ToString() + distributionID.ToString() + aggregationID.ToString(), buf );
try
{
var result = DecodeFromBytes<RecogReply>(returnedInfo);
return result;
}
catch ( Exception )
{
var result = new RecogReply();
result.Description = String.Format("{0}B has returned from gateway {1}, but fails to parse the return message", returnedInfo.Length, this.CurrentGateway);
return result;
}
}
catch (Exception ex)
{
var errorString = String.Format("Fails to process a request from gateway {0} ... ", this.CurrentGateway);
Debug.WriteLine(errorString);
ErrorMessage = errorString;
ExceptionMessage = ex.Message;
}
// Forcing checking gateway
var bGateway = await this.CheckGatewayStatus(true);
throw (new HttpRequestException(ErrorMessage));
}
/// <summary>
/// Process a request, return only the description in the request.
/// </summary>
/// <param name="providerID"> Guid that identifies service provider. </param>
/// <param name="schemaID"> Guid that identifies schema in use. </param>
/// <param name="domainID"> Guid that identifies service domain. </param>
/// <param name="distributionID"> Guid that identifies the distribution policy to be used.</param>
/// <param name="aggregationID"> Guid that identifies the aggregation policy to be used.</param>
/// <param name="buf"> Byte array that is the encoded image to be recognized, in .JPG format. </param>
/// <returns> Description of the request. </returns>
public async Task<String> ProcessAsyncString(Guid providerID, Guid schemaID, Guid domainID, Guid distributionID, Guid aggregationID, Byte[] buf)
{
try
{
var reqService = "Process/" + providerID.ToString() + "/"
+ schemaID.ToString() + "/"
+ domainID.ToString() + "/"
+ distributionID.ToString() + "/"
+ aggregationID.ToString();
var returnedInfo = await InvokeService(reqService, buf);
var result = DecodeFromBytes<RecogReply>(returnedInfo);
if ( Object.ReferenceEquals(result, null ))
{
var returnLength = 0;
if (!Object.ReferenceEquals(returnedInfo,null))
{
returnLength = returnedInfo.Length;
}
return String.Format("Request service {0} of {1}B return {2}B.",
reqService, buf.Length, returnLength);
}
else
return result.Description;
}
catch (Exception e)
{
var errorString = String.Format("Get ClassifyServiceAsync fails, current gateway {0} with request of {1}B, with exception {2}",
this.CurrentGateway,
buf.Length,
e.Message);
Debug.WriteLine(errorString);
return errorString;
}
}
/// <summary>
/// Process a certain media request
/// </summary>
/// <param name="buf"></param>
/// <returns></returns>
public async Task<String> ProcessRequest( Byte[] buf )
{
var providerID = Guid.Empty;
if ( !Object.ReferenceEquals(CurrentProvider,null ))
{
providerID = CurrentProvider.RecogEngineID;
}
var domainID = Guid.Empty;
if ( !Object.ReferenceEquals(CurrentDomain, null))
{
domainID = CurrentDomain.ServiceID;
}
var result = await ProcessAsyncString(providerID, CurrentSchema, domainID, CurrentDistribution, CurrentAggregation, buf);
return result;
}
}
}
| |
using DevProLauncher.Config;
using DevProLauncher.Helpers;
using DevProLauncher.Network.Data;
using DevProLauncher.Network.Enums;
using DevProLauncher.Windows.Components;
using DevProLauncher.Windows.Enums;
using DevProLauncher.Windows.MessageBoxs;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
namespace DevProLauncher.Windows
{
public sealed partial class ChatFrm : Form
{
private Dictionary<string, List<UserData>> m_channelData = new Dictionary<string, List<UserData>>();
private readonly Dictionary<string, PmWindowFrm> m_pmWindows = new Dictionary<string, PmWindowFrm>();
private List<UserData> m_filterUsers;
public bool Autoscroll = true;
public bool Joinchannel = false;
private bool m_onlineMode;
private bool m_friendMode;
private Timer m_searchReset;
private bool m_autoJoined;
private LanguageInfo lang = Program.LanguageManager.Translation;
public ChatFrm()
{
InitializeComponent();
TopLevel = false;
Dock = DockStyle.Fill;
Visible = true;
m_searchReset = new Timer { Interval = 1000 };
m_filterUsers = new List<UserData>();
//chat packets
Program.ChatServer.UserListUpdate += UpdateUserList;
Program.ChatServer.UpdateUserInfo += UpdateUserInfo;
Program.ChatServer.FriendList += CreateFriendList;
Program.ChatServer.TeamList += CreateTeamList;
Program.ChatServer.JoinChannel += ChannelAccept;
Program.ChatServer.ChatMessage += WriteMessage;
Program.ChatServer.DuelRequest += HandleDuelRequest;
Program.ChatServer.TeamRequest += HandleTeamRequest;
Program.ChatServer.DuelAccepted += StartDuelRequest;
Program.ChatServer.DuelRefused += DuelRequestRefused;
Program.ChatServer.ChannelUserList += UpdateOrAddChannelList;
Program.ChatServer.AddUserToChannel += AddChannelUser;
Program.ChatServer.RemoveUserFromChannel += RemoveChannelUser;
//form events
ChannelTabs.SelectedIndexChanged += UpdateChannelList;
UserSearch.Enter += UserSearch_Enter;
UserSearch.Leave += UserSearch_Leave;
UserSearch.TextChanged += UserSearch_TextChanged;
UserListTabs.SelectedIndexChanged += UserSearch_Reset;
ChatInput.KeyPress += ChatInput_KeyPress;
ChannelList.DoubleClick += List_DoubleClick;
UserList.DoubleClick += List_DoubleClick;
m_searchReset.Tick += SearchTick;
ApplyOptionEvents();
ChannelList.MouseUp += UserList_MouseUp;
UserList.MouseUp += UserList_MouseUp;
IgnoreList.MouseUp += IgnoreList_MouseUp;
//custom form drawing
ChannelList.DrawItem += UserList_DrawItem;
UserList.DrawItem += UserList_DrawItem;
ChatHelper.LoadChatTags();
LoadIgnoreList();
ApplyTranslations();
ApplyChatSettings();
WriteSystemMessage(lang.chatMsg1);
WriteSystemMessage(lang.chatMsg2);
}
public void LoadDefaultChannel()
{
if (!string.IsNullOrEmpty(Program.Config.DefaultChannel) && !m_autoJoined)
{
ChatWindow channel = GetChatWindow(Program.Config.DefaultChannel);
if (channel == null)
{
Program.ChatServer.SendPacket(DevServerPackets.JoinChannel, Program.Config.DefaultChannel);
m_autoJoined = true;
}
}
}
private void SearchTick(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<object, EventArgs>(SearchTick), sender, e);
return;
}
if (userSearchBtn.Text == "1")
{
userSearchBtn.Enabled = true;
adminSearchBtn.Enabled = true;
teamSearchBtn.Enabled = true;
friendSearchBtn.Enabled = true;
userSearchBtn.Text = lang.chatBtnUser;
adminSearchBtn.Text = lang.chatBtnAdmin;
teamSearchBtn.Text = lang.chatBtnTeam;
friendSearchBtn.Text = lang.chatBtnFriend;
m_searchReset.Enabled = false;
}
else
{
int value = Int32.Parse(userSearchBtn.Text);
userSearchBtn.Text = (value - 1).ToString();
adminSearchBtn.Text = (value - 1).ToString();
teamSearchBtn.Text = (value - 1).ToString();
friendSearchBtn.Text = (value - 1).ToString();
}
}
private void EnableSearchReset()
{
UserListTab.Focus();
userSearchBtn.Enabled = false;
adminSearchBtn.Enabled = false;
teamSearchBtn.Enabled = false;
friendSearchBtn.Enabled = false;
userSearchBtn.Text = "5";
adminSearchBtn.Text = "5";
teamSearchBtn.Text = "5";
friendSearchBtn.Text = "5";
m_searchReset.Enabled = true;
}
private void ApplyOptionEvents()
{
foreach (var checkBox in tableLayoutPanel14.Controls.OfType<CheckBox>())
{
checkBox.CheckStateChanged += Option_CheckStateChanged;
}
foreach (FontFamily fontFamily in FontFamily.Families.Where(fontFamily => fontFamily.IsStyleAvailable(FontStyle.Regular)))
{
FontList.Items.Add(fontFamily.Name);
}
FontList.SelectedIndexChanged += FontSettings_Changed;
FontSize.ValueChanged += FontSettings_Changed;
}
public void ApplyChatSettings()
{
ChatInput.BackColor = Program.Config.ChatBGColor.ToColor();
ChatInput.ForeColor = Program.Config.NormalTextColor.ToColor();
UserSearch.BackColor = Program.Config.ChatBGColor.ToColor();
UserList.BackColor = Program.Config.ChatBGColor.ToColor();
ChannelList.BackColor = Program.Config.ChatBGColor.ToColor();
IgnoreList.BackColor = Program.Config.ChatBGColor.ToColor();
IgnoreList.ForeColor = Program.Config.NormalTextColor.ToColor();
BackgroundColorBtn.BackColor = Program.Config.ChatBGColor.ToColor();
NormalTextColorBtn.BackColor = Program.Config.NormalTextColor.ToColor();
BotColorBtn.BackColor = Program.Config.BotColor.ToColor();
Level4ColorBtn.BackColor = Program.Config.Level4Color.ToColor();
Level3ColorBtn.BackColor = Program.Config.Level3Color.ToColor();
Level2ColorBtn.BackColor = Program.Config.Level2Color.ToColor();
Level1ColorBtn.BackColor = Program.Config.Level1Color.ToColor();
NormalUserColorBtn.BackColor = Program.Config.Level0Color.ToColor();
ServerColorBtn.BackColor = Program.Config.ServerMsgColor.ToColor();
MeColorBtn.BackColor = Program.Config.MeMsgColor.ToColor();
JoinColorBtn.BackColor = Program.Config.JoinColor.ToColor();
LeaveColorBtn.BackColor = Program.Config.LeaveColor.ToColor();
SystemColorBtn.BackColor = Program.Config.SystemColor.ToColor();
HideJoinLeavechk.Checked = Program.Config.HideJoinLeave;
Colorblindchk.Checked = Program.Config.ColorBlindMode;
Timestampchk.Checked = Program.Config.ShowTimeStamp;
DuelRequestchk.Checked = Program.Config.RefuseDuelRequests;
pmwindowchk.Checked = Program.Config.PmWindows;
usernamecolorchk.Checked = Program.Config.UsernameColors;
refuseteamchk.Checked = Program.Config.RefuseTeamInvites;
if (!string.IsNullOrEmpty(Program.Config.ChatFont))
{
if (FontList.Items.Contains(Program.Config.ChatFont))
{
FontList.SelectedItem = Program.Config.ChatFont;
}
}
FontSize.Value = Program.Config.ChatSize;
}
public void ApplyTranslations()
{
//options
groupBox7.Text = lang.chatoptionsGb2;
groupBox5.Text = lang.chatoptionsGb3;
HideJoinLeavechk.Text = lang.chatoptionsLblHideJoinLeave;
pmwindowchk.Text = lang.chatoptionsLblPmWindows;
Colorblindchk.Text = lang.chatoptionsLblColorBlindMode;
usernamecolorchk.Text = lang.chatoptionsLblUserColors;
refuseteamchk.Text = lang.chatoptionsLblRefuseTeamInvites;
Timestampchk.Text = lang.chatoptionsLblShowTimeStamp;
DuelRequestchk.Text = lang.chatoptionsLblRefuseDuelRequests;
groupBox1.Text = lang.chatoptionsFontTitle;
label1.Text = lang.chatoptionsFontLbl;
label2.Text = lang.chatoptionsFontSize;
label13.Text = lang.chatoptionsLblChatBackground;
label12.Text = lang.chatoptionsLblNormalText;
label11.Text = lang.chatoptionsLblLevel98;
//label10.Text = lang.chatoptionsLblLevel2;
label9.Text = lang.chatoptionsLblLevel1;
label4.Text = lang.chatoptionsLblNormalUser;
label7.Text = lang.chatoptionsLblServerMessages;
label8.Text = lang.chatoptionsLblMeMessage;
label14.Text = lang.chatoptionsLblJoin;
label15.Text = lang.chatoptionsLblLeave;
label16.Text = lang.chatoptionsLblSystem;
userSearchBtn.Text = lang.chatBtnUser;
adminSearchBtn.Text = lang.chatBtnAdmin;
teamSearchBtn.Text = lang.chatBtnTeam;
friendSearchBtn.Text = lang.chatBtnFriend;
ChannelListBtn.Text = lang.chatBtnChannel;
LeaveBtn.Text = lang.chatBtnLeave;
UserTab.Text = lang.chatUserTab;
IgnoreTab.Text = lang.chatIgnoreTab;
OptionsTab.Text = lang.chatOptionTab;
ChannelTab.Text = lang.chatChannelTab;
UserListTab.Text = lang.chatUserListTab;
}
public void LoadIgnoreList()
{
string[] users = Program.Config.IgnoreList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string user in users)
{
IgnoreList.Items.Add(user.ToLower());
}
}
private void JoinChannel(string channel)
{
Program.ChatServer.SendPacket(DevServerPackets.JoinChannel, channel);
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo, "System", "Join request for " + channel + " has been sent."));
}
private void LeaveChannel(string channel)
{
Program.ChatServer.SendPacket(DevServerPackets.LeaveChannel, channel);
if (GetChatWindow(channel) != null)
{
ChannelTabs.TabPages.Remove(GetChatWindow(channel));
Program.Config.ChatChannels.Remove(channel);
Program.SaveConfig(Program.ConfigurationFilename, Program.Config);
}
}
private void ChannelAccept(string channel)
{
if (InvokeRequired)
{
Invoke(new Action<string>(ChannelAccept), channel);
return;
}
if (GetChatWindow(channel) == null)
{
ChannelTabs.TabPages.Add(new ChatWindow(channel, false));
ChannelTabs.SelectedTab = GetChatWindow(channel);
if (!Program.Config.ChatChannels.Contains(channel))
{
Program.Config.ChatChannels.Add(channel);
Program.SaveConfig(Program.ConfigurationFilename, Program.Config);
}
}
if (!string.IsNullOrEmpty(Program.UserInfo.team) && GetChatWindow(MessageType.Team.ToString()) == null)
{
ChannelTabs.TabPages.Add(new ChatWindow(MessageType.Team.ToString(), false));
}
WriteMessage(new ChatMessage(MessageType.Server, CommandType.None, Program.UserInfo, "Server", "Join request for " + channel + " accepted."));
if (!Joinchannel)
{
Joinchannel = true;
if (GetChatWindow(MessageType.System.ToString()) != null)
{
ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.System.ToString()));
}
}
}
public void WriteMessage(ChatMessage message)
{
if (InvokeRequired)
{
Invoke(new Action<ChatMessage>(WriteMessage), message);
return;
}
if (message.from != null && IgnoreUser(message.from))
{
return;
}
ChatWindow window;
if ((MessageType)message.type == MessageType.Server || (MessageType)message.type == MessageType.System)
{
window = (ChatWindow)ChannelTabs.SelectedTab;
if (window == null)
{
window = new ChatWindow(((MessageType)message.type).ToString(), true) { IsSystemtab = true };
ChannelTabs.TabPages.Add(window);
window.WriteMessage(message, Autoscroll);
}
else window.WriteMessage(message, Autoscroll);
}
else if ((MessageType)message.type == MessageType.Join || (MessageType)message.type == MessageType.Leave || message.channel == null)
{
window = GetChatWindow(message.channel) ?? (ChatWindow)ChannelTabs.SelectedTab;
if (window == null)
{
window = new ChatWindow(message.type.ToString(CultureInfo.InvariantCulture), true) { IsSystemtab = true };
ChannelTabs.TabPages.Add(window);
window.WriteMessage(message, Autoscroll);
}
else window.WriteMessage(message, Autoscroll);
}
else if ((MessageType)message.type == MessageType.PrivateMessage && Program.Config.PmWindows)
{
if (m_pmWindows.ContainsKey(message.channel))
{
m_pmWindows[message.channel].WriteMessage(message);
}
else
{
m_pmWindows.Add(message.channel, new PmWindowFrm(message.channel, true));
m_pmWindows[message.channel].WriteMessage(message);
m_pmWindows[message.channel].Show();
m_pmWindows[message.channel].FormClosed += Chat_frm_FormClosed;
}
}
else if ((MessageType)message.type == MessageType.Team)
{
window = GetChatWindow(((MessageType)message.type).ToString());
if (window == null)
{
window = new ChatWindow(((MessageType)message.type).ToString(), (MessageType)message.type == MessageType.PrivateMessage);
ChannelTabs.TabPages.Add(window);
window.WriteMessage(message, Autoscroll);
}
else window.WriteMessage(message, Autoscroll);
}
else
{
window = GetChatWindow(message.channel);
if (window == null)
{
window = new ChatWindow(message.channel, (MessageType)message.type == MessageType.PrivateMessage);
ChannelTabs.TabPages.Add(window);
}
window.WriteMessage(message, Autoscroll);
}
}
public bool IgnoreUser(UserData user)
{
return IgnoreList.Items.Contains(user.username.ToLower()) && user.rank < 1;
}
public void WriteSystemMessage(string message)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, message));
}
private ChatWindow GetChatWindow(string name)
{
return ChannelTabs.TabPages.Cast<ChatWindow>().FirstOrDefault(x => x.Name == name);
}
private void Chat_frm_FormClosed(object sender, EventArgs e)
{
m_pmWindows.Remove(((PmWindowFrm)sender).Name);
}
private void UserSearch_Enter(object sender, EventArgs e)
{
if (UserSearch.Text == "Search")
{
UserSearch.ForeColor = Program.Config.NormalTextColor.ToColor();
UserSearch.Text = "";
}
}
private void UserSearch_Leave(object sender, EventArgs e)
{
if (UserSearch.Text == "")
{
UserSearch.ForeColor = SystemColors.WindowFrame;
UserSearch.Text = "Search";
}
}
private void UserSearch_Reset(object sender, EventArgs e)
{
UserSearch.ForeColor = SystemColors.WindowFrame;
UserSearch.Text = "Search";
}
private void UserSearch_TextChanged(object sender, EventArgs e)
{
if (UserListTabs.SelectedTab.Name == ChannelTab.Name)
{
ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab;
if (window != null)
{
if (m_channelData.ContainsKey(window.Name))
{
IEnumerable<UserData> users = m_channelData[window.Name];
if (!string.IsNullOrEmpty(UserSearch.Text) && UserSearch.ForeColor != SystemColors.WindowFrame)
{
users = users.Where(user => user.username.ToLower().Contains(UserSearch.Text.ToLower()));
}
ChannelList.Items.Clear();
ChannelList.Items.AddRange(users.ToArray<object>());
}
}
}
else
{
if (!string.IsNullOrEmpty(UserSearch.Text) && UserSearch.ForeColor != SystemColors.WindowFrame)
{
UserList.Items.Clear();
foreach (UserData user in m_filterUsers)
{
if (user.username.ToLower().Contains(UserSearch.Text.ToLower()))
UserList.Items.Add(user);
}
}
else
{
UserList.Items.Clear();
UserList.Items.AddRange(m_filterUsers.ToArray());
}
}
}
private void UpdateUserInfo(UserData user)
{
Program.UserInfo = user;
Program.MainForm.UpdateUsername();
if (!string.IsNullOrEmpty(Program.UserInfo.team))
LoadTeamWindow();
}
private void UpdateChannelList(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<object, EventArgs>(UpdateChannelList), sender, e);
return;
}
ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab;
if (window != null)
{
if (m_channelData.ContainsKey(window.Name))
{
List<UserData> users = m_channelData[window.Name];
ChannelList.Items.Clear();
ChannelList.Items.AddRange(users.ToArray());
}
}
else
{
ChannelList.Items.Clear();
}
}
private void UpdateOrAddChannelList(ChannelUsers users)
{
if (m_channelData.ContainsKey(users.Name))
m_channelData[users.Name] = new List<UserData>(users.Users);
else
m_channelData.Add(users.Name, new List<UserData>(users.Users));
UpdateChannelList(this, EventArgs.Empty);
}
private void AddOrRemoveChannelUser(UserData channelUser, bool remove)
{
if (InvokeRequired)
{
Invoke(new Action<UserData, bool>(AddOrRemoveChannelUser), channelUser, remove);
return;
}
UserData toRemove = null;
foreach (UserData user in ChannelList.Items)
{
if (user.username == channelUser.username)
toRemove = user;
}
if (toRemove != null)
ChannelList.Items.Remove(toRemove);
if (!remove)
{
ChannelList.Items.Add(channelUser);
}
}
private void AddChannelUser(ChannelUsers user)
{
if (InvokeRequired)
{
Invoke(new Action<ChannelUsers>(AddChannelUser), user);
return;
}
if (m_channelData.ContainsKey(user.Name))
{
UserData founduser = null;
foreach (UserData channeluser in m_channelData[user.Name])
{
if (channeluser.username == user.Users[0].username)
founduser = channeluser;
}
if (founduser == null)
m_channelData[user.Name].Add(user.Users[0]);
else
{
m_channelData[user.Name].Remove(founduser);
m_channelData[user.Name].Add(user.Users[0]);
}
}
ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab;
if (window != null)
{
if (user.Name == window.Name)
AddOrRemoveChannelUser(user.Users[0], false);
}
}
private void RemoveChannelUser(ChannelUsers user)
{
if (InvokeRequired)
{
Invoke(new Action<ChannelUsers>(RemoveChannelUser), user);
return;
}
if (m_channelData.ContainsKey(user.Name))
{
UserData founduser = null;
foreach (UserData channeluser in m_channelData[user.Name])
{
if (channeluser.username == user.Users[0].username)
founduser = channeluser;
}
if (founduser != null)
m_channelData[user.Name].Remove(founduser);
}
ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab;
if (window != null)
{
if (user.Name == window.Name)
AddOrRemoveChannelUser(user.Users[0], true);
}
}
private void UpdateUserList(UserData[] userlist)
{
if (InvokeRequired)
{
Invoke(new Action<UserData[]>(UpdateUserList), (object)userlist);
return;
}
m_onlineMode = false;
m_friendMode = false;
UserList.Items.Clear();
UserList.Items.AddRange(userlist);
m_filterUsers.Clear();
m_filterUsers.AddRange(userlist);
}
private void LoadTeamWindow()
{
if (InvokeRequired)
{
Invoke(new Action(LoadTeamWindow));
return;
}
if (GetChatWindow(MessageType.Team.ToString()) == null)
{
ChannelTabs.TabPages.Add(new ChatWindow(MessageType.Team.ToString(), false));
}
}
public void CreateFriendList(UserData[] friends)
{
if (InvokeRequired)
{
Invoke(new Action<UserData[]>(CreateFriendList), (object)friends);
return;
}
m_friendMode = true;
m_onlineMode = true;
UserList.Items.Clear();
UserList.Items.AddRange(friends);
m_filterUsers.Clear();
m_filterUsers.AddRange(friends);
}
public void CreateTeamList(UserData[] users)
{
if (InvokeRequired)
{
Invoke(new Action<UserData[]>(CreateTeamList), (object)users);
return;
}
m_onlineMode = true;
UserList.Items.Clear();
UserList.Items.AddRange(users);
m_filterUsers.Clear();
m_filterUsers.AddRange(users);
}
private void UserList_DrawItem(object sender, DrawItemEventArgs e)
{
ListBox list = (ListBox)sender;
e.DrawBackground();
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
int index = e.Index;
if (index == -1)
return;
if (index < 0 && index >= list.Items.Count)
{
e.DrawFocusRectangle();
return;
}
UserData user = (UserData)list.Items[index];
Graphics g = e.Graphics;
g.FillRectangle((selected) ? (Program.Config.ColorBlindMode ? new SolidBrush(Color.Black) : new SolidBrush(Color.Blue)) : new SolidBrush(Program.Config.ChatBGColor.ToColor()), e.Bounds);
if (!m_onlineMode)
{
if (user.usertag != "" || user.rank > 0 && user.rank < 99)
{
// Print text
g.DrawString("[", e.Font,
(selected)
? Brushes.White
: (Program.Config.ColorBlindMode
? Brushes.Black
: new SolidBrush(Program.Config.NormalTextColor.ToColor())),
list.GetItemRectangle(index).Location);
string title;
title = user.usertag;
//switch (user.rank)
//{
// case 1:
// title = "Helper";
// break;
// case 2:
// title = "TD";
// break;
// case 3:
// title = "Mod";
// break;
// case 4:
// title = "SMod";
// break;
// case 98:
// title = "Bot";
// break;
// /*
// case 99:
// title = "Dev";
// break;
// //*/
// default:
// title = user.usertag;
// break;
//}
g.DrawString(title, e.Font,
(selected)
? Brushes.White
: (Program.Config.ColorBlindMode
? Brushes.Black
: ChatMessage.GetUserColor(user.rank)),
new Point(
list.GetItemRectangle(index).Location.X +
(int)g.MeasureString("[", e.Font).Width - 1,
list.GetItemRectangle(index).Location.Y));
g.DrawString("]", e.Font,
(selected)
? Brushes.White
: (Program.Config.ColorBlindMode
? Brushes.Black
: new SolidBrush(Program.Config.NormalTextColor.ToColor())),
new Point(
list.GetItemRectangle(index).Location.X +
(int)g.MeasureString("[" + title, e.Font).Width,
list.GetItemRectangle(index).Location.Y));
if (user.getUserColor().ToArgb() == Color.Black.ToArgb())
{
g.DrawString(user.username, e.Font,
(selected)
? Brushes.White
: (Program.Config.ColorBlindMode
? Brushes.Black
: new SolidBrush(Program.Config.NormalTextColor.ToColor())),
new Point(
list.GetItemRectangle(index).Location.X +
(int)g.MeasureString("[" + title + "]", e.Font).Width,
list.GetItemRectangle(index).Location.Y));
}
else
{
g.DrawString(user.username, e.Font,
(selected)
? Brushes.White
: (Program.Config.ColorBlindMode
? Brushes.Black
: new SolidBrush(user.getUserColor())),
new Point(
list.GetItemRectangle(index).Location.X +
(int)g.MeasureString("[" + title + "]", e.Font).Width,
list.GetItemRectangle(index).Location.Y));
}
}
else
{
if (user.getUserColor().ToArgb() == Color.Black.ToArgb())
{
// Print text
g.DrawString(user.username, e.Font,
(selected)
? Brushes.White
: (Program.Config.ColorBlindMode
? Brushes.Black
: new SolidBrush(Program.Config.NormalTextColor.ToColor())),
list.GetItemRectangle(index).Location);
}
else
{
// Print text
g.DrawString(user.username, e.Font,
(selected)
? Brushes.White
: (Program.Config.ColorBlindMode
? Brushes.Black
: new SolidBrush(user.getUserColor())),
list.GetItemRectangle(index).Location);
}
}
}
else
{
//// Print text
g.DrawString((Program.Config.ColorBlindMode ? (user.Online ? user.username + " (Online)" : user.username + " (Offline)") : user.username), e.Font,
(selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : (user.Online ? Brushes.Green : Brushes.Red)),
list.GetItemRectangle(index).Location);
}
e.DrawFocusRectangle();
}
private void ApplyNewColor(object sender, EventArgs e)
{
var button = (Button)sender;
var selectcolor = new ColorDialog
{
Color = button.BackColor,
AllowFullOpen = true
};
if (selectcolor.ShowDialog() == DialogResult.OK)
{
switch (button.Name)
{
case "BackgroundColorBtn":
Program.Config.ChatBGColor = new SerializableColor(selectcolor.Color);
break;
case "SystemColorBtn":
Program.Config.SystemColor = new SerializableColor(selectcolor.Color);
break;
case "LeaveColorBtn":
Program.Config.LeaveColor = new SerializableColor(selectcolor.Color);
break;
case "JoinColorBtn":
Program.Config.JoinColor = new SerializableColor(selectcolor.Color);
break;
case "MeColorBtn":
Program.Config.MeMsgColor = new SerializableColor(selectcolor.Color);
break;
case "ServerColorBtn":
Program.Config.ServerMsgColor = new SerializableColor(selectcolor.Color);
break;
case "NormalUserColorBtn":
Program.Config.Level0Color = new SerializableColor(selectcolor.Color);
break;
case "Level1ColorBtn":
Program.Config.Level1Color = new SerializableColor(selectcolor.Color);
break;
case "Level2ColorBtn":
Program.Config.Level2Color = new SerializableColor(selectcolor.Color);
break;
case "Level3ColorBtn":
Program.Config.Level3Color = new SerializableColor(selectcolor.Color);
break;
case "Level4ColorBtn":
Program.Config.Level4Color = new SerializableColor(selectcolor.Color);
break;
case "BotColorBtn":
Program.Config.BotColor = new SerializableColor(selectcolor.Color);
break;
case "NormalTextColorBtn":
Program.Config.NormalTextColor = new SerializableColor(selectcolor.Color);
break;
}
button.BackColor = selectcolor.Color;
Program.SaveConfig(Program.ConfigurationFilename, Program.Config);
ApplyChatSettings();
}
}
private bool HandleCommand(string part, ChatWindow selectedTab)
{
var cmd = part.Substring(1).ToLower();
switch (cmd)
{
case "me":
if (selectedTab == null)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "No channel Selected."));
return false;
}
var isTeam = selectedTab.Name == MessageType.Team.ToString();
Program.ChatServer.SendMessage(isTeam ? MessageType.Team : MessageType.Message, CommandType.Me, selectedTab.Name, ChatInput.Text.Substring(part.Length).Trim());
break;
case "join":
JoinChannel(ChatInput.Text.Substring(part.Length).Trim());
break;
case "leave":
if (selectedTab == null)
{
return false;
}
if (selectedTab.IsPrivate)
{
ChannelTabs.TabPages.Remove(selectedTab);
}
else
{
LeaveChannel(selectedTab.Name);
}
break;
case "ping":
Program.ChatServer.SendPacket(DevServerPackets.Ping);
break;
case "autoscroll":
Autoscroll = !Autoscroll;
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, (Autoscroll ? "AutoScroll Enabled." : "AutoScroll Disabled.")));
break;
case "help":
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Basic Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/me - Displays Username, and then your Message"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/join - Joins another channel"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/leave - Leaves the channel you're currently in"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/autoscroll - Enable/Disable autoscroll"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ping - Ping the server"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/help - Displays the list you're reading now"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/uptime - Displays how long the server has been online"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/stats - Shows how many users are online, dueling, and how many duels"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/mute username hours - (Channel Owners/Admins) Prevents a user from sending any messages in a certain channel for a certain amount of hours."));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/unmute username - (Channel Owners/Admins) Allows a muted user to send messages again"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/setmotd message - (Channel Owners/Admins) Sets a message of the day that is sent to users when they join the channel."));
if (Program.UserInfo.rank == 1)
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, " -- Level 1 users are classed as helpers and don't need any extra commands"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/msg - Sends a server message"));
if (Program.UserInfo.rank > 1)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- TD Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/kick username reason - Kicks a user"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/msg - Sends a server message"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/smsg - Sends a launcher message which is displayed on the bottom of the launcher"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getaccounts username - Gets a list of accounts for the the inputted username"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/cmute roomname - Mutes a room so that only admins can speak"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/cunmute roomname - Unmutes a room that was muted."));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/roomowner roomname - Gets the creator of a channel"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/killroom roomname - forces a chat channel to close"));
}
if (Program.UserInfo.rank > 2)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Mod Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getuid username - Gets the UID of a username"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/gmute username hours - Globally mutes a user for X hours. ( if hours is empty, it's 24hours )"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/gunmute username - Unmutes a user that was muted globally"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/gumuteall - Clears all GMutes"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/info username - Gives info of an user."));
}
if (Program.UserInfo.rank > 3)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- SMod Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/shutdown [false]/[forced] servername - instructs the duel server to shutdown. If 'forced' is added: Does not wait for games to finish. Do not use false if you use Forced."));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/restart [false]/[forced] servername - instructs the duel server to restart. If 'forced' is added: Does not wait for games to finish. Do not use false if you use Forced."));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/kill [forced]- Kills all crashed cores. If 'forced' is added: Kills all cores (including running games)."));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ban username time reason - Bans a user, time format has to be in hours (max 730 hours), also you must give a reason."));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/banusername username - Bans a user's username"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getservers - Gives duel servers listed"));
}
if (Program.UserInfo.rank == 99)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team Leader Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ban username time reason - Bans a user, time format has to be in hours, also you must give a reason."));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/unban username - Unbans a user"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ip username - Gets a users IP"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/banip ip - Bans an IP"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/unbanip ip - Unbans IP"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getbanlist - Gets ban list"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/op username level - Sets a users level"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/setmps number - Changes the messages per second"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/addpoints username amount - Adds DevPoints to the given username"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/removepoints username amount - Removes DevPoints to the given username"));
}
if (Program.UserInfo.teamRank >= 0 && Program.UserInfo.team != string.Empty)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/leaveteam - leaves the team"));
}
if (Program.UserInfo.teamRank >= 1)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team User Level 1 Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamadd username - adds a user to the team"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamremove username - removes a user from the team"));
}
if (Program.UserInfo.teamRank == 99)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team User Level 99 Commands --"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamdisband - disbands the team"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamop username level - promotes a user in the team"));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamchangeleader username - changes the leader of a team"));
}
break;
case "teamdisband":
if (MessageBox.Show("Are you sure?", "Confirm team disband", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() }));
}
break;
case "setmotd":
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() + "|" + ChannelTabs.SelectedTab.Text }));
break;
case "mute":
case "unmute":
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() + "|" + ChannelTabs.SelectedTab.Text }));
break;
case "info":
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() + "|" + ChannelTabs.SelectedTab.Text }));
break;
default:
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() }));
break;
}
return true;
}
private void ChatInput_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 13 || string.IsNullOrWhiteSpace(ChatInput.Text))
{
return;
}
string[] parts = ChatInput.Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var selectedTab = (ChatWindow)ChannelTabs.SelectedTab;
if (parts[0].StartsWith("/"))
{
if (!HandleCommand(parts[0], selectedTab))
{
return;
}
}
else
{
if (selectedTab == null)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "No channel Selected."));
return;
}
if (selectedTab.IsSystemtab)
{
ChatInput.Clear();
return;
}
if (selectedTab.IsPrivate)
{
WriteMessage(new ChatMessage(MessageType.PrivateMessage, CommandType.None, Program.UserInfo, selectedTab.Name, ChatInput.Text));
Program.ChatServer.SendMessage(MessageType.PrivateMessage, CommandType.None, selectedTab.Name, ChatInput.Text);
}
else
{
var isTeam = selectedTab.Name == MessageType.Team.ToString();
Program.ChatServer.SendMessage(isTeam ? MessageType.Team : MessageType.Message, CommandType.None, selectedTab.Name, ChatInput.Text);
}
}
ChatInput.Clear();
e.Handled = true;
}
private void Option_CheckStateChanged(object sender, EventArgs e)
{
var check = (CheckBox)sender;
switch (check.Name)
{
case "Colorblindchk":
Program.Config.ColorBlindMode = check.Checked;
break;
case "Timestampchk":
Program.Config.ShowTimeStamp = check.Checked;
break;
case "DuelRequestchk":
Program.Config.RefuseDuelRequests = check.Checked;
break;
case "HideJoinLeavechk":
Program.Config.HideJoinLeave = check.Checked;
break;
case "usernamecolorchk":
Program.Config.UsernameColors = usernamecolorchk.Checked;
break;
case "refuseteamchk":
Program.Config.RefuseTeamInvites = refuseteamchk.Checked;
break;
case "pmwindowchk":
Program.Config.PmWindows = check.Checked;
if (Program.Config.PmWindows)
{
ChannelTabs.TabPages
.Cast<ChatWindow>()
.Where(x => x.IsPrivate)
.ToList()
.ForEach(window => ChannelTabs.TabPages.Remove(window));
}
else
{
m_pmWindows.Values.ToList().ForEach(x => x.Close());
}
break;
}
Program.SaveConfig(Program.ConfigurationFilename, Program.Config);
}
private void UserList_MouseUp(object sender, MouseEventArgs e)
{
ListBox list = (ListBox)sender;
if (e.Button == MouseButtons.Right)
{
int index = list.IndexFromPoint(e.Location);
if (index == -1)
{
return;
}
list.SelectedIndex = index;
if (list.SelectedItem == null)
{
return;
}
ContextMenuStrip mnu = new ContextMenuStrip();
ToolStripMenuItem mnuprofile = new ToolStripMenuItem(Program.LanguageManager.Translation.chatViewProfile);
ToolStripMenuItem mnuduel = new ToolStripMenuItem(Program.LanguageManager.Translation.chatRequestDuel);
ToolStripMenuItem mnufriend = new ToolStripMenuItem(Program.LanguageManager.Translation.chatAddFriend);
ToolStripMenuItem mnuignore = new ToolStripMenuItem(Program.LanguageManager.Translation.chatIgnoreUser);
ToolStripMenuItem mnukick = new ToolStripMenuItem(Program.LanguageManager.Translation.chatKick);
ToolStripMenuItem mnmute = new ToolStripMenuItem(Program.LanguageManager.Translation.chatMute);
ToolStripMenuItem mnuban = new ToolStripMenuItem(Program.LanguageManager.Translation.chatBan);
ToolStripMenuItem mnuremovefriend = new ToolStripMenuItem(Program.LanguageManager.Translation.chatRemoveFriend);
ToolStripMenuItem mnuremoveteam = new ToolStripMenuItem(Program.LanguageManager.Translation.chatTeamRemove);
ToolStripMenuItem mnuspectateuser = new ToolStripMenuItem(Program.LanguageManager.Translation.chatSpectate);
mnukick.Click += KickUser;
mnmute.Click += MuteUser;
mnuban.Click += BanUser;
mnuprofile.Click += ViewProfile;
mnuduel.Click += RequestDuel;
mnufriend.Click += AddFriend;
mnuignore.Click += IgnoreUser;
mnuremovefriend.Click += RemoveFriend;
mnuremoveteam.Click += RemoveFromTeam;
mnuspectateuser.Click += SpectateUser;
if (!m_onlineMode)
{
mnu.Items.AddRange(new ToolStripItem[] { mnuprofile, mnuduel, mnuspectateuser, mnufriend, mnuignore });
if (Program.UserInfo.rank > 1)
mnu.Items.Add(mnukick);
if (Program.UserInfo.rank > 3)
mnu.Items.Add(mnuban);
if (Program.UserInfo.rank > 1)
mnu.Items.Add(mnmute);
}
else
{
UserData user = (UserData)list.SelectedItem;
mnu.Items.Add(mnuprofile);
if (user.Online)
{
mnu.Items.AddRange(new ToolStripItem[] { mnuduel, mnuspectateuser });
}
if (m_friendMode)
mnu.Items.Add(mnuremovefriend);
else
{
if (Program.UserInfo.teamRank > 0)
mnu.Items.Add(mnuremoveteam);
}
}
mnu.Show(list, e.Location);
}
}
private void BanUser(object sender, EventArgs e)
{
ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList;
/*
if (list.SelectedItem != null && MessageBox.Show("Are you sure you want to ban " + ((UserData)list.SelectedItem).username, "Ban User", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(
new PacketCommand { Command = "BAN", Data = ((UserData)list.SelectedItem).username }));
}
*/
var input = new BanFrm(Program.LanguageManager.Translation.banTitle,
Program.LanguageManager.Translation.banMessageLbl,
Program.LanguageManager.Translation.banTimeLbl,
Program.LanguageManager.Translation.banReasonLbl,
Program.LanguageManager.Translation.banConfirm,
Program.LanguageManager.Translation.banCancel);
if ((!(list.SelectedItems.Count > 1)))
{
if ((input.ShowDialog() == DialogResult.OK))
{
try
{
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(
new PacketCommand { Command = "BAN", Data = ((UserData)list.SelectedItem).username + " " + input.inputBox1.Text + " " + input.inputBox2.Text }));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void KickUser(object sender, EventArgs e)
{
ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList;
if (list.SelectedItem == null)
{
return;
}
/*
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(
new PacketCommand { Command = "KICK", Data = ((UserData)list.SelectedItem).username }));
*/
var input = new BanFrm(Program.LanguageManager.Translation.kickTitle,
Program.LanguageManager.Translation.kickMessageLbl,
Program.LanguageManager.Translation.kickReasonLbl,
"",
Program.LanguageManager.Translation.kickConfirm,
Program.LanguageManager.Translation.kickCancel);
input.inputBox2.Visible = false;
if ((!(list.SelectedItems.Count > 1)))
{
if ((input.ShowDialog() == DialogResult.OK))
{
try
{
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(
new PacketCommand { Command = "KICK", Data = ((UserData)list.SelectedItem).username + " " + input.inputBox1.Text }));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void MuteUser(object sender, EventArgs e)
{
ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList;
var input = new BanFrm(Program.LanguageManager.Translation.muteTitle,
Program.LanguageManager.Translation.muteMessageLbl,
Program.LanguageManager.Translation.muteTimeLbl,
Program.LanguageManager.Translation.muteReasonLbl,
Program.LanguageManager.Translation.muteConfirm,
Program.LanguageManager.Translation.muteCancel);
if ((!(list.SelectedItems.Count > 1)))
{
if ((input.ShowDialog() == DialogResult.OK))
{
try
{
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(
new PacketCommand { Command = "MUTE", Data = ((UserData)list.SelectedItem).username + " " + input.inputBox1.Text + " " + input.inputBox2.Text + "|" + ChannelTabs.SelectedTab.Text }));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void SpectateUser(object sender, EventArgs e)
{
ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList;
if (list.SelectedItem == null)
return;
Program.ChatServer.SendPacket(DevServerPackets.SpectateUser, ((UserData)list.SelectedItem).username);
}
private void AddFriend(object sender, EventArgs e)
{
ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList;
if (list.SelectedItem == null)
return;
if (((UserData)list.SelectedItem).username == Program.UserInfo.username)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You cannot be your own friend."));
return;
}
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)list.SelectedItem).username + " has been added to your friend list."));
Program.ChatServer.SendPacket(DevServerPackets.AddFriend, ((UserData)list.SelectedItem).username);
}
private void IgnoreUser(object sender, EventArgs e)
{
ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList;
if (((UserData)list.SelectedItem).username == Program.UserInfo.username)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You cannot ignore yourself."));
return;
}
if (IgnoreList.Items.Contains(((UserData)list.SelectedItem).username.ToLower()))
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)list.SelectedItem).username + " is already on your ignore list."));
return;
}
IgnoreList.Items.Add(((UserData)list.SelectedItem).username.ToLower());
SaveIgnoreList();
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)list.SelectedItem).username + " has been added to your ignore list."));
}
private void RemoveFromTeam(object sender, EventArgs e)
{
if (UserList.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show("Are you sure?", "Remove User", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Program.ChatServer.SendPacket(DevServerPackets.ChatCommand,
JsonSerializer.SerializeToString(new PacketCommand { Command = "TEAMREMOVE", Data = ((UserData)UserList.SelectedItem).username }));
}
}
private void RemoveFriend(object sender, EventArgs e)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)UserList.SelectedItem).username + " has been removed from your friendlist."));
Program.ChatServer.SendPacket(DevServerPackets.RemoveFriend, ((UserData)UserList.SelectedItem).username);
UserList.Items.Remove(UserList.SelectedItem);
}
private void ViewProfile(object sender, EventArgs e)
{
ListBox list = (UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList);
if (list.SelectedItem == null)
return;
var profile = new ProfileFrm(list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username);
profile.ShowDialog();
}
private void RequestDuel(object sender, EventArgs e)
{
ListBox list = (UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList);
if (list.SelectedItem == null)
{
return;
}
if ((list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username) == Program.UserInfo.username)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You cannot duel request your self."));
}
else
{
var form = new Host();
ServerInfo server = Program.MainForm.GameWindow.GetServer(false);
if (server == null)
{
MessageBox.Show("No Server Available.");
return;
}
Program.ChatServer.SendPacket(DevServerPackets.RequestDuel,
JsonSerializer.SerializeToString(
new DuelRequest
{
username = list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username,
duelformatstring = form.GenerateURI(false),
server = server.serverName
}));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "Duel request sent to " + (list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username) + "."));
}
}
private void HandleDuelRequest(DuelRequest command)
{
if (InvokeRequired)
{
Invoke(new Action<DuelRequest>(HandleDuelRequest), command);
return;
}
if (Program.Config.RefuseDuelRequests || IgnoreList.Items.Contains(command.username.ToLower()))
{
Program.ChatServer.SendPacket(DevServerPackets.RefuseDuel);
return;
}
RoomInfos info = RoomInfos.FromName(command.duelformatstring);
var request = new DuelRequestFrm(
command.username
+ Program.LanguageManager.Translation.DuelReqestMessage
+ Environment.NewLine
+ Program.LanguageManager.Translation.DuelRequestMode
+ RoomInfos.GameMode(info.mode)
+ Program.LanguageManager.Translation.DuelRequestRules
+ RoomInfos.GameRule(info.rule)
+ Program.LanguageManager.Translation.DuelRequestBanlist
+ LauncherHelper.GetBanListFromInt(info.banListType));
if (request.ShowDialog() == DialogResult.Yes)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You accepted " + command.username + " duel request."));
Program.ChatServer.SendPacket(DevServerPackets.AcceptDuel);
}
else
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You refused " + command.username + " duel request."));
Program.ChatServer.SendPacket(DevServerPackets.RefuseDuel);
}
}
public void StartDuelRequest(DuelRequest request)
{
ServerInfo server = null;
if (Program.ServerList.ContainsKey(request.server))
server = Program.ServerList[request.server];
if (server != null)
{
LauncherHelper.GenerateConfig(server, request.duelformatstring);
LauncherHelper.RunGame("-j");
}
}
public void DuelRequestRefused()
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "Your duel request has been refused."));
}
private void HandleTeamRequest(PacketCommand command)
{
if (InvokeRequired)
{
Invoke(new Action<PacketCommand>(HandleTeamRequest), command);
return;
}
switch (command.Command)
{
case "JOIN":
if (Program.Config.RefuseTeamInvites)
{
Program.ChatServer.SendPacket(DevServerPackets.TeamCommand,
JsonSerializer.SerializeToString(new PacketCommand { Command = "AUTOREFUSE" }));
return;
}
if (MessageBox.Show(command.Data + " has invited you to join a team.", "Team Request", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have accepted the team invite."));
Program.ChatServer.SendPacket(DevServerPackets.TeamCommand,
JsonSerializer.SerializeToString(new PacketCommand { Command = "ACCEPT" }));
}
else
{
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have refused the team invite."));
Program.ChatServer.SendPacket(DevServerPackets.TeamCommand,
JsonSerializer.SerializeToString(new PacketCommand { Command = "REFUSE" }));
}
break;
case "LEAVE":
Program.UserInfo.team = string.Empty;
Program.UserInfo.teamRank = 0;
ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.Team.ToString()));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have left the team."));
break;
case "REMOVED":
Program.UserInfo.team = string.Empty;
Program.UserInfo.teamRank = 0;
ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.Team.ToString()));
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have been removed from the team."));
break;
case "DISBAND":
if (Program.UserInfo.team == command.Data)
{
Program.UserInfo.team = string.Empty;
Program.UserInfo.teamRank = 0;
ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.Team.ToString()));
}
break;
}
}
private void IgnoreList_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int index = IgnoreList.IndexFromPoint(e.Location);
if (index == -1)
{
return;
}
IgnoreList.SelectedIndex = index;
var mnu = new ContextMenuStrip();
var mnuremoveignore = new ToolStripMenuItem(Program.LanguageManager.Translation.chatRemoveIgnore);
mnuremoveignore.Click += UnignoreUser;
mnu.Items.Add(mnuremoveignore);
mnu.Show(IgnoreList, e.Location);
}
}
private void UnignoreUser(object sender, EventArgs e)
{
if (IgnoreList.SelectedItem == null)
{
return;
}
WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, IgnoreList.SelectedItem + " has been removed from your ignore list."));
IgnoreList.Items.Remove(IgnoreList.SelectedItem);
SaveIgnoreList();
}
private void SaveIgnoreList()
{
var ignoredusers = new string[IgnoreList.Items.Count];
// ReSharper disable CoVariantArrayConversion
IgnoreList.Items.CopyTo(ignoredusers, 0);
// ReSharper restore CoVariantArrayConversion
string ignorestring = string.Join(",", ignoredusers);
Program.Config.IgnoreList = ignorestring;
Program.SaveConfig(Program.ConfigurationFilename, Program.Config);
}
private void FontSettings_Changed(object sender, EventArgs e)
{
var box = sender as ComboBox;
var down = sender as NumericUpDown;
if (box != null)
{
ComboBox fontstyle = box;
Program.Config.ChatFont = fontstyle.SelectedItem.ToString();
}
else if (down != null)
{
NumericUpDown size = down;
Program.Config.ChatSize = size.Value;
}
foreach (ChatWindow tab in ChannelTabs.TabPages)
{
tab.ApplyNewSettings();
}
foreach (var form in m_pmWindows.Values)
{
form.ApplyNewSettings();
}
Program.SaveConfig(Program.ConfigurationFilename, Program.Config);
}
private void List_DoubleClick(object sender, EventArgs e)
{
ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList;
if (list.SelectedIndex == -1)
return;
string user = list.Name == ChannelList.Name || list.Name == UserList.Name ?
((UserData)list.SelectedItem).username : list.SelectedItem.ToString();
if (Program.Config.PmWindows)
{
if (!m_pmWindows.ContainsKey(user))
{
m_pmWindows.Add(user, new PmWindowFrm(user, true));
m_pmWindows[user].Show();
m_pmWindows[user].FormClosed += Chat_frm_FormClosed;
}
else
{
m_pmWindows[user].BringToFront();
}
}
else
{
if (GetChatWindow(user) == null)
{
ChannelTabs.TabPages.Add(new ChatWindow(user, true));
ChannelTabs.SelectedTab = GetChatWindow(user);
}
else
{
ChannelTabs.SelectedTab = GetChatWindow(user);
}
}
}
private void ChannelListBtn_Click(object sender, EventArgs e)
{
var channellist = new ChannelListFrm();
channellist.ShowDialog();
}
private void LeaveBtn_Click(object sender, EventArgs e)
{
if (ChannelTabs.SelectedIndex != -1)
{
var selectedTab = (ChatWindow)ChannelTabs.SelectedTab;
if (selectedTab.IsPrivate)
{
ChannelTabs.TabPages.Remove(selectedTab);
}
else
{
LeaveChannel(selectedTab.Text);
}
}
}
private void userSearchBtn_Click(object sender, EventArgs e)
{
string searchinfo = UserSearch.ForeColor == SystemColors.WindowFrame ? string.Empty : UserSearch.Text;
Program.ChatServer.SendPacket(DevServerPackets.UserList,
JsonSerializer.SerializeToString(new PacketCommand() { Command = "USERS", Data = searchinfo }));
EnableSearchReset();
}
private void adminSearchBtn_Click(object sender, EventArgs e)
{
string searchinfo = UserSearch.ForeColor == SystemColors.WindowFrame ? string.Empty : UserSearch.Text;
Program.ChatServer.SendPacket(DevServerPackets.UserList,
JsonSerializer.SerializeToString(new PacketCommand() { Command = "ADMIN", Data = searchinfo }));
EnableSearchReset();
}
private void teamSearchBtn_Click(object sender, EventArgs e)
{
Program.ChatServer.SendPacket(DevServerPackets.UserList,
JsonSerializer.SerializeToString(new PacketCommand() { Command = "TEAM", Data = string.Empty }));
EnableSearchReset();
}
private void friendSearchBtn_Click(object sender, EventArgs e)
{
Program.ChatServer.SendPacket(DevServerPackets.UserList,
JsonSerializer.SerializeToString(new PacketCommand() { Command = "FRIENDS", Data = string.Empty }));
EnableSearchReset();
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmStockGroup
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmStockGroup() : base()
{
FormClosed += frmStockGroup_FormClosed;
KeyPress += frmStockGroup_KeyPress;
Resize += frmStockGroup_Resize;
Load += frmStockGroup_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.CheckBox _chkFields_1;
private System.Windows.Forms.TextBox withEventsField__txtFields_0;
public System.Windows.Forms.TextBox _txtFields_0 {
get { return withEventsField__txtFields_0; }
set {
if (withEventsField__txtFields_0 != null) {
withEventsField__txtFields_0.Enter -= txtFields_Enter;
}
withEventsField__txtFields_0 = value;
if (withEventsField__txtFields_0 != null) {
withEventsField__txtFields_0.Enter += txtFields_Enter;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdCancel;
public System.Windows.Forms.Button cmdCancel {
get { return withEventsField_cmdCancel; }
set {
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click -= cmdCancel_Click;
}
withEventsField_cmdCancel = value;
if (withEventsField_cmdCancel != null) {
withEventsField_cmdCancel.Click += cmdCancel_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.Label _lblLabels_38;
public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2;
public System.Windows.Forms.Label _lbl_5;
//Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray
public RectangleShapeArray Shape1;
public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockGroup));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer();
this._chkFields_1 = new System.Windows.Forms.CheckBox();
this._txtFields_0 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdCancel = new System.Windows.Forms.Button();
this.cmdClose = new System.Windows.Forms.Button();
this._lblLabels_38 = new System.Windows.Forms.Label();
this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape();
this._lbl_5 = new System.Windows.Forms.Label();
//Me.chkFields = New Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components)
this.Shape1 = new RectangleShapeArray(components);
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
//CType(Me.chkFields, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit()
((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Edit Stock Group Details";
this.ClientSize = new System.Drawing.Size(527, 117);
this.Location = new System.Drawing.Point(73, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmStockGroup";
this._chkFields_1.CheckAlign = System.Drawing.ContentAlignment.MiddleRight;
this._chkFields_1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this._chkFields_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._chkFields_1.Text = "Disable this Stock Group";
this._chkFields_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._chkFields_1.Size = new System.Drawing.Size(139, 13);
this._chkFields_1.Location = new System.Drawing.Point(360, 90);
this._chkFields_1.TabIndex = 6;
this._chkFields_1.CausesValidation = true;
this._chkFields_1.Enabled = true;
this._chkFields_1.Cursor = System.Windows.Forms.Cursors.Default;
this._chkFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._chkFields_1.Appearance = System.Windows.Forms.Appearance.Normal;
this._chkFields_1.TabStop = true;
this._chkFields_1.CheckState = System.Windows.Forms.CheckState.Unchecked;
this._chkFields_1.Visible = true;
this._chkFields_1.Name = "_chkFields_1";
this._txtFields_0.AutoSize = false;
this._txtFields_0.Size = new System.Drawing.Size(375, 19);
this._txtFields_0.Location = new System.Drawing.Point(126, 66);
this._txtFields_0.TabIndex = 5;
this._txtFields_0.AcceptsReturn = true;
this._txtFields_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this._txtFields_0.BackColor = System.Drawing.SystemColors.Window;
this._txtFields_0.CausesValidation = true;
this._txtFields_0.Enabled = true;
this._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtFields_0.HideSelection = true;
this._txtFields_0.ReadOnly = false;
this._txtFields_0.MaxLength = 0;
this._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtFields_0.Multiline = false;
this._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtFields_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtFields_0.TabStop = true;
this._txtFields_0.Visible = true;
this._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._txtFields_0.Name = "_txtFields_0";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(527, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 2;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCancel.Text = "&Undo";
this.cmdCancel.Size = new System.Drawing.Size(73, 29);
this.cmdCancel.Location = new System.Drawing.Point(5, 3);
this.cmdCancel.TabIndex = 1;
this.cmdCancel.TabStop = false;
this.cmdCancel.BackColor = System.Drawing.SystemColors.Control;
this.cmdCancel.CausesValidation = true;
this.cmdCancel.Enabled = true;
this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCancel.Name = "cmdCancel";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(441, 4);
this.cmdClose.TabIndex = 0;
this.cmdClose.TabStop = false;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.Name = "cmdClose";
this._lblLabels_38.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_38.Text = "Stock Group Name:";
this._lblLabels_38.Size = new System.Drawing.Size(94, 13);
this._lblLabels_38.Location = new System.Drawing.Point(27, 69);
this._lblLabels_38.TabIndex = 4;
this._lblLabels_38.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_38.Enabled = true;
this._lblLabels_38.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_38.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_38.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_38.UseMnemonic = true;
this._lblLabels_38.Visible = true;
this._lblLabels_38.AutoSize = true;
this._lblLabels_38.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_38.Name = "_lblLabels_38";
this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque;
this._Shape1_2.Size = new System.Drawing.Size(502, 49);
this._Shape1_2.Location = new System.Drawing.Point(15, 60);
this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText;
this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this._Shape1_2.BorderWidth = 1;
this._Shape1_2.FillColor = System.Drawing.Color.Black;
this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent;
this._Shape1_2.Visible = true;
this._Shape1_2.Name = "_Shape1_2";
this._lbl_5.BackColor = System.Drawing.Color.Transparent;
this._lbl_5.Text = "&1. General";
this._lbl_5.Size = new System.Drawing.Size(60, 13);
this._lbl_5.Location = new System.Drawing.Point(15, 45);
this._lbl_5.TabIndex = 3;
this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_5.Enabled = true;
this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_5.UseMnemonic = true;
this._lbl_5.Visible = true;
this._lbl_5.AutoSize = true;
this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_5.Name = "_lbl_5";
this.Controls.Add(_chkFields_1);
this.Controls.Add(_txtFields_0);
this.Controls.Add(picButtons);
this.Controls.Add(_lblLabels_38);
this.ShapeContainer1.Shapes.Add(_Shape1_2);
this.Controls.Add(_lbl_5);
this.Controls.Add(ShapeContainer1);
this.picButtons.Controls.Add(cmdCancel);
this.picButtons.Controls.Add(cmdClose);
//Me.chkFields.SetIndex(_chkFields_1, CType(1, Short))
//Me.lbl.SetIndex(_lbl_5, CType(5, Short))
//Me.lblLabels.SetIndex(_lblLabels_38, CType(38, Short))
//Me.txtFields.SetIndex(_txtFields_0, CType(0, Short))
this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2));
((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit();
//CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.chkFields, System.ComponentModel.ISupportInitialize).EndInit()
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class SoundManagerEditor : Editor {
#region editor variables
private AudioClip editAddSFX;
private string groupToAdd = "";
private Dictionary<int, List<int>> clipsByGroup = new Dictionary<int, List<int>>();
private bool debugDict = false;
#endregion
private void InitSFX()
{
clipsByGroup.Clear();
for(int i = script.clipToGroupValues.Count-1; i >= 0; i--)
{
if(i >= script.clipToGroupKeys.Count)
continue;
string groupName = script.clipToGroupValues[i];
string clipName = script.clipToGroupKeys[i];
int clipIndex = IndexOfClip(clipName);
int groupIndex = IndexOfGroup(groupName);
if(clipIndex < 0)
{
script.clipToGroupValues.RemoveAt(i);
script.clipToGroupKeys.RemoveAt(i);
continue;
}
if(clipsByGroup.ContainsKey(groupIndex))
{
clipsByGroup[groupIndex].Add(clipIndex);
}
else
{
clipsByGroup.Add(groupIndex, new List<int>(){clipIndex});
}
}
while(script.sfxPrePoolAmounts.Count > script.sfxBaseVolumes.Count)
script.sfxBaseVolumes.Add(1f);
while(script.sfxPrePoolAmounts.Count > script.sfxVolumeVariations.Count)
script.sfxVolumeVariations.Add(0f);
while(script.sfxPrePoolAmounts.Count > script.sfxPitchVariations.Count)
script.sfxPitchVariations.Add(0f);
QueryDict("InitSFX");
}
private void ShowSoundFX()
{
ShowSoundFXGroupsTitle();
ShowSoundFXGroupsList();
EditorGUILayout.Space();
EditorGUILayout.Space();
ShowSoundFXTitle();
ShowSoundFXList();
EditorGUILayout.Space();
EditorGUILayout.Space();
ShowAddSoundFX();
}
string[] toolbarStrings = new string[]{"Sort By Time Added", "Sort By Group"};
private void ShowSoundFXTitle()
{
int toolbarInt = script.showAsGrouped ? 1 : 0;
EditorGUILayout.LabelField(new GUIContent("Stored SFX", "These are SFX saved on the SoundManager. Each SFX has its own set of attributes that you can access by opening their drop downs. At the bottom, you can automatically set these attributes as you add SFX in the 'auto' section."), EditorStyles.boldLabel, GUILayout.ExpandWidth(false));
toolbarInt = GUILayout.Toolbar (toolbarInt, toolbarStrings, EditorStyles.toolbarButton, GUILayout.ExpandWidth(true));
script.showAsGrouped = (toolbarInt == 0) ? false : true;
}
private void ShowSoundFXGroupsTitle()
{
EditorGUILayout.LabelField(new GUIContent("SFX Groups", "SFX Groups let you randomly load a clip from them and they can have their own personalized SFX Cap Amount for capped sounds. Click the '?' to know more."), EditorStyles.boldLabel);
}
private void ShowSoundFXGroupsList()
{
EditorGUILayout.BeginVertical();
{
EditorGUI.indentLevel++;
if(script.helpOn)
EditorGUILayout.HelpBox("SFX Groups are used to:\n1. Access random clips in a set.\n2. Apply specific cap amounts to clips when using SoundManager.PlayCappedSFX." +
"\n\n-Setting the cap amount to -1 will make a group use the default SFX Cap Amount\n\n-Setting the cap amount to 0 will make a group not use a cap at all.",MessageType.Info);
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Group Name:", GUILayout.ExpandWidth(true));
EditorGUILayout.LabelField("Cap:", GUILayout.Width(40f));
bool helpOn = script.helpOn;
helpOn = GUILayout.Toggle(helpOn, "?", GUI.skin.button, GUILayout.Width(35f));
if(helpOn != script.helpOn)
{
SoundManagerEditorTools.RegisterObjectChange("Change SFXGroup Help", script);
script.helpOn = helpOn;
EditorUtility.SetDirty(script);
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("", GUILayout.Width(10f));
GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1));
}
EditorGUILayout.EndHorizontal();
for(int i = 0 ; i < script.sfxGroups.Count; i++)
{
EditorGUILayout.BeginHorizontal();
{
SFXGroup grp = script.sfxGroups[i];
if(grp != null)
{
EditorGUILayout.LabelField(grp.groupName, GUILayout.ExpandWidth(true));
int specificCapAmount = grp.specificCapAmount;
bool isAuto = false, isNo = false;
if(specificCapAmount == -1)
isAuto = true;
else if(specificCapAmount == 0)
isNo = true;
bool newAuto = GUILayout.Toggle(isAuto, "Auto Cap", GUI.skin.button, GUILayout.ExpandWidth(false));
bool newNo = GUILayout.Toggle(isNo, "No Cap", GUI.skin.button, GUILayout.ExpandWidth(false));
if(newAuto != isAuto && newAuto)
{
specificCapAmount = -1;
}
if(newNo != isNo && newNo)
{
specificCapAmount = 0;
}
specificCapAmount = EditorGUILayout.IntField(specificCapAmount, GUILayout.Width(40f));
if(specificCapAmount < -1) specificCapAmount = -1;
if(specificCapAmount != grp.specificCapAmount)
{
SoundManagerEditorTools.RegisterObjectChange("Change Group Cap", script);
grp.specificCapAmount = specificCapAmount;
EditorUtility.SetDirty(script);
}
EditorGUILayout.LabelField("", GUILayout.Width(10f));
GUI.color = Color.red;
if(GUILayout.Button("X", GUILayout.Width(20f)))
{
RemoveGroup(i);
return;
}
GUI.color = Color.white;
}
}
EditorGUILayout.EndHorizontal();
}
ShowAddGroup();
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
EditorGUILayout.EndVertical();
}
private void ShowAddGroup()
{
EditorGUI.indentLevel += 2;
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.LabelField("Add a Group:");
groupToAdd = EditorGUILayout.TextField(groupToAdd, GUILayout.ExpandWidth(true));
GUI.color = softGreen;
if(GUILayout.Button("add", GUILayout.Width(40f)))
{
AddGroup(groupToAdd, -1);
groupToAdd = "";
GUIUtility.keyboardControl = 0;
}
GUI.color = Color.white;
}
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel -= 2;
}
private void QueryDict(string comingfrom)
{
if(!debugDict) return;
string result = comingfrom + "\n";
for(int i = 0; i < clipsByGroup.Count; i++)
{
KeyValuePair<int, List<int>> pair = clipsByGroup.ElementAt(i);
result += pair.Key + ":";
if(script.sfxGroups.Count > pair.Key)
result += script.sfxGroups[pair.Key].groupName;
else
result += "ERR";
result += "\n";
for(int j = 0; j < pair.Value.Count; j++)
{
result += " ";
result += pair.Value[j] + ":";
if(script.storedSFXs.Count > pair.Value[j])
result += script.storedSFXs[pair.Value[j]].name + "\n";
else
result += "ERR";
}
}
Debug.Log(result);
}
private void ShowSoundFXList()
{
var expand = '\u2261'.ToString();
GUIContent expandContent = new GUIContent(expand, "Expand/Collapse");
string[] groups = GetAvailableGroups();
EditorGUILayout.BeginVertical();
{
if(!script.showAsGrouped)
{
EditorGUI.indentLevel++;
for(int i = 0 ; i < script.storedSFXs.Count ; i++)
{
if(i < script.storedSFXs.Count && script.storedSFXs[i] != null)
ShowIndividualSFXAtIndex(i, groups, expandContent);
else
RemoveSFX(i);
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
else
{
// by group
EditorGUI.indentLevel++;
for(int j = 0; j < clipsByGroup.Count; j++)
{
KeyValuePair<int, List<int>> pair = clipsByGroup.ElementAt(j);
if(pair.Key >= script.sfxGroups.Count || script.sfxGroups[pair.Key] == null)
continue;
EditorGUILayout.LabelField(script.sfxGroups[pair.Key].groupName + ":");
EditorGUI.indentLevel+=2;
{
for(int i = 0; i < pair.Value.Count; i++)
{
int index = pair.Value[i];
if(index >= 0 && index < script.storedSFXs.Count && script.storedSFXs[index] != null)
ShowIndividualSFXAtIndex(index, groups, expandContent);
else
RemoveSFX(index);
}
}
EditorGUI.indentLevel-=2;
}
EditorGUILayout.LabelField("Not Grouped:");
for(int i = 0; i < script.storedSFXs.Count; i++)
{
EditorGUI.indentLevel+=2;
if(i < script.storedSFXs.Count && script.storedSFXs[i] != null && !script.clipToGroupKeys.Contains(script.storedSFXs[i].name))
ShowIndividualSFXAtIndex(i, groups, expandContent);
else if (script.storedSFXs[i] == null)
RemoveSFX(i);
EditorGUI.indentLevel-=2;
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
}
EditorGUILayout.EndVertical();
}
private void ShowIndividualSFXAtIndex(int i, string[] groups, GUIContent expandContent)
{
if(i >= script.storedSFXs.Count) return;
AudioClip obj = script.storedSFXs[i];
if(obj != null)
{
EditorGUILayout.BeginHorizontal();
{
AudioClip newClip = (AudioClip)EditorGUILayout.ObjectField(obj, typeof(AudioClip), false);
if(newClip != obj)
{
if(newClip == null)
{
RemoveSFX(i);
return;
}
else
{
SoundManagerEditorTools.RegisterObjectChange("Change SFX", script);
obj = newClip;
EditorUtility.SetDirty(script);
}
}
if((script.showSFXDetails[i] && GUILayout.Button("-", GUILayout.Width(30f))) || (!script.showSFXDetails[i] && GUILayout.Button(expandContent, GUILayout.Width(30f))))
{
script.showSFXDetails[i] = !script.showSFXDetails[i];
}
GUI.color = Color.red;
if(GUILayout.Button("X", GUILayout.Width(20f)))
{
RemoveSFX(i);
return;
}
GUI.color = Color.white;
}
EditorGUILayout.EndHorizontal();
if(script.showSFXDetails[i])
{
EditorGUI.indentLevel+=4;
string clipName = obj.name;
int oldIndex = IndexOfKey(clipName);
if(oldIndex >= 0) // if in a group, find index
oldIndex = IndexOfGroup(script.clipToGroupValues[oldIndex]);
if(oldIndex < 0) // if not in a group, set it to none
oldIndex = 0;
else //if in a group, add 1 to index to cover for None group type
oldIndex++;
int newIndex = EditorGUILayout.Popup("Group:", oldIndex, groups, EditorStyles.popup);
if(oldIndex != newIndex)
{
string groupName = groups[newIndex];
ChangeGroup(clipName, oldIndex, newIndex, groupName);
return;
}
int prepoolAmount = script.sfxPrePoolAmounts[i];
prepoolAmount = EditorGUILayout.IntField(new GUIContent("Prepool Amount:", "Minimum amount of SFX objects for this clip waiting in the pool on standby. Good for performance."), prepoolAmount);
if(prepoolAmount < 0)
prepoolAmount = 0;
if(prepoolAmount != script.sfxPrePoolAmounts[i])
{
SoundManagerEditorTools.RegisterObjectChange("Change Prepool Amount", script);
script.sfxPrePoolAmounts[i] = prepoolAmount;
EditorUtility.SetDirty(script);
}
float baseVolume = script.sfxBaseVolumes[i];
baseVolume = EditorGUILayout.FloatField(new GUIContent("Base Volume:", "Base volume for this AudioClip. Lower this value if you don't want this AudioClip to play as loud. When in doubt, keep this at 1."), baseVolume);
if(baseVolume < 0f)
baseVolume = 0f;
else if(baseVolume > 1f)
baseVolume = 1f;
if(baseVolume != script.sfxBaseVolumes[i])
{
SoundManagerEditorTools.RegisterObjectChange("Change Base Volume", script);
script.sfxBaseVolumes[i] = baseVolume;
EditorUtility.SetDirty(script);
}
float volumeVariation = script.sfxVolumeVariations[i];
volumeVariation = EditorGUILayout.FloatField(new GUIContent("Volume Variation:", "Let's you vary the volume of this clip each time it's played. You get a much greater impact if you randomly vary pitch and volume between 3% and 5% each time that sound is played. So keep this value low: ~0.05"), volumeVariation);
if(volumeVariation < 0f)
volumeVariation = 0f;
else if(volumeVariation > 1f)
volumeVariation = 1f;
if(volumeVariation != script.sfxVolumeVariations[i])
{
SoundManagerEditorTools.RegisterObjectChange("Change Volume Variation", script);
script.sfxVolumeVariations[i] = volumeVariation;
EditorUtility.SetDirty(script);
}
float pitchVariation = script.sfxPitchVariations[i];
pitchVariation = EditorGUILayout.FloatField(new GUIContent("Pitch Variation:", "Let's you vary the pitch of this clip each time it's played. You get a much greater impact if you randomly vary pitch and volume between 3% and 5% each time that sound is played. So keep this value low: ~0.025"), pitchVariation);
if(pitchVariation < 0f)
pitchVariation = 0f;
else if(pitchVariation > 1f)
pitchVariation = 1f;
if(pitchVariation != script.sfxPitchVariations[i])
{
SoundManagerEditorTools.RegisterObjectChange("Change Pitch Variation", script);
script.sfxPitchVariations[i] = pitchVariation;
EditorUtility.SetDirty(script);
}
EditorGUI.indentLevel-=4;
}
}
}
private void ShowAddSoundFX()
{
ShowAddSoundFXDropGUI();
ShowAddSoundFXSelector();
string[] groups = GetAvailableGroups();
if(groups.Length > 1)
script.groupAddIndex = EditorGUILayout.Popup("Auto-Add To Group:", script.groupAddIndex, groups, EditorStyles.popup, GUILayout.Width(100f), GUILayout.ExpandWidth(true));
else
script.groupAddIndex = 0;
script.autoPrepoolAmount = EditorGUILayout.IntField("Auto-Prepool Amount:", script.autoPrepoolAmount);
if(script.autoPrepoolAmount < 0)
script.autoPrepoolAmount = 0;
script.autoBaseVolume = EditorGUILayout.FloatField("Auto-Base Volume:", script.autoBaseVolume);
if(script.autoBaseVolume < 0f)
script.autoBaseVolume = 0f;
else if(script.autoBaseVolume > 1f)
script.autoBaseVolume = 1f;
script.autoVolumeVariation = EditorGUILayout.FloatField("Auto-Volume Variation:", script.autoVolumeVariation);
if(script.autoVolumeVariation < 0f)
script.autoVolumeVariation = 0f;
else if(script.autoVolumeVariation > 1f)
script.autoVolumeVariation = 1f;
script.autoPitchVariation = EditorGUILayout.FloatField("Auto-Pitch Variation:", script.autoPitchVariation);
if(script.autoPitchVariation < 0f)
script.autoPitchVariation = 0f;
else if(script.autoPitchVariation > 1f)
script.autoPitchVariation = 1f;
}
private void ShowAddSoundFXDropGUI()
{
GUI.color = softGreen;
EditorGUILayout.BeginVertical();
{
var evt = Event.current;
var dropArea = GUILayoutUtility.GetRect(0f,50f,GUILayout.ExpandWidth(true));
GUI.Box (dropArea, "Drag SFX(s) Here");
switch (evt.type)
{
case EventType.DragUpdated:
case EventType.DragPerform:
if(!dropArea.Contains (evt.mousePosition))
break;
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if( evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
foreach (var draggedObject in DragAndDrop.objectReferences)
{
var aC = draggedObject as AudioClip;
if(!aC || aC.GetType() != typeof(AudioClip))
continue;
if(AlreadyContainsSFX(aC))
Debug.LogError("You already have that sound effect(" +aC.name+ ") attached, or a sound effect with the same name.");
else
AddSFX(aC, script.groupAddIndex, script.autoPrepoolAmount, script.autoBaseVolume, script.autoVolumeVariation, script.autoPitchVariation);
}
}
Event.current.Use();
break;
}
}
EditorGUILayout.EndVertical();
GUI.color = Color.white;
}
private void ShowAddSoundFXSelector()
{
EditorGUILayout.BeginHorizontal();
{
editAddSFX = EditorGUILayout.ObjectField("Select A SFX:", editAddSFX, typeof(AudioClip), false) as AudioClip;
GUI.color = softGreen;
if(GUILayout.Button("add", GUILayout.Width(40f)))
{
if(AlreadyContainsSFX(editAddSFX))
Debug.LogError("You already have that sound effect(" +editAddSFX.name+ ") attached, or a sound effect with the same name.");
else
AddSFX(editAddSFX, script.groupAddIndex, script.autoPrepoolAmount, script.autoBaseVolume, script.autoVolumeVariation, script.autoPitchVariation);
editAddSFX = null;
}
GUI.color = Color.white;
}
EditorGUILayout.EndHorizontal();
}
private void AddSFX(AudioClip clip, int groupIndex, int prepoolAmount, float baseVolume, float volumeVariation, float pitchVariation)
{
if(clip == null)
return;
SoundManagerEditorTools.RegisterObjectChange("Add SFX", script);
script.storedSFXs.Add(clip);
script.sfxPrePoolAmounts.Add(prepoolAmount);
script.sfxBaseVolumes.Add(baseVolume);
script.sfxVolumeVariations.Add(volumeVariation);
script.sfxPitchVariations.Add(pitchVariation);
script.showSFXDetails.Add(false);
if(script.groupAddIndex > 0)
AddToGroup(clip.name, GetAvailableGroups()[script.groupAddIndex]);
else
{
EditorUtility.SetDirty(script);
SceneView.RepaintAll();
}
QueryDict("AddSFX");
}
private void RemoveSFX(int index)
{
SoundManagerEditorTools.RegisterObjectChange("Remove SFX", script);
string clipName = "";
if(script.storedSFXs[index] != null)
clipName = script.storedSFXs[index].name;
script.storedSFXs.RemoveAt(index);
script.sfxPrePoolAmounts.RemoveAt(index);
script.sfxBaseVolumes.RemoveAt(index);
script.sfxVolumeVariations.RemoveAt(index);
script.sfxPitchVariations.RemoveAt(index);
script.showSFXDetails.RemoveAt(index);
if(!string.IsNullOrEmpty(clipName))
{
if(IsInAGroup(clipName))
RemoveFromGroup(clipName);
}
else
{
RemoveTracesOfIndex(index);
}
InitSFX();
EditorUtility.SetDirty(script);
SceneView.RepaintAll();
QueryDict("RemoveSFX");
}
private void RemoveTracesOfIndex(int index)
{
string groupName = "";
foreach(KeyValuePair<int, List<int>> pair in clipsByGroup)
{
if(pair.Value.Contains(index))
{
groupName = script.sfxGroups[pair.Key].groupName;
pair.Value.Remove(index);
break;
}
}
if(!string.IsNullOrEmpty(groupName))
{
//if it was in a group, lets remove other traces.
for(int i = 0; i < script.clipToGroupValues.Count; i++)
{
if(script.clipToGroupValues[i] == groupName && IndexOfClip(script.clipToGroupKeys[i]) == -1)
{
script.clipToGroupKeys.RemoveAt(i);
script.clipToGroupValues.RemoveAt(i);
break;
}
}
}
}
private void AddGroup(string groupName, int capAmount)
{
if(AlreadyContainsGroup(groupName))
return;
SoundManagerEditorTools.RegisterObjectChange("Add Group", script);
script.sfxGroups.Add(new SFXGroup(groupName, capAmount));
if(!clipsByGroup.ContainsKey(script.sfxGroups.Count-1))
{
clipsByGroup.Add(script.sfxGroups.Count-1, new List<int>());
}
EditorUtility.SetDirty(script);
SceneView.RepaintAll();
QueryDict("AddGroup");
}
private void RemoveGroup(int index)
{
SoundManagerEditorTools.RegisterObjectChange("Remove Group", script);
string groupName = script.sfxGroups[index].groupName;
RemoveAllInGroup(groupName);
script.sfxGroups.RemoveAt(index);
if(clipsByGroup.ContainsKey(index))
clipsByGroup.Remove(index);
InitSFX();
EditorUtility.SetDirty(script);
SceneView.RepaintAll();
QueryDict("RemoveGroup");
}
private void RemoveAllInGroup(string groupName)
{
for( int i = script.clipToGroupKeys.Count-1; i >= 0; i--)
{
if(script.clipToGroupValues[i] == groupName)
RemoveFromGroup(script.clipToGroupKeys[i]);
}
}
private string[] GetAvailableGroups()
{
List<string> result = new List<string>();
result.Add("None");
for( int i = 0; i < script.sfxGroups.Count; i++)
result.Add(script.sfxGroups[i].groupName);
return result.ToArray();
}
private bool IsInAGroup(string clipname)
{
for( int i = 0; i < script.clipToGroupKeys.Count; i++)
if(script.clipToGroupKeys[i] == clipname)
return true;
return false;
}
private int IndexOfKey(string clipname)
{
for( int i = 0; i < script.clipToGroupKeys.Count; i++)
if(script.clipToGroupKeys[i] == clipname)
return i;
return -1;
}
private int IndexOfClip(string clipname)
{
for( int i = 0; i < script.storedSFXs.Count; i++)
if(script.storedSFXs[i] != null && script.storedSFXs[i].name == clipname)
return i;
return -1;
}
private int IndexOfGroup(string groupname)
{
for( int i = 0; i < script.sfxGroups.Count; i++)
if(script.sfxGroups[i].groupName == groupname)
return i;
return -1;
}
private void ChangeGroup(string clipName, int previousIndex, int nextIndex, string groupName)
{
SoundManagerEditorTools.RegisterObjectChange("Change Group", script);
if(previousIndex == 0) //wasnt in group, so add it
{
AddToGroup(clipName, groupName);
}
else if (nextIndex == 0) //was in group but now doesn't want to be
{
RemoveFromGroup(clipName);
}
else //just changing groups
{
int index = IndexOfKey(clipName);
int groupIndex = IndexOfGroup(groupName);
int clipIndex = IndexOfClip(clipName);
int oldGroupIndex = IndexOfGroup(script.clipToGroupValues[index]);
script.clipToGroupValues[index] = groupName;
if(clipsByGroup.ContainsKey(groupIndex))
{
clipsByGroup[oldGroupIndex].Remove(clipIndex);
clipsByGroup[groupIndex].Add(clipIndex);
}
else
{
clipsByGroup.Add(groupIndex, new List<int>(){clipIndex});
}
EditorUtility.SetDirty(script);
}
QueryDict("ChangeGroup");
}
private void AddToGroup(string clipName, string groupName)
{
if(IsInAGroup(clipName) || !AlreadyContainsGroup(groupName))
return;
script.clipToGroupKeys.Add(clipName);
script.clipToGroupValues.Add(groupName);
int groupIndex = IndexOfGroup(groupName);
int clipIndex = IndexOfClip(clipName);
if(clipsByGroup.ContainsKey(groupIndex))
clipsByGroup[groupIndex].Add(clipIndex);
else
{
clipsByGroup.Add(groupIndex, new List<int>(){clipIndex});
}
EditorUtility.SetDirty(script);
SceneView.RepaintAll();
QueryDict("AddToGroup");
}
private void RemoveFromGroup(string clipName)
{
if(!IsInAGroup(clipName))
return;
int index = IndexOfKey(clipName);
int clipIndex = IndexOfClip(clipName);
int groupIndex = IndexOfGroup(script.clipToGroupValues[index]);
script.clipToGroupKeys.RemoveAt(index);
script.clipToGroupValues.RemoveAt(index);
if(clipsByGroup.ContainsKey(groupIndex))
clipsByGroup[groupIndex].Remove(clipIndex);
EditorUtility.SetDirty(script);
SceneView.RepaintAll();
QueryDict("RemoveFromGroup");
}
private bool AlreadyContainsSFX(AudioClip clip)
{
for(int i = 0 ; i < script.storedSFXs.Count ; i++)
{
AudioClip obj = script.storedSFXs[i];
if(obj == null) continue;
if(obj.name == clip.name || obj == clip)
return true;
}
return false;
}
private bool AlreadyContainsGroup(string grpName)
{
for(int i = 0 ; i < script.sfxGroups.Count ; i++)
{
SFXGroup grp = script.sfxGroups[i];
if(grp == null) continue;
if(grp.groupName == grpName)
return true;
}
return false;
}
}
| |
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
using RTHandle = RTHandleSystem.RTHandle;
[Serializable, VolumeComponentMenu("Lighting/Ambient Occlusion")]
public sealed class AmbientOcclusion : VolumeComponent
{
[Tooltip("Controls the strength of the ambient occlusion effect. Increase this value to produce darker areas.")]
public ClampedFloatParameter intensity = new ClampedFloatParameter(0f, 0f, 4f);
[Tooltip("Controls the thickness of occluders. Increase this value to increase the size of dark areas.")]
public ClampedFloatParameter thicknessModifier = new ClampedFloatParameter(1f, 1f, 10f);
[Tooltip("Controls how much the ambient light affects occlusion.")]
public ClampedFloatParameter directLightingStrength = new ClampedFloatParameter(0f, 0f, 1f);
// Hidden parameters
[HideInInspector] public ClampedFloatParameter noiseFilterTolerance = new ClampedFloatParameter(0f, -8f, 0f);
[HideInInspector] public ClampedFloatParameter blurTolerance = new ClampedFloatParameter(-4.6f, -8f, 1f);
[HideInInspector] public ClampedFloatParameter upsampleTolerance = new ClampedFloatParameter(-12f, -12f, -1f);
}
public class AmbientOcclusionSystem
{
enum MipLevel { Original, L1, L2, L3, L4, L5, L6, Count }
RenderPipelineResources m_Resources;
RenderPipelineSettings m_Settings;
// The arrays below are reused between frames to reduce GC allocation.
readonly float[] m_SampleThickness =
{
Mathf.Sqrt(1f - 0.2f * 0.2f),
Mathf.Sqrt(1f - 0.4f * 0.4f),
Mathf.Sqrt(1f - 0.6f * 0.6f),
Mathf.Sqrt(1f - 0.8f * 0.8f),
Mathf.Sqrt(1f - 0.2f * 0.2f - 0.2f * 0.2f),
Mathf.Sqrt(1f - 0.2f * 0.2f - 0.4f * 0.4f),
Mathf.Sqrt(1f - 0.2f * 0.2f - 0.6f * 0.6f),
Mathf.Sqrt(1f - 0.2f * 0.2f - 0.8f * 0.8f),
Mathf.Sqrt(1f - 0.4f * 0.4f - 0.4f * 0.4f),
Mathf.Sqrt(1f - 0.4f * 0.4f - 0.6f * 0.6f),
Mathf.Sqrt(1f - 0.4f * 0.4f - 0.8f * 0.8f),
Mathf.Sqrt(1f - 0.6f * 0.6f - 0.6f * 0.6f)
};
readonly float[] m_InvThicknessTable = new float[12];
readonly float[] m_SampleWeightTable = new float[12];
readonly int[] m_Widths = new int[7];
readonly int[] m_Heights = new int[7];
readonly RTHandle m_AmbientOcclusionTex;
// All the targets needed are pre-allocated and only released on cleanup for now to avoid
// having to constantly allo/dealloc on every frame
readonly RTHandle m_LinearDepthTex;
readonly RTHandle m_LowDepth1Tex;
readonly RTHandle m_LowDepth2Tex;
readonly RTHandle m_LowDepth3Tex;
readonly RTHandle m_LowDepth4Tex;
readonly RTHandle m_TiledDepth1Tex;
readonly RTHandle m_TiledDepth2Tex;
readonly RTHandle m_TiledDepth3Tex;
readonly RTHandle m_TiledDepth4Tex;
readonly RTHandle m_Occlusion1Tex;
readonly RTHandle m_Occlusion2Tex;
readonly RTHandle m_Occlusion3Tex;
readonly RTHandle m_Occlusion4Tex;
readonly RTHandle m_Combined1Tex;
readonly RTHandle m_Combined2Tex;
readonly RTHandle m_Combined3Tex;
readonly ScaleFunc[] m_ScaleFunctors;
// MSAA-specifics
readonly RTHandle m_MultiAmbientOcclusionTex;
readonly MaterialPropertyBlock m_ResolvePropertyBlock;
readonly Material m_ResolveMaterial;
#if ENABLE_RAYTRACING
public HDRaytracingManager m_RayTracingManager = new HDRaytracingManager();
readonly HDRaytracingAmbientOcclusion m_RaytracingAmbientOcclusion = new HDRaytracingAmbientOcclusion();
#endif
public AmbientOcclusionSystem(HDRenderPipelineAsset hdAsset)
{
m_Settings = hdAsset.currentPlatformRenderPipelineSettings;
m_Resources = hdAsset.renderPipelineResources;
if (!hdAsset.currentPlatformRenderPipelineSettings.supportSSAO)
return;
bool supportMSAA = hdAsset.currentPlatformRenderPipelineSettings.supportMSAA;
// Destination targets
m_AmbientOcclusionTex = RTHandles.Alloc(Vector2.one,
filterMode: FilterMode.Bilinear,
colorFormat: GraphicsFormat.R8_UNorm,
enableRandomWrite: true,
xrInstancing: true,
useDynamicScale: true,
name: "Ambient Occlusion"
);
if (supportMSAA)
{
m_MultiAmbientOcclusionTex = RTHandles.Alloc(Vector2.one,
filterMode: FilterMode.Bilinear,
colorFormat: GraphicsFormat.R8G8_UNorm,
enableRandomWrite: true,
xrInstancing: true,
useDynamicScale: true,
name: "Ambient Occlusion MSAA"
);
m_ResolveMaterial = CoreUtils.CreateEngineMaterial(m_Resources.shaders.aoResolvePS);
m_ResolvePropertyBlock = new MaterialPropertyBlock();
}
// Prepare scale functors
m_ScaleFunctors = new ScaleFunc[(int)MipLevel.Count];
m_ScaleFunctors[0] = size => size; // 0 is original size (mip0)
for (int i = 1; i < m_ScaleFunctors.Length; i++)
{
int mult = i;
m_ScaleFunctors[i] = size =>
{
int div = 1 << mult;
return new Vector2Int(
(size.x + (div - 1)) / div,
(size.y + (div - 1)) / div
);
};
}
var fmtFP16 = supportMSAA ? GraphicsFormat.R16G16_SFloat : GraphicsFormat.R16_SFloat;
var fmtFP32 = supportMSAA ? GraphicsFormat.R32G32_SFloat : GraphicsFormat.R32_SFloat;
var fmtFX8 = supportMSAA ? GraphicsFormat.R8G8_UNorm : GraphicsFormat.R8_UNorm;
// All of these are pre-allocated to 1x1 and will be automatically scaled properly by
// the internal RTHandle system
Alloc(out m_LinearDepthTex, MipLevel.Original, fmtFP16, true, "AOLinearDepth");
Alloc(out m_LowDepth1Tex, MipLevel.L1, fmtFP32, true, "AOLowDepth1");
Alloc(out m_LowDepth2Tex, MipLevel.L2, fmtFP32, true, "AOLowDepth2");
Alloc(out m_LowDepth3Tex, MipLevel.L3, fmtFP32, true, "AOLowDepth3");
Alloc(out m_LowDepth4Tex, MipLevel.L4, fmtFP32, true, "AOLowDepth4");
AllocArray(out m_TiledDepth1Tex, MipLevel.L3, fmtFP16, true, "AOTiledDepth1");
AllocArray(out m_TiledDepth2Tex, MipLevel.L4, fmtFP16, true, "AOTiledDepth2");
AllocArray(out m_TiledDepth3Tex, MipLevel.L5, fmtFP16, true, "AOTiledDepth3");
AllocArray(out m_TiledDepth4Tex, MipLevel.L6, fmtFP16, true, "AOTiledDepth4");
Alloc(out m_Occlusion1Tex, MipLevel.L1, fmtFX8, true, "AOOcclusion1");
Alloc(out m_Occlusion2Tex, MipLevel.L2, fmtFX8, true, "AOOcclusion2");
Alloc(out m_Occlusion3Tex, MipLevel.L3, fmtFX8, true, "AOOcclusion3");
Alloc(out m_Occlusion4Tex, MipLevel.L4, fmtFX8, true, "AOOcclusion4");
Alloc(out m_Combined1Tex, MipLevel.L1, fmtFX8, true, "AOCombined1");
Alloc(out m_Combined2Tex, MipLevel.L2, fmtFX8, true, "AOCombined2");
Alloc(out m_Combined3Tex, MipLevel.L3, fmtFX8, true, "AOCombined3");
}
public void Cleanup()
{
#if ENABLE_RAYTRACING
m_RaytracingAmbientOcclusion.Release();
#endif
CoreUtils.Destroy(m_ResolveMaterial);
RTHandles.Release(m_AmbientOcclusionTex);
RTHandles.Release(m_MultiAmbientOcclusionTex);
RTHandles.Release(m_LinearDepthTex);
RTHandles.Release(m_LowDepth1Tex);
RTHandles.Release(m_LowDepth2Tex);
RTHandles.Release(m_LowDepth3Tex);
RTHandles.Release(m_LowDepth4Tex);
RTHandles.Release(m_TiledDepth1Tex);
RTHandles.Release(m_TiledDepth2Tex);
RTHandles.Release(m_TiledDepth3Tex);
RTHandles.Release(m_TiledDepth4Tex);
RTHandles.Release(m_Occlusion1Tex);
RTHandles.Release(m_Occlusion2Tex);
RTHandles.Release(m_Occlusion3Tex);
RTHandles.Release(m_Occlusion4Tex);
RTHandles.Release(m_Combined1Tex);
RTHandles.Release(m_Combined2Tex);
RTHandles.Release(m_Combined3Tex);
}
#if ENABLE_RAYTRACING
public void InitRaytracing(HDRaytracingManager raytracingManager, SharedRTManager sharedRTManager)
{
m_RayTracingManager = raytracingManager;
m_RaytracingAmbientOcclusion.Init(m_Resources, m_Settings, m_RayTracingManager, sharedRTManager);
}
#endif
public bool IsActive(HDCamera camera, AmbientOcclusion settings) => camera.frameSettings.IsEnabled(FrameSettingsField.SSAO) && settings.intensity.value > 0f;
public void Render(CommandBuffer cmd, HDCamera camera, SharedRTManager sharedRTManager, ScriptableRenderContext renderContext, int frameCount)
{
#if ENABLE_RAYTRACING
HDRaytracingEnvironment rtEnvironement = m_RayTracingManager.CurrentEnvironment();
if (rtEnvironement != null && rtEnvironement.raytracedAO)
m_RaytracingAmbientOcclusion.RenderAO(camera, cmd, m_AmbientOcclusionTex, renderContext, frameCount);
else
#endif
{
Dispatch(cmd, camera, sharedRTManager);
PostDispatchWork(cmd, camera, sharedRTManager);
}
}
public void Dispatch(CommandBuffer cmd, HDCamera camera, SharedRTManager sharedRTManager)
{
// Grab current settings
var settings = VolumeManager.instance.stack.GetComponent<AmbientOcclusion>();
if (!IsActive(camera, settings))
return;
using (new ProfilingSample(cmd, "Render SSAO", CustomSamplerId.RenderSSAO.GetSampler()))
{
// Base size
m_Widths[0] = camera.actualWidth;
m_Heights[0] = camera.actualHeight;
// L1 -> L6 sizes
// We need to recalculate these on every frame, we can't rely on RTHandle width/height
// values as they may have been rescaled and not the actual size we want
for (int i = 1; i < (int)MipLevel.Count; i++)
{
int div = 1 << i;
m_Widths[i] = (m_Widths[0] + (div - 1)) / div;
m_Heights[i] = (m_Heights[0] + (div - 1)) / div;
}
// Grab current viewport scale factor - needed to handle RTHandle auto resizing
var viewport = new Vector2(RTHandles.rtHandleProperties.rtHandleScale.x, RTHandles.rtHandleProperties.rtHandleScale.y);
// Textures used for rendering
RTHandle depthMap, destination;
bool msaa = camera.frameSettings.IsEnabled(FrameSettingsField.MSAA);
if (msaa)
{
depthMap = sharedRTManager.GetDepthValuesTexture();
destination = m_MultiAmbientOcclusionTex;
}
else
{
depthMap = sharedRTManager.GetDepthTexture();
destination = m_AmbientOcclusionTex;
}
// Render logic
PushDownsampleCommands(cmd, camera, depthMap, msaa);
float tanHalfFovH = CalculateTanHalfFovHeight(camera);
PushRenderCommands(cmd, camera, viewport, m_TiledDepth1Tex, m_Occlusion1Tex, settings, GetSizeArray(MipLevel.L3), tanHalfFovH, msaa);
PushRenderCommands(cmd, camera, viewport, m_TiledDepth2Tex, m_Occlusion2Tex, settings, GetSizeArray(MipLevel.L4), tanHalfFovH, msaa);
PushRenderCommands(cmd, camera, viewport, m_TiledDepth3Tex, m_Occlusion3Tex, settings, GetSizeArray(MipLevel.L5), tanHalfFovH, msaa);
PushRenderCommands(cmd, camera, viewport, m_TiledDepth4Tex, m_Occlusion4Tex, settings, GetSizeArray(MipLevel.L6), tanHalfFovH, msaa);
PushUpsampleCommands(cmd, camera, viewport, m_LowDepth4Tex, m_Occlusion4Tex, m_LowDepth3Tex, m_Occlusion3Tex, m_Combined3Tex, settings, GetSize(MipLevel.L4), GetSize(MipLevel.L3), msaa);
PushUpsampleCommands(cmd, camera, viewport, m_LowDepth3Tex, m_Combined3Tex, m_LowDepth2Tex, m_Occlusion2Tex, m_Combined2Tex, settings, GetSize(MipLevel.L3), GetSize(MipLevel.L2), msaa);
PushUpsampleCommands(cmd, camera, viewport, m_LowDepth2Tex, m_Combined2Tex, m_LowDepth1Tex, m_Occlusion1Tex, m_Combined1Tex, settings, GetSize(MipLevel.L2), GetSize(MipLevel.L1), msaa);
PushUpsampleCommands(cmd, camera, viewport, m_LowDepth1Tex, m_Combined1Tex, m_LinearDepthTex, null, destination, settings, GetSize(MipLevel.L1), GetSize(MipLevel.Original), msaa);
}
}
public void PostDispatchWork(CommandBuffer cmd, HDCamera camera, SharedRTManager sharedRTManager)
{
// Grab current settings
var settings = VolumeManager.instance.stack.GetComponent<AmbientOcclusion>();
if (!IsActive(camera, settings))
{
// No AO applied - neutral is black, see the comment in the shaders
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, TextureXR.GetBlackTexture());
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, Vector4.zero);
return;
}
// MSAA Resolve
if (camera.frameSettings.IsEnabled(FrameSettingsField.MSAA))
{
using (new ProfilingSample(cmd, "Resolve AO Buffer", CustomSamplerId.ResolveSSAO.GetSampler()))
{
HDUtils.SetRenderTarget(cmd, m_AmbientOcclusionTex);
m_ResolvePropertyBlock.SetTexture(HDShaderIDs._DepthValuesTexture, sharedRTManager.GetDepthValuesTexture());
m_ResolvePropertyBlock.SetTexture(HDShaderIDs._MultiAmbientOcclusionTexture, m_MultiAmbientOcclusionTex);
cmd.DrawProcedural(Matrix4x4.identity, m_ResolveMaterial, 0, MeshTopology.Triangles, 3, 1, m_ResolvePropertyBlock);
}
}
cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, m_AmbientOcclusionTex);
cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(0f, 0f, 0f, settings.directLightingStrength.value));
// TODO: All the pushdebug stuff should be centralized somewhere
(RenderPipelineManager.currentPipeline as HDRenderPipeline).PushFullScreenDebugTexture(camera, cmd, m_AmbientOcclusionTex, FullScreenDebugMode.SSAO);
}
void Alloc(out RTHandle rt, MipLevel size, GraphicsFormat format, bool uav, string name)
{
rt = RTHandles.Alloc(
scaleFunc: m_ScaleFunctors[(int)size],
dimension: TextureDimension.Tex2D,
colorFormat: format,
depthBufferBits: DepthBits.None,
autoGenerateMips: false,
enableMSAA: false,
useDynamicScale: true,
enableRandomWrite: uav,
filterMode: FilterMode.Point,
xrInstancing: true,
name: name
);
}
void AllocArray(out RTHandle rt, MipLevel size, GraphicsFormat format, bool uav, string name)
{
rt = RTHandles.Alloc(
scaleFunc: m_ScaleFunctors[(int)size],
dimension: TextureDimension.Tex2DArray,
colorFormat: format,
depthBufferBits: DepthBits.None,
slices: 16,
autoGenerateMips: false,
enableMSAA: false,
useDynamicScale: true,
enableRandomWrite: uav,
filterMode: FilterMode.Point,
xrInstancing: true,
name: name
);
}
float CalculateTanHalfFovHeight(HDCamera camera)
{
// XRTODO: handle XR instancing by looping over camera.xrViewConstants
return 1f / camera.mainViewConstants.projMatrix[0, 0];
}
Vector2 GetSize(MipLevel mip)
{
return new Vector2(m_Widths[(int)mip], m_Heights[(int)mip]);
}
Vector3 GetSizeArray(MipLevel mip)
{
return new Vector3(m_Widths[(int)mip], m_Heights[(int)mip], 16);
}
void PushDownsampleCommands(CommandBuffer cmd, HDCamera camera, RTHandle depthMap, bool msaa)
{
var kernelName = msaa ? "KMain_MSAA" : "KMain";
// 1st downsampling pass.
var cs = m_Resources.shaders.aoDownsample1CS;
int kernel = cs.FindKernel(kernelName);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._LinearZ, m_LinearDepthTex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS2x, m_LowDepth1Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS4x, m_LowDepth2Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS2xAtlas, m_TiledDepth1Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS4xAtlas, m_TiledDepth2Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._Depth, depthMap, 0);
cmd.DispatchCompute(cs, kernel, m_Widths[(int)MipLevel.L4], m_Heights[(int)MipLevel.L4], camera.computePassCount);
// 2nd downsampling pass.
cs = m_Resources.shaders.aoDownsample2CS;
kernel = cs.FindKernel(kernelName);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS4x, m_LowDepth2Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS8x, m_LowDepth3Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS16x, m_LowDepth4Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS8xAtlas, m_TiledDepth3Tex);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._DS16xAtlas, m_TiledDepth4Tex);
cmd.DispatchCompute(cs, kernel, m_Widths[(int)MipLevel.L6], m_Heights[(int)MipLevel.L6], camera.computePassCount);
}
void PushRenderCommands(CommandBuffer cmd, HDCamera camera, in Vector4 viewport, RTHandle source, RTHandle destination, AmbientOcclusion settings, in Vector3 sourceSize, float tanHalfFovH, bool msaa)
{
// Here we compute multipliers that convert the center depth value into (the reciprocal
// of) sphere thicknesses at each sample location. This assumes a maximum sample radius
// of 5 units, but since a sphere has no thickness at its extent, we don't need to
// sample that far out. Only samples whole integer offsets with distance less than 25
// are used. This means that there is no sample at (3, 4) because its distance is
// exactly 25 (and has a thickness of 0.)
// The shaders are set up to sample a circular region within a 5-pixel radius.
const float kScreenspaceDiameter = 10f;
// SphereDiameter = CenterDepth * ThicknessMultiplier. This will compute the thickness
// of a sphere centered at a specific depth. The ellipsoid scale can stretch a sphere
// into an ellipsoid, which changes the characteristics of the AO.
// TanHalfFovH: Radius of sphere in depth units if its center lies at Z = 1
// ScreenspaceDiameter: Diameter of sample sphere in pixel units
// ScreenspaceDiameter / BufferWidth: Ratio of the screen width that the sphere actually covers
float thicknessMultiplier = 2f * tanHalfFovH * kScreenspaceDiameter / sourceSize.x;
// This will transform a depth value from [0, thickness] to [0, 1].
float inverseRangeFactor = 1f / thicknessMultiplier;
// The thicknesses are smaller for all off-center samples of the sphere. Compute
// thicknesses relative to the center sample.
for (int i = 0; i < 12; i++)
m_InvThicknessTable[i] = inverseRangeFactor / m_SampleThickness[i];
// These are the weights that are multiplied against the samples because not all samples
// are equally important. The farther the sample is from the center location, the less
// they matter. We use the thickness of the sphere to determine the weight. The scalars
// in front are the number of samples with this weight because we sum the samples
// together before multiplying by the weight, so as an aggregate all of those samples
// matter more. After generating this table, the weights are normalized.
m_SampleWeightTable[ 0] = 4 * m_SampleThickness[ 0]; // Axial
m_SampleWeightTable[ 1] = 4 * m_SampleThickness[ 1]; // Axial
m_SampleWeightTable[ 2] = 4 * m_SampleThickness[ 2]; // Axial
m_SampleWeightTable[ 3] = 4 * m_SampleThickness[ 3]; // Axial
m_SampleWeightTable[ 4] = 4 * m_SampleThickness[ 4]; // Diagonal
m_SampleWeightTable[ 5] = 8 * m_SampleThickness[ 5]; // L-shaped
m_SampleWeightTable[ 6] = 8 * m_SampleThickness[ 6]; // L-shaped
m_SampleWeightTable[ 7] = 8 * m_SampleThickness[ 7]; // L-shaped
m_SampleWeightTable[ 8] = 4 * m_SampleThickness[ 8]; // Diagonal
m_SampleWeightTable[ 9] = 8 * m_SampleThickness[ 9]; // L-shaped
m_SampleWeightTable[10] = 8 * m_SampleThickness[10]; // L-shaped
m_SampleWeightTable[11] = 4 * m_SampleThickness[11]; // Diagonal
// Zero out the unused samples.
// FIXME: should we support SAMPLE_EXHAUSTIVELY mode?
m_SampleWeightTable[0] = 0;
m_SampleWeightTable[2] = 0;
m_SampleWeightTable[5] = 0;
m_SampleWeightTable[7] = 0;
m_SampleWeightTable[9] = 0;
// Normalize the weights by dividing by the sum of all weights
float totalWeight = 0f;
foreach (float w in m_SampleWeightTable)
totalWeight += w;
for (int i = 0; i < m_SampleWeightTable.Length; i++)
m_SampleWeightTable[i] /= totalWeight;
// Set the arguments for the render kernel.
var cs = m_Resources.shaders.aoRenderCS;
int kernel = cs.FindKernel(msaa ? "KMainInterleaved_MSAA" : "KMainInterleaved");
cmd.SetComputeFloatParams(cs, HDShaderIDs._InvThicknessTable, m_InvThicknessTable);
cmd.SetComputeFloatParams(cs, HDShaderIDs._SampleWeightTable, m_SampleWeightTable);
cmd.SetComputeVectorParam(cs, HDShaderIDs._InvSliceDimension, new Vector2(1f / sourceSize.x * viewport.x, 1f / sourceSize.y * viewport.y));
cmd.SetComputeVectorParam(cs, HDShaderIDs._AdditionalParams, new Vector2(-1f / settings.thicknessModifier.value, settings.intensity.value));
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._Depth, source);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._Occlusion, destination);
// Calculate the thread group count and add a dispatch command with them.
cs.GetKernelThreadGroupSizes(kernel, out var xsize, out var ysize, out var zsize);
cmd.DispatchCompute(
cs, kernel,
((int)sourceSize.x + (int)xsize - 1) / (int)xsize,
((int)sourceSize.y + (int)ysize - 1) / (int)ysize,
camera.computePassCount * ((int)sourceSize.z + (int)zsize - 1) / (int)zsize
);
}
void PushUpsampleCommands(CommandBuffer cmd, HDCamera camera, in Vector4 viewport, RTHandle lowResDepth, RTHandle interleavedAO, RTHandle highResDepth, RTHandle highResAO, RTHandle dest, AmbientOcclusion settings, in Vector3 lowResDepthSize, in Vector2 highResDepthSize, bool msaa)
{
var cs = m_Resources.shaders.aoUpsampleCS;
int kernel = msaa
? cs.FindKernel(highResAO == null ? "KMainInvert_MSAA" : "KMainBlendout_MSAA")
: cs.FindKernel(highResAO == null ? "KMainInvert" : "KMainBlendout");
float stepSize = 1920f / lowResDepthSize.x;
float bTolerance = 1f - Mathf.Pow(10f, settings.blurTolerance.value) * stepSize;
bTolerance *= bTolerance;
float uTolerance = Mathf.Pow(10f, settings.upsampleTolerance.value);
float noiseFilterWeight = 1f / (Mathf.Pow(10f, settings.noiseFilterTolerance.value) + uTolerance);
cmd.SetComputeVectorParam(cs, HDShaderIDs._InvLowResolution, new Vector2(1f / lowResDepthSize.x * viewport.x, 1f / lowResDepthSize.y * viewport.y));
cmd.SetComputeVectorParam(cs, HDShaderIDs._InvHighResolution, new Vector2(1f / highResDepthSize.x * viewport.x, 1f / highResDepthSize.y * viewport.y));
cmd.SetComputeVectorParam(cs, HDShaderIDs._AdditionalParams, new Vector4(noiseFilterWeight, stepSize, bTolerance, uTolerance));
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._LoResDB, lowResDepth);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._HiResDB, highResDepth);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._LoResAO1, interleavedAO);
if (highResAO != null)
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._HiResAO, highResAO);
cmd.SetComputeTextureParam(cs, kernel, HDShaderIDs._AoResult, dest);
int xcount = ((int)highResDepthSize.x + 17) / 16;
int ycount = ((int)highResDepthSize.y + 17) / 16;
cmd.DispatchCompute(cs, kernel, xcount, ycount, camera.computePassCount);
}
}
}
| |
using System;
using System.Collections.Generic;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Localization;
namespace Nop.Core.Domain.Catalog
{
/// <summary>
/// Represents a product variant
/// </summary>
public partial class ProductVariant : BaseEntity, ILocalizedEntity
{
private ICollection<ProductVariantAttribute> _productVariantAttributes;
private ICollection<ProductVariantAttributeCombination> _productVariantAttributeCombinations;
private ICollection<TierPrice> _tierPrices;
private ICollection<Discount> _appliedDiscounts;
/// <summary>
/// Gets or sets the product identifier
/// </summary>
public virtual int ProductId { get; set; }
/// <summary>
/// Gets or sets the name
/// </summary>
public virtual string Name { get; set; }
/// <summary>
/// Gets or sets the SKU
/// </summary>
public virtual string Sku { get; set; }
/// <summary>
/// Gets or sets the description
/// </summary>
public virtual string Description { get; set; }
/// <summary>
/// Gets or sets the admin comment
/// </summary>
public virtual string AdminComment { get; set; }
/// <summary>
/// Gets or sets the manufacturer part number
/// </summary>
public virtual string ManufacturerPartNumber { get; set; }
/// <summary>
/// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in Europe), JAN (in Japan), and ISBN (for books).
/// </summary>
public virtual string Gtin { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product variant is gift card
/// </summary>
public virtual bool IsGiftCard { get; set; }
/// <summary>
/// Gets or sets the gift card type identifier
/// </summary>
public virtual int GiftCardTypeId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product variant requires that other product variants are added to the cart (Product X requires Product Y)
/// </summary>
public virtual bool RequireOtherProducts { get; set; }
/// <summary>
/// Gets or sets a required product variant identifiers (comma separated)
/// </summary>
public virtual string RequiredProductVariantIds { get; set; }
/// <summary>
/// Gets or sets a value indicating whether required product variants are automatically added to the cart
/// </summary>
public virtual bool AutomaticallyAddRequiredProductVariants { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product variant is download
/// </summary>
public virtual bool IsDownload { get; set; }
/// <summary>
/// Gets or sets the download identifier
/// </summary>
public virtual int DownloadId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this downloadable product can be downloaded unlimited number of times
/// </summary>
public virtual bool UnlimitedDownloads { get; set; }
/// <summary>
/// Gets or sets the maximum number of downloads
/// </summary>
public virtual int MaxNumberOfDownloads { get; set; }
/// <summary>
/// Gets or sets the number of days during customers keeps access to the file.
/// </summary>
public virtual int? DownloadExpirationDays { get; set; }
/// <summary>
/// Gets or sets the download activation type
/// </summary>
public virtual int DownloadActivationTypeId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product variant has a sample download file
/// </summary>
public virtual bool HasSampleDownload { get; set; }
/// <summary>
/// Gets or sets the sample download identifier
/// </summary>
public virtual int SampleDownloadId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product has user agreement
/// </summary>
public virtual bool HasUserAgreement { get; set; }
/// <summary>
/// Gets or sets the text of license agreement
/// </summary>
public virtual string UserAgreementText { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product variant is recurring
/// </summary>
public virtual bool IsRecurring { get; set; }
/// <summary>
/// Gets or sets the cycle length
/// </summary>
public virtual int RecurringCycleLength { get; set; }
/// <summary>
/// Gets or sets the cycle period
/// </summary>
public virtual int RecurringCyclePeriodId { get; set; }
/// <summary>
/// Gets or sets the total cycles
/// </summary>
public virtual int RecurringTotalCycles { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is ship enabled
/// </summary>
public virtual bool IsShipEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is free shipping
/// </summary>
public virtual bool IsFreeShipping { get; set; }
/// <summary>
/// Gets or sets the additional shipping charge
/// </summary>
public virtual decimal AdditionalShippingCharge { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product variant is marked as tax exempt
/// </summary>
public virtual bool IsTaxExempt { get; set; }
/// <summary>
/// Gets or sets the tax category identifier
/// </summary>
public virtual int TaxCategoryId { get; set; }
/// <summary>
/// Gets or sets a value indicating how to manage inventory
/// </summary>
public virtual int ManageInventoryMethodId { get; set; }
/// <summary>
/// Gets or sets the stock quantity
/// </summary>
public virtual int StockQuantity { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to display stock availability
/// </summary>
public virtual bool DisplayStockAvailability { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to display stock quantity
/// </summary>
public virtual bool DisplayStockQuantity { get; set; }
/// <summary>
/// Gets or sets the minimum stock quantity
/// </summary>
public virtual int MinStockQuantity { get; set; }
/// <summary>
/// Gets or sets the low stock activity identifier
/// </summary>
public virtual int LowStockActivityId { get; set; }
/// <summary>
/// Gets or sets the quantity when admin should be notified
/// </summary>
public virtual int NotifyAdminForQuantityBelow { get; set; }
/// <summary>
/// Gets or sets a value backorder mode identifier
/// </summary>
public virtual int BackorderModeId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to back in stock subscriptions are allowed
/// </summary>
public virtual bool AllowBackInStockSubscriptions { get; set; }
/// <summary>
/// Gets or sets the order minimum quantity
/// </summary>
public virtual int OrderMinimumQuantity { get; set; }
/// <summary>
/// Gets or sets the order maximum quantity
/// </summary>
public virtual int OrderMaximumQuantity { get; set; }
/// <summary>
/// Gets or sets the comma seperated list of allowed quantities. null or empty if any quantity is allowed
/// </summary>
public virtual string AllowedQuantities { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to disable buy (Add to cart) button
/// </summary>
public virtual bool DisableBuyButton { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to disable "Add to wishlist" button
/// </summary>
public virtual bool DisableWishlistButton { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this item is available for Pre-Order
/// </summary>
public virtual bool AvailableForPreOrder { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to show "Call for Pricing" or "Call for quote" instead of price
/// </summary>
public virtual bool CallForPrice { get; set; }
/// <summary>
/// Gets or sets the price
/// </summary>
public virtual decimal Price { get; set; }
/// <summary>
/// Gets or sets the old price
/// </summary>
public virtual decimal OldPrice { get; set; }
/// <summary>
/// Gets or sets the product cost
/// </summary>
public virtual decimal ProductCost { get; set; }
/// <summary>
/// Gets or sets the product special price
/// </summary>
public virtual decimal? SpecialPrice { get; set; }
/// <summary>
/// Gets or sets the start date and time of the special price
/// </summary>
public virtual DateTime? SpecialPriceStartDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets the end date and time of the special price
/// </summary>
public virtual DateTime? SpecialPriceEndDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a customer enters price
/// </summary>
public virtual bool CustomerEntersPrice { get; set; }
/// <summary>
/// Gets or sets the minimum price entered by a customer
/// </summary>
public virtual decimal MinimumCustomerEnteredPrice { get; set; }
/// <summary>
/// Gets or sets the maximum price entered by a customer
/// </summary>
public virtual decimal MaximumCustomerEnteredPrice { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this product variant has tier prices configured
/// <remarks>The same as if we run variant.TierPrices.Count > 0
/// We use this property for performance optimization:
/// if this property is set to false, then we do not need to load tier prices navifation property
/// </remarks>
/// </summary>
public virtual bool HasTierPrices { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this product variant has discounts applied
/// <remarks>The same as if we run variant.AppliedDiscounts.Count > 0
/// We use this property for performance optimization:
/// if this property is set to false, then we do not need to load Applied Discounts navifation property
/// </remarks>
/// </summary>
public virtual bool HasDiscountsApplied { get; set; }
/// <summary>
/// Gets or sets the weight
/// </summary>
public virtual decimal Weight { get; set; }
/// <summary>
/// Gets or sets the length
/// </summary>
public virtual decimal Length { get; set; }
/// <summary>
/// Gets or sets the width
/// </summary>
public virtual decimal Width { get; set; }
/// <summary>
/// Gets or sets the height
/// </summary>
public virtual decimal Height { get; set; }
/// <summary>
/// Gets or sets the picture identifier
/// </summary>
public virtual int PictureId { get; set; }
/// <summary>
/// Gets or sets the available start date and time
/// </summary>
public virtual DateTime? AvailableStartDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets the available end date and time
/// </summary>
public virtual DateTime? AvailableEndDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is published
/// </summary>
public virtual bool Published { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity has been deleted
/// </summary>
public virtual bool Deleted { get; set; }
/// <summary>
/// Gets or sets the display order
/// </summary>
public virtual int DisplayOrder { get; set; }
/// <summary>
/// Gets or sets the date and time of instance creation
/// </summary>
public virtual DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the date and time of instance update
/// </summary>
public virtual DateTime UpdatedOnUtc { get; set; }
/// <summary>
/// Gets the full product name
/// </summary>
public virtual string FullProductName
{
get
{
Product product = this.Product;
if (product != null)
{
if (!string.IsNullOrWhiteSpace(this.Name))
return product.Name + " (" + this.Name + ")";
return product.Name;
}
return string.Empty;
}
}
/// <summary>
/// Gets or sets the backorder mode
/// </summary>
public virtual BackorderMode BackorderMode
{
get
{
return (BackorderMode)this.BackorderModeId;
}
set
{
this.BackorderModeId = (int)value;
}
}
/// <summary>
/// Gets or sets the download activation type
/// </summary>
public virtual DownloadActivationType DownloadActivationType
{
get
{
return (DownloadActivationType)this.DownloadActivationTypeId;
}
set
{
this.DownloadActivationTypeId = (int)value;
}
}
/// <summary>
/// Gets or sets the gift card type
/// </summary>
public virtual GiftCardType GiftCardType
{
get
{
return (GiftCardType)this.GiftCardTypeId;
}
set
{
this.GiftCardTypeId = (int)value;
}
}
/// <summary>
/// Gets or sets the low stock activity
/// </summary>
public virtual LowStockActivity LowStockActivity
{
get
{
return (LowStockActivity)this.LowStockActivityId;
}
set
{
this.LowStockActivityId = (int)value;
}
}
/// <summary>
/// Gets or sets the value indicating how to manage inventory
/// </summary>
public virtual ManageInventoryMethod ManageInventoryMethod
{
get
{
return (ManageInventoryMethod)this.ManageInventoryMethodId;
}
set
{
this.ManageInventoryMethodId = (int)value;
}
}
/// <summary>
/// Gets or sets the cycle period for recurring products
/// </summary>
public virtual RecurringProductCyclePeriod RecurringCyclePeriod
{
get
{
return (RecurringProductCyclePeriod)this.RecurringCyclePeriodId;
}
set
{
this.RecurringCyclePeriodId = (int)value;
}
}
/// <summary>
/// Gets or sets the product
/// </summary>
public virtual Product Product { get; set; }
/// <summary>
/// Gets or sets the product variant attributes
/// </summary>
public virtual ICollection<ProductVariantAttribute> ProductVariantAttributes
{
get { return _productVariantAttributes ?? (_productVariantAttributes = new List<ProductVariantAttribute>()); }
protected set { _productVariantAttributes = value; }
}
/// <summary>
/// Gets or sets the product variant attribute combinations
/// </summary>
public virtual ICollection<ProductVariantAttributeCombination> ProductVariantAttributeCombinations
{
get { return _productVariantAttributeCombinations ?? (_productVariantAttributeCombinations = new List<ProductVariantAttributeCombination>()); }
protected set { _productVariantAttributeCombinations = value; }
}
/// <summary>
/// Gets or sets the tier prices
/// </summary>
public virtual ICollection<TierPrice> TierPrices
{
get { return _tierPrices ?? (_tierPrices = new List<TierPrice>()); }
protected set { _tierPrices = value; }
}
/// <summary>
/// Gets or sets the collection of applied discounts
/// </summary>
public virtual ICollection<Discount> AppliedDiscounts
{
get { return _appliedDiscounts ?? (_appliedDiscounts = new List<Discount>()); }
protected set { _appliedDiscounts = value; }
}
}
}
| |
/*
* 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.Collections.Specialized;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects avatar presence information (for tracking current location and
/// message routing) to the SimianGrid backend
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianPresenceServiceConnector")]
public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_serverUrl = String.Empty;
private SimianActivityDetector m_activityDetector;
private bool m_Enabled = false;
#region ISharedRegionModule
public Type ReplaceableInterface { get { return null; } }
public void RegionLoaded(Scene scene) { }
public void PostInitialise() { }
public void Close() { }
public SimianPresenceServiceConnector() { }
public string Name { get { return "SimianPresenceServiceConnector"; } }
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
scene.RegisterModuleInterface<IPresenceService>(this);
scene.RegisterModuleInterface<IGridUserService>(this);
m_activityDetector.AddRegion(scene);
LogoutRegionAgents(scene.RegionInfo.RegionID);
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IPresenceService>(this);
scene.UnregisterModuleInterface<IGridUserService>(this);
m_activityDetector.RemoveRegion(scene);
LogoutRegionAgents(scene.RegionInfo.RegionID);
}
}
#endregion ISharedRegionModule
public SimianPresenceServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("PresenceServices", "");
if (name == Name)
CommonInit(source);
}
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["PresenceService"];
if (gridConfig != null)
{
string serviceUrl = gridConfig.GetString("PresenceServerURI");
if (!String.IsNullOrEmpty(serviceUrl))
{
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_serverUrl = serviceUrl;
m_activityDetector = new SimianActivityDetector(this);
m_Enabled = true;
}
}
if (String.IsNullOrEmpty(m_serverUrl))
m_log.Info("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI specified, disabling connector");
}
#region IPresenceService
public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
{
m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}",
userID, sessionID, secureSessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddSession" },
{ "UserID", userID.ToString() }
};
if (sessionID != UUID.Zero)
{
requestArgs["SessionID"] = sessionID.ToString();
requestArgs["SecureSessionID"] = secureSessionID.ToString();
}
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString());
return success;
}
public bool LogoutAgent(UUID sessionID)
{
// m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveSession" },
{ "SessionID", sessionID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString());
return success;
}
public bool LogoutRegionAgents(UUID regionID)
{
// m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "RemoveSessions" },
{ "SceneID", regionID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString());
return success;
}
public bool ReportAgent(UUID sessionID, UUID regionID)
{
// Not needed for SimianGrid
return true;
}
public PresenceInfo GetAgent(UUID sessionID)
{
OSDMap sessionResponse = GetSessionDataFromSessionID(sessionID);
if (sessionResponse == null)
{
m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session {0}: {1}",sessionID.ToString(),sessionResponse["Message"].AsString());
return null;
}
UUID userID = sessionResponse["UserID"].AsUUID();
OSDMap userResponse = GetUserData(userID);
if (userResponse == null)
{
m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for {0}: {1}",userID.ToString(),userResponse["Message"].AsString());
return null;
}
return ResponseToPresenceInfo(sessionResponse);
}
public PresenceInfo[] GetAgents(string[] userIDs)
{
List<PresenceInfo> presences = new List<PresenceInfo>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetSessions" },
{ "UserIDList", String.Join(",",userIDs) }
};
OSDMap sessionListResponse = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (! sessionListResponse["Success"].AsBoolean())
{
m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve sessions: {0}",sessionListResponse["Message"].AsString());
return null;
}
OSDArray sessionList = sessionListResponse["Sessions"] as OSDArray;
for (int i = 0; i < sessionList.Count; i++)
{
OSDMap sessionInfo = sessionList[i] as OSDMap;
presences.Add(ResponseToPresenceInfo(sessionInfo));
}
return presences.ToArray();
}
#endregion IPresenceService
#region IGridUserService
public GridUserInfo LoggedIn(string userID)
{
// Never implemented at the sim
return null;
}
public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Logging out user " + userID);
// Remove the session to mark this user offline
if (!LogoutAgent(sessionID))
return false;
// Save our last position as user data
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString());
return success;
}
public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "HomeLocation", SerializeLocation(regionID, position, lookAt) }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString());
return success;
}
public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
return UpdateSession(sessionID, regionID, lastPosition, lastLookAt);
}
public GridUserInfo GetGridUserInfo(string user)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user);
UUID userID = new UUID(user);
OSDMap userResponse = GetUserData(userID);
if (userResponse == null)
{
m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for {0}", userID);
}
// Note that ResponseToGridUserInfo properly checks for and returns a null if passed a null.
return ResponseToGridUserInfo(userResponse);
}
#endregion
#region Helpers
private OSDMap GetUserData(UUID userID)
{
// m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean() && response["User"] is OSDMap)
return response;
m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for {0}; {1}",userID.ToString(),response["Message"].AsString());
return null;
}
private OSDMap GetSessionDataFromSessionID(UUID sessionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetSession" },
{ "SessionID", sessionID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
return response;
m_log.WarnFormat("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session data for {0}; {1}",sessionID.ToString(),response["Message"].AsString());
return null;
}
private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
// Save our current location as session data
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "UpdateSession" },
{ "SessionID", sessionID.ToString() },
{ "SceneID", regionID.ToString() },
{ "ScenePosition", lastPosition.ToString() },
{ "SceneLookAt", lastLookAt.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString());
return success;
}
private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse)
{
if (sessionResponse == null)
return null;
PresenceInfo info = new PresenceInfo();
info.UserID = sessionResponse["UserID"].AsUUID().ToString();
info.RegionID = sessionResponse["SceneID"].AsUUID();
return info;
}
private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse)
{
if (userResponse != null && userResponse["User"] is OSDMap)
{
GridUserInfo info = new GridUserInfo();
info.Online = true;
info.UserID = userResponse["UserID"].AsUUID().ToString();
info.LastRegionID = userResponse["SceneID"].AsUUID();
info.LastPosition = userResponse["ScenePosition"].AsVector3();
info.LastLookAt = userResponse["SceneLookAt"].AsVector3();
OSDMap user = (OSDMap)userResponse["User"];
info.Login = user["LastLoginDate"].AsDate();
info.Logout = user["LastLogoutDate"].AsDate();
DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt);
return info;
}
return null;
}
private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt)
{
return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}";
}
private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt)
{
OSDMap map = null;
try { map = OSDParser.DeserializeJson(location) as OSDMap; }
catch { }
if (map != null)
{
regionID = map["SceneID"].AsUUID();
if (Vector3.TryParse(map["Position"].AsString(), out position) &&
Vector3.TryParse(map["LookAt"].AsString(), out lookAt))
{
return true;
}
}
regionID = UUID.Zero;
position = Vector3.Zero;
lookAt = Vector3.Zero;
return false;
}
public GridUserInfo[] GetGridUserInfo(string[] userIDs)
{
return new GridUserInfo[0];
}
#endregion Helpers
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
namespace SharpDX.Toolkit.Graphics
{
internal class EffectParser
{
/// <summary>
/// End of file token.
/// </summary>
private static readonly Token EndOfFile = new Token(TokenType.EndOfFile, null, new SourceSpan());
private int bracketCount = 0;
private int curlyBraceCount = 0;
private string currentFile;
private int currentLine;
private int currentLineAbsolutePos;
private Ast.Pass currentPass;
private List<Token> currentPreviewTokens = new List<Token>();
private Ast.Technique currentTechnique;
private Token currentToken;
private bool isPreviewToken = false;
private int parentCount = 0;
private List<Token> previewTokens = new List<Token>();
private EffectParserResult result;
private Token savedPreviewToken;
private IEnumerator<Token> tokenEnumerator;
private List<string> includeDirectoryList;
private string newPreprocessedSource;
/// <summary>
/// Initializes a new instance of the <see cref="EffectParser" /> class.
/// </summary>
public EffectParser()
{
includeDirectoryList = new List<string>();
Macros = new List<ShaderMacro>();
}
/// <summary>
/// Gets or sets the include file callback.
/// </summary>
/// <value>The include file callback.</value>
public IncludeFileDelegate IncludeFileCallback { get; set; }
/// <summary>
/// Gets the macros.
/// </summary>
/// <value>The macros.</value>
public List<ShaderMacro> Macros { get; private set; }
/// <summary>
/// Gets the include directory list.
/// </summary>
/// <value>The include directory list.</value>
public List<string> IncludeDirectoryList
{
get { return includeDirectoryList; }
}
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value>The logger.</value>
public EffectCompilerLogger Logger { get; set; }
/// <summary>
/// Parses the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>Result of parsing</returns>
private EffectParserResult PrepareParsing(string input, string fileName)
{
var filePath = Path.GetFullPath(fileName);
fileName = Path.GetFileName(fileName);
var localResult = new EffectParserResult
{
SourceFileName = Path.Combine(Environment.CurrentDirectory, filePath),
IncludeHandler = new FileIncludeHandler { Logger = Logger }
};
localResult.IncludeHandler.CurrentDirectory.Push(Path.GetDirectoryName(localResult.SourceFileName));
localResult.IncludeHandler.IncludeDirectories.AddRange(IncludeDirectoryList);
localResult.IncludeHandler.IncludeFileCallback = IncludeFileCallback;
localResult.IncludeHandler.FileResolved.Add(fileName, new FileIncludeHandler.FileItem(fileName, filePath, File.GetLastWriteTime(filePath)));
string compilationErrors = null;
var preprocessedInput = ShaderBytecode.Preprocess(input, Macros.ToArray(), localResult.IncludeHandler, out compilationErrors, filePath);
localResult.PreprocessedSource = preprocessedInput;
localResult.DependencyList = CalculateDependencies(localResult);
return localResult;
}
/// <summary>
/// Continues the parsing.
/// </summary>
/// <param name="previousParsing">The previous parsing.</param>
/// <returns>EffectParserResult.</returns>
private EffectParserResult ContinueParsing(EffectParserResult previousParsing)
{
// Reset count
parentCount = 0;
curlyBraceCount = 0;
bracketCount = 0;
result = previousParsing;
newPreprocessedSource = result.PreprocessedSource;
tokenEnumerator = Tokenizer.Run(previousParsing.PreprocessedSource).GetEnumerator();
do
{
var token = NextToken();
if (token.Type == TokenType.EndOfFile)
break;
switch (token.Type)
{
case TokenType.Identifier:
if ((token.EqualString("technique") || token.EqualString("technique10") || token.EqualString("technique11")) && curlyBraceCount == 0)
ParseTechnique();
break;
}
} while (true);
if (!CheckAllBracketsClosed())
{
if (parentCount != 0)
{
Logger.Error("Error matching closing parentheses for '('", lastParentToken.Span);
}
if (bracketCount != 0)
{
Logger.Error("Error matching closing bracket for '['", lastBracketToken.Span);
}
if (curlyBraceCount != 0)
{
Logger.Error("Error matching closing curly brace for '{'", lastCurlyBraceToken.Span);
}
}
result.PreprocessedSource = newPreprocessedSource;
return result;
}
/// <summary>
/// Parses the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>Result of parsing</returns>
public EffectParserResult Parse(string input, string fileName)
{
return ContinueParsing(PrepareParsing(input, fileName));
}
private bool CheckAllBracketsClosed()
{
return parentCount == 0 && bracketCount == 0 && curlyBraceCount == 0;
}
private Token lastParentToken;
private Token lastBracketToken;
private Token lastCurlyBraceToken;
private bool HandleBrackets(Token token)
{
bool isBracketOk = true;
switch (token.Type)
{
case TokenType.LeftParent:
lastParentToken = token;
parentCount++;
break;
case TokenType.RightParent:
lastParentToken = token;
parentCount--;
if (parentCount < 0)
{
parentCount = 0;
Logger.Error("No matching parenthesis '(' for this closing token.", token.Span);
isBracketOk = false;
}
break;
case TokenType.LeftBracket:
lastBracketToken = token;
bracketCount++;
break;
case TokenType.RightBracket:
lastBracketToken = token;
bracketCount--;
if (bracketCount < 0)
{
bracketCount = 0;
Logger.Error("No matching bracket '[' for this closing token.", token.Span);
isBracketOk = false;
}
break;
case TokenType.LeftCurlyBrace:
lastCurlyBraceToken = token;
curlyBraceCount++;
break;
case TokenType.RightCurlyBrace:
lastCurlyBraceToken = token;
curlyBraceCount--;
if (curlyBraceCount < 0)
{
curlyBraceCount = 0;
Logger.Error("No matching curly brace '{{' for this closing token.", token.Span);
isBracketOk = false;
}
break;
}
return isBracketOk;
}
private void BeginPreviewToken()
{
isPreviewToken = true;
savedPreviewToken = currentToken;
}
private void EndPreviewToken()
{
isPreviewToken = false;
previewTokens = currentPreviewTokens;
currentPreviewTokens = new List<Token>();
currentToken = savedPreviewToken;
}
private Token NextToken()
{
var token = InternalNextToken();
// Handle preprocessor "line"
while (token.Type == TokenType.Preprocessor)
{
InternalNextToken();
if (!Expect("line"))
{
Logger.Error("Unsupported preprocessor token [{0}]. Only #line is supported.", token.Span, currentToken.Value);
return currentToken;
}
if (!ExpectNext(TokenType.Number))
return currentToken;
// Set currentLine - 1 as the NL at the end of the preprocessor line will add +1
currentLine = int.Parse(currentToken.Value) - 1;
// Check next token
token = InternalNextToken();
// If this is a string, then this is the end of preprocessor line
if (token.Type == TokenType.String)
{
currentFile = token.Value.Substring(1, token.Value.Length - 2);
// Replace "file" from #line preprocessor with the actual full path.
var includeHandler = result.IncludeHandler;
if (includeHandler.FileResolved.ContainsKey(currentFile))
{
var fullPathFile = includeHandler.FileResolved[currentFile].FilePath;
// This is not 100% accurate, but it is better than having invalid file path
newPreprocessedSource = newPreprocessedSource.Replace(token.Value, "\"" + fullPathFile + "\"");
currentFile = fullPathFile;
}
currentFile = currentFile.Replace(@"\\", @"\");
token = InternalNextToken();
}
}
// Set correct location for current token
currentToken.Span.Line = currentLine;
currentToken.Span.Column = token.Span.Index - currentLineAbsolutePos + 1;
currentToken.Span.FilePath = currentFile;
return currentToken;
}
private Token InternalNextToken()
{
// TODO: token preview is not safe with NewLine count
if (previewTokens.Count > 0)
{
currentToken = previewTokens[0];
previewTokens.RemoveAt(0);
if (isPreviewToken)
currentPreviewTokens.Add(currentToken);
return currentToken;
}
while (tokenEnumerator.MoveNext())
{
currentToken = tokenEnumerator.Current;
if (currentToken.Type == TokenType.Newline)
{
currentLine++;
currentLineAbsolutePos = currentToken.Span.Index + currentToken.Span.Length;
}
else
{
currentToken.Span.Line = currentLine;
currentToken.Span.Column = currentToken.Span.Index - currentLineAbsolutePos + 1;
currentToken.Span.FilePath = currentFile;
HandleBrackets(currentToken);
if (isPreviewToken)
currentPreviewTokens.Add(currentToken);
return currentToken;
}
}
currentToken = EndOfFile;
return currentToken;
}
private bool ExpectNext(TokenType tokenType)
{
NextToken();
return Expect(tokenType);
}
private bool Expect(TokenType tokenType)
{
bool isSameTokenType = currentToken.Type == tokenType;
if (!isSameTokenType)
Logger.Error("Error while parsing unexpected token [{0}]. Expecting token [{1}]", currentToken.Span, currentToken.Value, tokenType);
return isSameTokenType;
}
private bool Expect(string keyword, bool isCaseSensitive = false)
{
if (Expect(TokenType.Identifier))
{
if (!(currentToken.EqualString(keyword, isCaseSensitive)))
{
Logger.Error("Error while parsing unexpected keyword [{0}]. Expecting keyword [{1}]", currentToken.Span, currentToken.Value, keyword);
}
else
{
return true;
}
}
return false;
}
private void ParseTechnique()
{
var technique = new Ast.Technique() {Span = currentToken.Span};
// Get Technique name if any.
var ident = NextToken();
if (ident.Type == TokenType.Identifier)
{
technique.Name = ident.Value;
NextToken();
}
if (!Expect(TokenType.LeftCurlyBrace))
return;
// Add the technique being parsed
currentTechnique = technique;
bool continueParsingTecnhique = true;
bool isParseOk = false;
do
{
var token = NextToken();
switch (token.Type)
{
case TokenType.Identifier:
if (token.EqualString("pass"))
ParsePass();
break;
case TokenType.RightCurlyBrace:
isParseOk = true;
continueParsingTecnhique = false;
break;
default:
Logger.Error("Unexpected token [{0}]. Expecting tokens ['pass','}}']", currentToken.Span, currentToken);
continueParsingTecnhique = false;
break;
}
} while (continueParsingTecnhique);
if (isParseOk)
{
if (result.Shader == null)
result.Shader = new Ast.Shader();
result.Shader.Techniques.Add(technique);
}
}
private void ParsePass()
{
var pass = new Ast.Pass() {Span = currentToken.Span};
// Get Pass name if any.
var ident = NextToken();
if (ident.Type == TokenType.Identifier)
{
pass.Name = ident.Value;
NextToken();
}
if (!Expect(TokenType.LeftCurlyBrace))
return;
// Add the technique being parsed
currentPass = pass;
bool continueParsingTecnhique = true;
bool isParseOk = false;
do
{
var token = NextToken();
switch (token.Type)
{
case TokenType.Identifier:
if (!ParseStatement())
continueParsingTecnhique = false;
break;
case TokenType.RightCurlyBrace:
isParseOk = true;
continueParsingTecnhique = false;
break;
// fxc doesn't support empty statements, so we don't support them.
//case TokenType.SemiColon:
// // Skip empty statements
// break;
default:
Logger.Error("Unexpected token [{0}]. Expecting tokens ['identifier','}}']", currentToken.Span, currentToken);
continueParsingTecnhique = false;
break;
}
} while (continueParsingTecnhique);
if (isParseOk)
currentTechnique.Passes.Add(pass);
}
private bool ParseStatement()
{
var expression = ParseExpression();
if (expression == null)
return false;
if (!ExpectNext(TokenType.SemiColon))
return false;
currentPass.Statements.Add(new Ast.ExpressionStatement(expression) {Span = expression.Span});
return true;
}
private Ast.Expression ParseExpression(bool allowIndirectIdentifier = false)
{
Ast.Expression expression = null;
var token = currentToken;
switch (token.Type)
{
case TokenType.Identifier:
if (token.Value == "true")
expression = new Ast.LiteralExpression(new Ast.Literal(true) {Span = token.Span}) {Span = token.Span};
else if (token.Value == "false")
expression = new Ast.LiteralExpression(new Ast.Literal(false) {Span = token.Span}) {Span = token.Span};
else if (string.Compare(token.Value, "null", StringComparison.OrdinalIgnoreCase) == 0)
expression = new Ast.LiteralExpression(new Ast.Literal(null) {Span = token.Span}) {Span = token.Span};
else if (token.Value == "compile")
{
expression = ParseCompileExpression();
}
else
{
var nextIdentifier = ParseIdentifier(token, true);
// check next token
BeginPreviewToken();
var nextToken = NextToken();
EndPreviewToken();
switch (nextToken.Type)
{
case TokenType.LeftParent:
var methodExpression = ParseMethodExpression();
methodExpression.Name = nextIdentifier;
expression = methodExpression;
break;
case TokenType.Equal:
var assignExpression = ParseAssignExpression();
assignExpression.Name = nextIdentifier;
expression = assignExpression;
break;
default:
expression = new Ast.IdentifierExpression(nextIdentifier) {Span = token.Span};
break;
}
}
break;
case TokenType.LeftParent:
expression = ParseArrayInitializerExpression(TokenType.RightParent);
//expression = ParseExpression();
//ExpectNext(TokenType.RightParent);
break;
case TokenType.String:
// TODO doesn't support escaped strings
var str = token.Value.Substring(1, token.Value.Length - 2);
// Temporary escape
str = str.Replace("\\r\\n", "\r\n");
str = str.Replace("\\n", "\n");
str = str.Replace("\\t", "\t");
expression = new Ast.LiteralExpression(new Ast.Literal(str) {Span = token.Span}) {Span = token.Span};
break;
case TokenType.Number:
var numberStr = token.Value.Replace(" ", "");
object numberValue;
if (numberStr.EndsWith("f", false, CultureInfo.InvariantCulture) || numberStr.Contains("e") || numberStr.Contains("E") || numberStr.Contains("."))
{
var floatStr = numberStr.TrimEnd('f');
numberValue = float.Parse(floatStr, NumberStyles.Float, CultureInfo.InvariantCulture);
}
else
{
numberValue = int.Parse(numberStr, NumberStyles.Integer, CultureInfo.InvariantCulture);
}
expression = new Ast.LiteralExpression(new Ast.Literal(numberValue) {Span = token.Span}) {Span = token.Span};
break;
case TokenType.Hexa:
var intValue = int.Parse(token.Value.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
expression = new Ast.LiteralExpression(new Ast.Literal(intValue) {Span = token.Span}) {Span = token.Span};
break;
case TokenType.LeftCurlyBrace:
expression = ParseArrayInitializerExpression(TokenType.RightCurlyBrace);
break;
default:
if (token.Type == TokenType.LessThan && allowIndirectIdentifier)
{
NextToken();
var identifierExpression = ParseExpression() as Ast.IdentifierExpression;
bool isClosedIndirect = ExpectNext(TokenType.GreaterThan);
if (identifierExpression == null)
{
Logger.Error("Unexpected expression inside indirect reference.", token.Span);
}
else
{
identifierExpression.Name.IsIndirect = isClosedIndirect;
expression = identifierExpression;
}
}
else
{
Logger.Error("Unexpected token [{0}]. Expecting tokens ['identifier', 'string', 'number', '{{']", currentToken.Span, currentToken);
}
break;
}
return expression;
}
private Ast.Identifier ParseIdentifier(Token token, bool allowIndexed = false)
{
var identifierName = new System.Text.StringBuilder(token.Value);
// ------------------------------------------------------------
// Parse complex identifier XXXX::AAAA::BBBBB
// ------------------------------------------------------------
BeginPreviewToken();
var nextToken = NextToken();
EndPreviewToken();
// Dot are not supported by compiler XXXX.AAAA.BBBB
// if (nextToken.Type == TokenType.DoubleColon || nextToken.Type == TokenType.Dot)
if (nextToken.Type == TokenType.DoubleColon)
{
var identifierSeparatorType = nextToken.Type;
var endChar = nextToken.Type == TokenType.DoubleColon ? "::" : ".";
nextToken = NextToken();
identifierName.Append(nextToken.Value);
bool continueParsing = true;
do
{
BeginPreviewToken();
nextToken = NextToken();
EndPreviewToken();
switch (nextToken.Type)
{
case TokenType.Identifier:
identifierName.Append(nextToken.Value);
break;
case TokenType.DoubleColon:
case TokenType.Dot:
if (identifierName[identifierName.Length - 1] == endChar[0])
{
Logger.Error("Unexpected token [{0}]. Expecting tokens [identifier]", nextToken.Span, endChar);
}
if (identifierSeparatorType != nextToken.Type)
{
Logger.Error("Unexpected token [{0}]. Expecting tokens [{1}]", nextToken.Span, nextToken.Value, endChar);
}
identifierName.Append(nextToken.Value);
break;
default:
continueParsing = false;
break;
}
// If can go to the next token
if (continueParsing)
{
nextToken = NextToken();
}
} while (continueParsing);
if (identifierName[identifierName.Length - 1] == endChar[0])
{
Logger.Error("Unexpected token [{0}]. Expecting tokens [identifier]", nextToken.Span, endChar);
}
}
// ------------------------------------------------------------
// Parse optional indexer a[xxx]
// ------------------------------------------------------------
if (allowIndexed)
{
BeginPreviewToken();
var arrayToken = NextToken();
EndPreviewToken();
if (arrayToken.Type == TokenType.LeftBracket)
{
// Skip left bracket [
NextToken();
// Get first token from inside bracket
NextToken();
// Parse value inside bracket
var expression = ParseExpression() as Ast.LiteralExpression;
if (expression == null || !(expression.Value.Value is int))
{
Logger.Error("Unsupported expression for indexed variable. Only support for integer Literal", currentToken.Span);
return null;
}
ExpectNext(TokenType.RightBracket);
return new Ast.IndexedIdentifier(identifierName.ToString(), (int)expression.Value.Value) { Span = token.Span };
}
}
return new Ast.Identifier(identifierName.ToString()) { Span = token.Span };
}
private Ast.Expression ParseCompileExpression()
{
var compileExp = new Ast.CompileExpression() {Span = currentToken.Span};
if (!ExpectNext(TokenType.Identifier))
return compileExp;
compileExp.Profile = ParseIdentifier(currentToken);
// Go to expression token
NextToken();
compileExp.Method = ParseExpression();
return compileExp;
}
private Ast.MethodExpression ParseMethodExpression()
{
if (!ExpectNext(TokenType.LeftParent))
return null;
var methodExp = new Ast.MethodExpression {Span = currentToken.Span};
int expectedArguments = 0;
bool continueParsing = true;
do
{
var token = NextToken();
switch (token.Type)
{
case TokenType.RightParent:
continueParsing = false;
break;
default:
var nextValue = ParseExpression();
if (nextValue == null)
{
continueParsing = false;
}
else
{
methodExp.Arguments.Add(nextValue);
NextToken();
if (currentToken.Type == TokenType.RightParent)
{
continueParsing = false;
}
else if (currentToken.Type == TokenType.Comma)
{
expectedArguments += (expectedArguments == 0) ? 2 : 1;
}
else
{
Logger.Error("Unexpected token [{0}]. Expecting tokens [',', ')']", currentToken.Span, currentToken);
continueParsing = false;
}
}
break;
}
} while (continueParsing);
int argCount = methodExp.Arguments.Count;
if (expectedArguments > 0 && expectedArguments != argCount)
Logger.Error("Unexpected number of commas.", currentToken.Span);
return methodExp;
}
private Ast.AssignExpression ParseAssignExpression()
{
var span = currentToken.Span;
if (!ExpectNext(TokenType.Equal))
return null;
NextToken();
var value = ParseExpression(true);
return new Ast.AssignExpression {Value = value, Span = span};
}
private Ast.ArrayInitializerExpression ParseArrayInitializerExpression(TokenType rightParent)
{
var expression = new Ast.ArrayInitializerExpression() {Span = currentToken.Span};
var values = expression.Values;
bool continueParsing = true;
do
{
var token = NextToken();
if (token.Type == rightParent)
break;
var nextValue = ParseExpression();
if (nextValue == null)
{
continueParsing = false;
}
else
{
values.Add(nextValue);
NextToken();
if (currentToken.Type == rightParent)
{
continueParsing = false;
}
else if (currentToken.Type != TokenType.Comma)
{
Logger.Error("Unexpected token [{0}]. Expecting tokens [',', '{1}']", currentToken.Span, currentToken.Value, rightParent);
continueParsing = false;
}
}
} while (continueParsing);
return expression;
}
private FileDependencyList CalculateDependencies(EffectParserResult parserResult)
{
var keys = new List<string>(parserResult.IncludeHandler.FileResolved.Keys);
keys.Sort(StringComparer.InvariantCultureIgnoreCase);
var dependency = new FileDependencyList();
dependency.AddDefaultDependencies();
foreach (var fileKey in keys)
{
var fileItem = parserResult.IncludeHandler.FileResolved[fileKey];
dependency.AddDependencyPath(fileItem.FilePath);
}
return dependency;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace ClosedXML.Excel
{
internal class XLCellsCollection
{
private readonly Dictionary<int, Dictionary<int, XLCell>> rowsCollection = new Dictionary<int, Dictionary<int, XLCell>>();
public readonly Dictionary<Int32, Int32> ColumnsUsed = new Dictionary<int, int>();
public readonly Dictionary<Int32, HashSet<Int32>> deleted = new Dictionary<int, HashSet<int>>();
internal Dictionary<int, Dictionary<int, XLCell>> RowsCollection
{
get { return rowsCollection; }
}
public Int32 MaxColumnUsed;
public Int32 MaxRowUsed;
public Dictionary<Int32, Int32> RowsUsed = new Dictionary<int, int>();
public XLCellsCollection()
{
Clear();
}
public Int32 Count { get; private set; }
public void Add(XLSheetPoint sheetPoint, XLCell cell)
{
Add(sheetPoint.Row, sheetPoint.Column, cell);
}
public void Add(Int32 row, Int32 column, XLCell cell)
{
Count++;
IncrementUsage(RowsUsed, row);
IncrementUsage(ColumnsUsed, column);
if (!rowsCollection.TryGetValue(row, out Dictionary<int, XLCell> columnsCollection))
{
columnsCollection = new Dictionary<int, XLCell>();
rowsCollection.Add(row, columnsCollection);
}
columnsCollection.Add(column, cell);
if (row > MaxRowUsed) MaxRowUsed = row;
if (column > MaxColumnUsed) MaxColumnUsed = column;
if (deleted.TryGetValue(row, out HashSet<int> delHash))
delHash.Remove(column);
}
private static void IncrementUsage(Dictionary<int, int> dictionary, Int32 key)
{
if (dictionary.ContainsKey(key))
dictionary[key]++;
else
dictionary.Add(key, 1);
}
private static void DecrementUsage(Dictionary<int, int> dictionary, Int32 key)
{
if (!dictionary.TryGetValue(key, out Int32 count)) return;
if (count > 0)
dictionary[key]--;
else
dictionary.Remove(key);
}
public void Clear()
{
Count = 0;
RowsUsed.Clear();
ColumnsUsed.Clear();
rowsCollection.Clear();
MaxRowUsed = 0;
MaxColumnUsed = 0;
}
public void Remove(XLSheetPoint sheetPoint)
{
Remove(sheetPoint.Row, sheetPoint.Column);
}
public void Remove(Int32 row, Int32 column)
{
Count--;
DecrementUsage(RowsUsed, row);
DecrementUsage(ColumnsUsed, row);
if (deleted.TryGetValue(row, out HashSet<Int32> delHash))
{
if (!delHash.Contains(column))
delHash.Add(column);
}
else
{
delHash = new HashSet<int>();
delHash.Add(column);
deleted.Add(row, delHash);
}
if (rowsCollection.TryGetValue(row, out Dictionary<Int32, XLCell> columnsCollection))
{
columnsCollection.Remove(column);
if (columnsCollection.Count == 0)
{
rowsCollection.Remove(row);
}
}
}
internal IEnumerable<XLCell> GetCells(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd,
Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<Int32, XLCell> columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.TryGetValue(co, out XLCell cell)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
internal IEnumerable<XLCell> GetCellsUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd,
Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<Int32, XLCell> columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.TryGetValue(co, out XLCell cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
public XLSheetPoint FirstPointUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
var firstRow = FirstRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstRow == 0) return new XLSheetPoint(0, 0);
var firstColumn = FirstColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstColumn == 0) return new XLSheetPoint(0, 0);
return new XLSheetPoint(firstRow, firstColumn);
}
public XLSheetPoint LastPointUsed(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd, Boolean includeFormats = false, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
var firstRow = LastRowUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstRow == 0) return new XLSheetPoint(0, 0);
var firstColumn = LastColumnUsed(rowStart, columnStart, finalRow, finalColumn, includeFormats, predicate);
if (firstColumn == 0) return new XLSheetPoint(0, 0);
return new XLSheetPoint(firstRow, firstColumn);
}
public int FirstRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats,
Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<Int32, XLCell> columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.TryGetValue(co, out XLCell cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return ro;
}
}
}
return 0;
}
public int FirstColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
int firstColumnUsed = finalColumn;
var found = false;
for (int ro = rowStart; ro <= finalRow; ro++)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<Int32, XLCell> columnsCollection))
{
for (int co = columnStart; co <= firstColumnUsed; co++)
{
if (columnsCollection.TryGetValue(co, out XLCell cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell))
&& co <= firstColumnUsed)
{
firstColumnUsed = co;
found = true;
break;
}
}
}
}
return found ? firstColumnUsed : 0;
}
public int LastRowUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = finalRow; ro >= rowStart; ro--)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<Int32, XLCell> columnsCollection))
{
for (int co = finalColumn; co >= columnStart; co--)
{
if (columnsCollection.TryGetValue(co, out XLCell cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
return ro;
}
}
}
return 0;
}
public int LastColumnUsed(int rowStart, int columnStart, int rowEnd, int columnEnd, Boolean includeFormats, Func<IXLCell, Boolean> predicate = null)
{
int maxCo = 0;
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = finalRow; ro >= rowStart; ro--)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<int, XLCell> columnsCollection))
{
for (int co = finalColumn; co >= columnStart && co > maxCo; co--)
{
if (columnsCollection.TryGetValue(co, out XLCell cell)
&& !cell.IsEmpty(includeFormats)
&& (predicate == null || predicate(cell)))
maxCo = co;
}
}
}
return maxCo;
}
public void RemoveAll(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<int, XLCell> columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.ContainsKey(co))
Remove(ro, co);
}
}
}
}
public IEnumerable<XLSheetPoint> GetSheetPoints(Int32 rowStart, Int32 columnStart,
Int32 rowEnd, Int32 columnEnd)
{
int finalRow = rowEnd > MaxRowUsed ? MaxRowUsed : rowEnd;
int finalColumn = columnEnd > MaxColumnUsed ? MaxColumnUsed : columnEnd;
for (int ro = rowStart; ro <= finalRow; ro++)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<Int32, XLCell> columnsCollection))
{
for (int co = columnStart; co <= finalColumn; co++)
{
if (columnsCollection.ContainsKey(co))
yield return new XLSheetPoint(ro, co);
}
}
}
}
public XLCell GetCell(Int32 row, Int32 column)
{
if (row > MaxRowUsed || column > MaxColumnUsed)
return null;
if (rowsCollection.TryGetValue(row, out Dictionary<Int32, XLCell> columnsCollection))
{
return columnsCollection.TryGetValue(column, out XLCell cell) ? cell : null;
}
return null;
}
public XLCell GetCell(XLSheetPoint sp)
{
return GetCell(sp.Row, sp.Column);
}
internal void SwapRanges(XLSheetRange sheetRange1, XLSheetRange sheetRange2, XLWorksheet worksheet)
{
Int32 rowCount = sheetRange1.LastPoint.Row - sheetRange1.FirstPoint.Row + 1;
Int32 columnCount = sheetRange1.LastPoint.Column - sheetRange1.FirstPoint.Column + 1;
for (int row = 0; row < rowCount; row++)
{
for (int column = 0; column < columnCount; column++)
{
var sp1 = new XLSheetPoint(sheetRange1.FirstPoint.Row + row, sheetRange1.FirstPoint.Column + column);
var sp2 = new XLSheetPoint(sheetRange2.FirstPoint.Row + row, sheetRange2.FirstPoint.Column + column);
var cell1 = GetCell(sp1);
var cell2 = GetCell(sp2);
if (cell1 == null) cell1 = worksheet.Cell(sp1.Row, sp1.Column);
if (cell2 == null) cell2 = worksheet.Cell(sp2.Row, sp2.Column);
//if (cell1 != null)
//{
cell1.Address = new XLAddress(cell1.Worksheet, sp2.Row, sp2.Column, false, false);
Remove(sp1);
//if (cell2 != null)
Add(sp1, cell2);
//}
//if (cell2 == null) continue;
cell2.Address = new XLAddress(cell2.Worksheet, sp1.Row, sp1.Column, false, false);
Remove(sp2);
//if (cell1 != null)
Add(sp2, cell1);
}
}
}
internal IEnumerable<XLCell> GetCells()
{
return GetCells(1, 1, MaxRowUsed, MaxColumnUsed);
}
internal IEnumerable<XLCell> GetCells(Func<IXLCell, Boolean> predicate)
{
for (int ro = 1; ro <= MaxRowUsed; ro++)
{
if (rowsCollection.TryGetValue(ro, out Dictionary<Int32, XLCell> columnsCollection))
{
for (int co = 1; co <= MaxColumnUsed; co++)
{
if (columnsCollection.TryGetValue(co, out XLCell cell)
&& (predicate == null || predicate(cell)))
yield return cell;
}
}
}
}
public Boolean Contains(Int32 row, Int32 column)
{
return rowsCollection.TryGetValue(row, out Dictionary<Int32, XLCell> columnsCollection)
&& columnsCollection.ContainsKey(column);
}
public Int32 MinRowInColumn(Int32 column)
{
for (int row = 1; row <= MaxRowUsed; row++)
{
if (rowsCollection.TryGetValue(row, out Dictionary<Int32, XLCell> columnsCollection)
&& columnsCollection.ContainsKey(column))
return row;
}
return 0;
}
public Int32 MaxRowInColumn(Int32 column)
{
for (int row = MaxRowUsed; row >= 1; row--)
{
if (rowsCollection.TryGetValue(row, out Dictionary<Int32, XLCell> columnsCollection)
&& columnsCollection.ContainsKey(column))
return row;
}
return 0;
}
public Int32 MinColumnInRow(Int32 row)
{
if (rowsCollection.TryGetValue(row, out Dictionary<Int32, XLCell> columnsCollection)
&& columnsCollection.Any())
return columnsCollection.Keys.Min();
return 0;
}
public Int32 MaxColumnInRow(Int32 row)
{
if (rowsCollection.TryGetValue(row, out Dictionary<Int32, XLCell> columnsCollection)
&& columnsCollection.Any())
return columnsCollection.Keys.Max();
return 0;
}
public IEnumerable<XLCell> GetCellsInColumn(Int32 column)
{
return GetCells(1, column, MaxRowUsed, column);
}
public IEnumerable<XLCell> GetCellsInRow(Int32 row)
{
return GetCells(row, 1, row, MaxColumnUsed);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Configuration;
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using ToolsetConfigurationSection = Microsoft.Build.Evaluation.ToolsetConfigurationSection;
using Xunit;
using System;
using System.Collections.Generic;
namespace Microsoft.Build.UnitTests.Definition
{
/// <summary>
/// Unit tests for ToolsetConfigurationReader class
/// </summary>
public class ToolsetConfigurationReaderTests : IDisposable
{
private static string s_msbuildToolsets = "msbuildToolsets";
public void Dispose()
{
ToolsetConfigurationReaderTestHelper.CleanUp();
}
#region "msbuildToolsets element tests"
/// <summary>
/// msbuildToolsets element is empty
/// </summary>
[Fact]
public void MSBuildToolsetsTest_EmptyElement()
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets />
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection;
Assert.Null(msbuildToolsetSection.MSBuildOverrideTasksPath);
Assert.NotNull(msbuildToolsetSection);
Assert.Null(msbuildToolsetSection.Default);
Assert.NotNull(msbuildToolsetSection.Toolsets);
Assert.Empty(msbuildToolsetSection.Toolsets);
}
/// <summary>
/// tests if ToolsetConfigurationReaderTests is successfully initialized from the config file
/// </summary>
[Fact]
public void MSBuildToolsetsTest_Basic()
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ConfigurationSection section = config.GetSection(s_msbuildToolsets);
ToolsetConfigurationSection msbuildToolsetSection = section as ToolsetConfigurationSection;
Assert.Null(msbuildToolsetSection.MSBuildOverrideTasksPath);
Assert.Equal("2.0", msbuildToolsetSection.Default);
Assert.Single(msbuildToolsetSection.Toolsets);
Assert.Equal("2.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion);
Assert.Single(msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements);
Assert.Equal(
@"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\",
msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value);
Assert.Empty(msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths);
}
/// <summary>
/// Tests if ToolsetConfigurationReaderTests is successfully initialized from the config file when msbuildOVerrideTasksPath is set.
/// Also verify the msbuildOverrideTasksPath is properly read in.
/// </summary>
[Fact]
public void MSBuildToolsetsTest_Basic2()
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"" msbuildOverrideTasksPath=""c:\foo"">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ConfigurationSection section = config.GetSection(s_msbuildToolsets);
ToolsetConfigurationSection msbuildToolsetSection = section as ToolsetConfigurationSection;
Assert.Equal("c:\\foo", msbuildToolsetSection.MSBuildOverrideTasksPath);
}
/// <summary>
/// Tests if ToolsetConfigurationReaderTests is successfully initialized from the config file and that msbuildOVerrideTasksPath
/// is correctly read in when the value is empty.
/// </summary>
[Fact]
public void MSBuildToolsetsTest_Basic3()
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"" msbuildOverrideTasksPath="""">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ConfigurationSection section = config.GetSection(s_msbuildToolsets);
ToolsetConfigurationSection msbuildToolsetSection = section as ToolsetConfigurationSection;
Assert.Null(msbuildToolsetSection.MSBuildOverrideTasksPath);
}
/// <summary>
/// tests if ToolsetConfigurationReaderTests is successfully initialized from the config file
/// </summary>
[Fact]
public void MSBuildToolsetsTest_BasicWithOtherConfigEntries()
{
// NOTE: for some reason, <configSections> MUST be the first element under <configuration>
// for the API to read it. The docs don't make this clear.
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<startup>
<supportedRuntime imageVersion=""v2.0.60510"" version=""v2.0.x86chk""/>
<requiredRuntime imageVersion=""v2.0.60510"" version=""v2.0.x86chk"" safemode=""true""/>
</startup>
<msbuildToolsets default=""2.0"">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
</toolset>
</msbuildToolsets>
<runtime>
<assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"">
<dependentAssembly>
<assemblyIdentity name=""Microsoft.Build.Framework"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral""/>
<bindingRedirect oldVersion=""0.0.0.0-99.9.9.9"" newVersion=""2.0.0.0""/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection;
Assert.Equal("2.0", msbuildToolsetSection.Default);
Assert.Single(msbuildToolsetSection.Toolsets);
Assert.Equal("2.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion);
Assert.Single(msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements);
Assert.Equal(
@"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\",
msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value);
Assert.Empty(msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths);
}
#endregion
#region "toolsVersion element tests"
#region "Invalid cases (exception is expected to be thrown)"
/// <summary>
/// name attribute is missing from toolset element
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ToolsVersionTest_NameNotSpecified()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"">
<toolset>
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
</toolset>
<toolset toolsVersion=""4.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
/// <summary>
/// More than 1 toolset element with the same name
/// </summary>
[Fact]
public void ToolsVersionTest_MultipleElementsWithSameName()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
</toolset>
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
/// <summary>
/// empty toolset element
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ToolsVersionTest_EmptyElement()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"">
<toolset />
<toolset toolsVersion=""4.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
#endregion
#region "Valid cases (No exception expected)"
/// <summary>
/// only 1 toolset is specified
/// </summary>
[Fact]
public void ToolsVersionTest_SingleElement()
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""4.0"">
<toolset toolsVersion=""4.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection;
Assert.Equal("4.0", msbuildToolsetSection.Default);
Assert.Single(msbuildToolsetSection.Toolsets);
Assert.Equal("4.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion);
Assert.Single(msbuildToolsetSection.Toolsets.GetElement("4.0").PropertyElements);
Assert.Equal(
@"D:\windows\Microsoft.NET\Framework\v3.5.x86ret\",
msbuildToolsetSection.Toolsets.GetElement("4.0").PropertyElements.GetElement("MSBuildBinPath").Value);
}
#endregion
#endregion
#region "Property"
#region "Invalid cases (exception is expected to be thrown)"
/// <summary>
/// name attribute is missing
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void PropertyTest_NameNotSpecified()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""4.0"">
<toolset toolsVersion=""4.0"">
<property value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
/// <summary>
/// value attribute is missing
/// </summary>
[Fact]
public void PropertyTest_ValueNotSpecified()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""4.0"">
<toolset name=""4.0"">
<property name=""MSBuildBinPath"" />
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
/// <summary>
/// more than 1 property element with the same name
/// </summary>
[Fact]
public void PropertyTest_MultipleElementsWithSameName()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""4.0"">
<toolset ToolsVersion=""msbuilddefaulttoolsversion"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
/// <summary>
/// property element is an empty element
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void PropertyTest_EmptyElement()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""4.0"">
<toolset toolsVersion=""4.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
<property />
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
#endregion
#region "Valid cases"
/// <summary>
/// more than 1 property element specified
/// </summary>
[Fact]
public void PropertyTest_MultipleElement()
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
<property name=""SomeOtherPropertyName"" value=""SomeOtherPropertyValue""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection;
Assert.Equal("2.0", msbuildToolsetSection.Default);
Assert.Single(msbuildToolsetSection.Toolsets);
Assert.Equal(2, msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.Count);
Assert.Equal(
@"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\",
msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value);
Assert.Equal(
@"SomeOtherPropertyValue",
msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("SomeOtherPropertyName").Value);
}
/// <summary>
/// tests GetElement(string name) function in propertycollection class
/// </summary>
[Fact]
public void PropertyTest_GetValueByName()
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
<property name=""SomeOtherPropertyName"" value=""SomeOtherPropertyValue""/>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection;
// Verifications
Assert.Equal("2.0", msbuildToolsetSection.Default);
Assert.Single(msbuildToolsetSection.Toolsets);
Assert.Equal(2, msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.Count);
Assert.Equal(@"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\",
msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value);
Assert.Equal(@"SomeOtherPropertyValue",
msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("SomeOtherPropertyName").Value);
}
#endregion
#endregion
#region Extensions Paths
/// <summary>
/// Tests multiple extensions paths from the config file, specified for multiple OSes
/// </summary>
[Fact]
public void ExtensionPathsTest_Basic1()
{
// NOTE: for some reason, <configSections> MUST be the first element under <configuration>
// for the API to read it. The docs don't make this clear.
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""2.0"">
<toolset toolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
<property name=""MSBuildToolsPath"" value=""D:\windows\Microsoft.NET\Framework\v2.0.x86ret\""/>
<projectImportSearchPaths>
<searchPaths os=""windows"">
<property name=""MSBuildExtensionsPath"" value=""c:\foo""/>
<property name=""MSBuildExtensionsPath64"" value=""c:\foo64;c:\bar64""/>
</searchPaths>
<searchPaths os=""osx"">
<property name=""MSBuildExtensionsPath"" value=""/tmp/foo""/>
<property name=""MSBuildExtensionsPath32"" value=""/tmp/foo32;/tmp/bar32""/>
</searchPaths>
<searchPaths os=""unix"">
<property name=""MSBuildExtensionsPath"" value=""/tmp/bar""/>
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
ToolsetConfigurationSection msbuildToolsetSection = config.GetSection(s_msbuildToolsets) as ToolsetConfigurationSection;
Assert.Equal("2.0", msbuildToolsetSection.Default);
Assert.Single(msbuildToolsetSection.Toolsets);
Assert.Equal("2.0", msbuildToolsetSection.Toolsets.GetElement(0).toolsVersion);
Assert.Equal(2, msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.Count);
Assert.Equal(
@"D:\windows\Microsoft.NET\Framework\v2.0.x86ret\",
msbuildToolsetSection.Toolsets.GetElement("2.0").PropertyElements.GetElement("MSBuildBinPath").Value);
Assert.Equal(3, msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths.Count);
var allPaths = msbuildToolsetSection.Toolsets.GetElement(0).AllProjectImportSearchPaths;
Assert.Equal("windows", allPaths.GetElement(0).OS);
Assert.Equal(2, allPaths.GetElement(0).PropertyElements.Count);
Assert.Equal(@"c:\foo", allPaths.GetElement(0).PropertyElements.GetElement("MSBuildExtensionsPath").Value);
Assert.Equal(@"c:\foo64;c:\bar64", allPaths.GetElement(0).PropertyElements.GetElement("MSBuildExtensionsPath64").Value);
Assert.Equal("osx", allPaths.GetElement(1).OS);
Assert.Equal(2, allPaths.GetElement(1).PropertyElements.Count);
Assert.Equal(@"/tmp/foo", allPaths.GetElement(1).PropertyElements.GetElement("MSBuildExtensionsPath").Value);
Assert.Equal(@"/tmp/foo32;/tmp/bar32", allPaths.GetElement(1).PropertyElements.GetElement("MSBuildExtensionsPath32").Value);
Assert.Equal("unix", allPaths.GetElement(2).OS);
Assert.Single(allPaths.GetElement(2).PropertyElements);
Assert.Equal( @"/tmp/bar", allPaths.GetElement(2).PropertyElements.GetElement("MSBuildExtensionsPath").Value);
var reader = GetStandardConfigurationReader();
Dictionary<string, Toolset> toolsets = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase);
reader.ReadToolsets(toolsets, new PropertyDictionary<ProjectPropertyInstance>(),
new PropertyDictionary<ProjectPropertyInstance>(), true,
out string msbuildOverrideTasksPath, out string defaultOverrideToolsVersion);
Dictionary<string, ProjectImportPathMatch> pathsTable = toolsets["2.0"].ImportPropertySearchPathsTable;
if (NativeMethodsShared.IsWindows)
{
CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"c:\\foo"});
CheckPathsTable(pathsTable, "MSBuildExtensionsPath64", new string[] {"c:\\foo64", "c:\\bar64"});
}
else if (NativeMethodsShared.IsOSX)
{
CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"/tmp/foo"});
CheckPathsTable(pathsTable, "MSBuildExtensionsPath32", new string[] {"/tmp/foo32", "/tmp/bar32"});
}
else
{
CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"/tmp/bar"});
}
}
private void CheckPathsTable(Dictionary<string, ProjectImportPathMatch> pathsTable, string kind, string[] expectedPaths)
{
Assert.True(pathsTable.ContainsKey(kind));
var paths = pathsTable[kind];
Assert.Equal(paths.SearchPaths.Count, expectedPaths.Length);
for (int i = 0; i < paths.SearchPaths.Count; i ++)
{
Assert.Equal(paths.SearchPaths[i], expectedPaths[i]);
}
}
/// <summary>
/// more than 1 searchPaths elements with the same OS
/// </summary>
[Fact]
public void ExtensionsPathsTest_MultipleElementsWithSameOS()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""4.0"">
<toolset ToolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
<projectImportSearchPaths>
<searchPaths os=""windows"">
<property name=""MSBuildExtensionsPath"" value=""c:\foo""/>
</searchPaths>
<searchPaths os=""windows"">
<property name=""MSBuildExtensionsPath"" value=""c:\bar""/>
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
/// <summary>
/// more than value is element found for a the same extensions path property name+os
/// </summary>
[Fact]
public void ExtensionsPathsTest_MultipleElementsWithSamePropertyNameForSameOS()
{
Assert.Throws<ConfigurationErrorsException>(() =>
{
ToolsetConfigurationReaderTestHelper.WriteConfigFile(ObjectModelHelpers.CleanupFileContents(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""4.0"">
<toolset ToolsVersion=""2.0"">
<property name=""MSBuildBinPath"" value=""D:\windows\Microsoft.NET\Framework\v3.5.x86ret\""/>
<projectImportSearchPaths>
<searchPaths os=""windows"">
<property name=""MSBuildExtensionsPath"" value=""c:\foo""/>
<property name=""MSBuildExtensionsPath"" value=""c:\bar""/>
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>"));
Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest();
config.GetSection(s_msbuildToolsets);
}
);
}
private ToolsetConfigurationReader GetStandardConfigurationReader()
{
return new ToolsetConfigurationReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>(), ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest);
}
#endregion
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Individual
///<para>SObject Name: Individual</para>
///<para>Custom Object: False</para>
///</summary>
public class SfIndividual : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "Individual"; }
}
///<summary>
/// Individual ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Owner ID
/// <para>Name: OwnerId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "ownerId")]
public string OwnerId { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: Owner</para>
///</summary>
[JsonProperty(PropertyName = "owner")]
[Updateable(false), Createable(false)]
public SfUser Owner { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Last Name
/// <para>Name: LastName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastName")]
public string LastName { get; set; }
///<summary>
/// First Name
/// <para>Name: FirstName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "firstName")]
public string FirstName { get; set; }
///<summary>
/// Salutation
/// <para>Name: Salutation</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "salutation")]
public string Salutation { get; set; }
///<summary>
/// Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
[Updateable(false), Createable(false)]
public string Name { get; set; }
///<summary>
/// Don't Track
/// <para>Name: HasOptedOutTracking</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "hasOptedOutTracking")]
public bool? HasOptedOutTracking { get; set; }
///<summary>
/// Don't Profile
/// <para>Name: HasOptedOutProfiling</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "hasOptedOutProfiling")]
public bool? HasOptedOutProfiling { get; set; }
///<summary>
/// Don't Process
/// <para>Name: HasOptedOutProcessing</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "hasOptedOutProcessing")]
public bool? HasOptedOutProcessing { get; set; }
///<summary>
/// Don't Market
/// <para>Name: HasOptedOutSolicit</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "hasOptedOutSolicit")]
public bool? HasOptedOutSolicit { get; set; }
///<summary>
/// Forget this Individual
/// <para>Name: ShouldForget</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "shouldForget")]
public bool? ShouldForget { get; set; }
///<summary>
/// Export Individual's Data
/// <para>Name: SendIndividualData</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "sendIndividualData")]
public bool? SendIndividualData { get; set; }
///<summary>
/// OK to Store PII Data Elsewhere
/// <para>Name: CanStorePiiElsewhere</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "canStorePiiElsewhere")]
public bool? CanStorePiiElsewhere { get; set; }
///<summary>
/// Block Geolocation Tracking
/// <para>Name: HasOptedOutGeoTracking</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "hasOptedOutGeoTracking")]
public bool? HasOptedOutGeoTracking { get; set; }
///<summary>
/// Birth Date
/// <para>Name: BirthDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "birthDate")]
public DateTime? BirthDate { get; set; }
///<summary>
/// Death Date
/// <para>Name: DeathDate</para>
/// <para>SF Type: date</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "deathDate")]
public DateTime? DeathDate { get; set; }
///<summary>
/// Conviction Count
/// <para>Name: ConvictionsCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "convictionsCount")]
public int? ConvictionsCount { get; set; }
///<summary>
/// Number of Children
/// <para>Name: ChildrenCount</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "childrenCount")]
public int? ChildrenCount { get; set; }
///<summary>
/// Military Service
/// <para>Name: MilitaryService</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "militaryService")]
public string MilitaryService { get; set; }
///<summary>
/// Is Homeowner
/// <para>Name: IsHomeOwner</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isHomeOwner")]
public bool? IsHomeOwner { get; set; }
///<summary>
/// Occupation
/// <para>Name: Occupation</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "occupation")]
public string Occupation { get; set; }
///<summary>
/// Website
/// <para>Name: Website</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "website")]
public string Website { get; set; }
///<summary>
/// Individual's Age
/// <para>Name: IndividualsAge</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "individualsAge")]
public string IndividualsAge { get; set; }
///<summary>
/// Last Viewed Date
/// <para>Name: LastViewedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastViewedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastViewedDate { get; set; }
///<summary>
/// Master Record ID
/// <para>Name: MasterRecordId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "masterRecordId")]
[Updateable(false), Createable(false)]
public string MasterRecordId { get; set; }
///<summary>
/// ReferenceTo: Individual
/// <para>RelationshipName: MasterRecord</para>
///</summary>
[JsonProperty(PropertyName = "masterRecord")]
[Updateable(false), Createable(false)]
public SfIndividual MasterRecord { get; set; }
///<summary>
/// Consumer Credit Score
/// <para>Name: ConsumerCreditScore</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "consumerCreditScore")]
public int? ConsumerCreditScore { get; set; }
///<summary>
/// Consumer Credit Score Provider Name
/// <para>Name: ConsumerCreditScoreProviderName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "consumerCreditScoreProviderName")]
public string ConsumerCreditScoreProviderName { get; set; }
///<summary>
/// Influencer Rating
/// <para>Name: InfluencerRating</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "influencerRating")]
public int? InfluencerRating { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
}
}
| |
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
{
public class SensorRepeat
{
public AsyncCommandManager m_CmdManager;
public SensorRepeat(AsyncCommandManager CmdManager)
{
m_CmdManager = CmdManager;
maximumRange = CmdManager.m_ScriptEngine.Config.GetDouble("SensorMaxRange", 96.0d);
maximumToReturn = CmdManager.m_ScriptEngine.Config.GetInt("SensorMaxResults", 16);
}
private Object SenseLock = new Object();
private const int AGENT = 1;
private const int ACTIVE = 2;
private const int PASSIVE = 4;
private const int SCRIPTED = 8;
private double maximumRange = 96.0;
private int maximumToReturn = 16;
//
// SenseRepeater and Sensors
//
private class SenseRepeatClass
{
public uint localID;
public UUID itemID;
public double interval;
public DateTime next;
public string name;
public UUID keyID;
public int type;
public double range;
public double arc;
public SceneObjectPart host;
}
//
// Sensed entity
//
private class SensedEntity : IComparable
{
public SensedEntity(double detectedDistance, UUID detectedID)
{
distance = detectedDistance;
itemID = detectedID;
}
public int CompareTo(object obj)
{
if (!(obj is SensedEntity)) throw new InvalidOperationException();
SensedEntity ent = (SensedEntity)obj;
if (ent == null || ent.distance < distance) return 1;
if (ent.distance > distance) return -1;
return 0;
}
public UUID itemID;
public double distance;
}
private List<SenseRepeatClass> SenseRepeaters = new List<SenseRepeatClass>();
private object SenseRepeatListLock = new object();
public void SetSenseRepeatEvent(uint m_localID, UUID m_itemID,
string name, UUID keyID, int type, double range,
double arc, double sec, SceneObjectPart host)
{
// Always remove first, in case this is a re-set
UnSetSenseRepeaterEvents(m_localID, m_itemID);
if (sec == 0) // Disabling timer
return;
// Add to timer
SenseRepeatClass ts = new SenseRepeatClass();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = sec;
ts.name = name;
ts.keyID = keyID;
ts.type = type;
if (range > maximumRange)
ts.range = maximumRange;
else
ts.range = range;
ts.arc = arc;
ts.host = host;
ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
lock (SenseRepeatListLock)
{
SenseRepeaters.Add(ts);
}
}
public void UnSetSenseRepeaterEvents(uint m_localID, UUID m_itemID)
{
// Remove from timer
lock (SenseRepeatListLock)
{
List<SenseRepeatClass> NewSensors = new List<SenseRepeatClass>();
foreach (SenseRepeatClass ts in SenseRepeaters)
{
if (ts.localID != m_localID && ts.itemID != m_itemID)
{
NewSensors.Add(ts);
}
}
SenseRepeaters.Clear();
SenseRepeaters = NewSensors;
}
}
public void CheckSenseRepeaterEvents()
{
// Nothing to do here?
if (SenseRepeaters.Count == 0)
return;
lock (SenseRepeatListLock)
{
// Go through all timers
foreach (SenseRepeatClass ts in SenseRepeaters)
{
// Time has passed?
if (ts.next.ToUniversalTime() < DateTime.Now.ToUniversalTime())
{
SensorSweep(ts);
// set next interval
ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
}
}
} // lock
}
public void SenseOnce(uint m_localID, UUID m_itemID,
string name, UUID keyID, int type,
double range, double arc, SceneObjectPart host)
{
// Add to timer
SenseRepeatClass ts = new SenseRepeatClass();
ts.localID = m_localID;
ts.itemID = m_itemID;
ts.interval = 0;
ts.name = name;
ts.keyID = keyID;
ts.type = type;
if (range > maximumRange)
ts.range = maximumRange;
else
ts.range = range;
ts.arc = arc;
ts.host = host;
SensorSweep(ts);
}
private void SensorSweep(SenseRepeatClass ts)
{
if (ts.host == null)
{
return;
}
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// Is the sensor type is AGENT and not SCRIPTED then include agents
if ((ts.type & AGENT) != 0 && (ts.type & SCRIPTED) == 0)
{
sensedEntities.AddRange(doAgentSensor(ts));
}
// If SCRIPTED or PASSIVE or ACTIVE check objects
if ((ts.type & SCRIPTED) != 0 || (ts.type & PASSIVE) != 0 || (ts.type & ACTIVE) != 0)
{
sensedEntities.AddRange(doObjectSensor(ts));
}
lock (SenseLock)
{
if (sensedEntities.Count == 0)
{
// send a "no_sensor"
// Add it to queue
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("no_sensor", new Object[0],
new DetectParams[0]));
}
else
{
// Sort the list to get everything ordered by distance
sensedEntities.Sort();
int count = sensedEntities.Count;
int idx;
List<DetectParams> detected = new List<DetectParams>();
for (idx = 0; idx < count; idx++)
{
try
{
DetectParams detect = new DetectParams();
detect.Key = sensedEntities[idx].itemID;
detect.Populate(m_CmdManager.m_ScriptEngine.World);
detected.Add(detect);
}
catch (Exception)
{
// Ignore errors, the object has been deleted or the avatar has gone and
// there was a problem in detect.Populate so nothing added to the list
}
if (detected.Count == maximumToReturn)
break;
}
if (detected.Count == 0)
{
// To get here with zero in the list there must have been some sort of problem
// like the object being deleted or the avatar leaving to have caused some
// difficulty during the Populate above so fire a no_sensor event
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("no_sensor", new Object[0],
new DetectParams[0]));
}
else
{
m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
new EventParams("sensor",
new Object[] {new LSL_Types.LSLInteger(detected.Count) },
detected.ToArray()));
}
}
}
}
private List<SensedEntity> doObjectSensor(SenseRepeatClass ts)
{
List<EntityBase> Entities;
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// If this is an object sense by key try to get it directly
// rather than getting a list to scan through
if (ts.keyID != UUID.Zero)
{
EntityBase e = null;
m_CmdManager.m_ScriptEngine.World.Entities.TryGetValue(ts.keyID, out e);
if (e == null)
return sensedEntities;
Entities = new List<EntityBase>();
Entities.Add(e);
}
else
{
Entities = m_CmdManager.m_ScriptEngine.World.GetEntities();
}
SceneObjectPart SensePoint = ts.host;
Vector3 fromRegionPos = SensePoint.AbsolutePosition;
// pre define some things to avoid repeated definitions in the loop body
Vector3 toRegionPos;
double dis;
int objtype;
SceneObjectPart part;
float dx;
float dy;
float dz;
Quaternion q = SensePoint.RotationOffset;
LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
Vector3 ZeroVector = new Vector3(0, 0, 0);
bool nameSearch = (ts.name != null && ts.name != "");
foreach (EntityBase ent in Entities)
{
bool keep = true;
if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search
continue;
if (ent.IsDeleted) // taken so long to do this it has gone from the scene
continue;
if (!(ent is SceneObjectGroup)) // dont bother if it is a pesky avatar
continue;
toRegionPos = ent.AbsolutePosition;
// Calculation is in line for speed
dx = toRegionPos.X - fromRegionPos.X;
dy = toRegionPos.Y - fromRegionPos.Y;
dz = toRegionPos.Z - fromRegionPos.Z;
// Weed out those that will not fit in a cube the size of the range
// no point calculating if they are within a sphere the size of the range
// if they arent even in the cube
if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range)
dis = ts.range + 1.0;
else
dis = Math.Sqrt(dx * dx + dy * dy + dz * dz);
if (keep && dis <= ts.range && ts.host.UUID != ent.UUID)
{
// In Range and not the object containing the script, is it the right Type ?
objtype = 0;
part = ((SceneObjectGroup)ent).RootPart;
if (part.AttachmentPoint != 0) // Attached so ignore
continue;
if (part.Inventory.ContainsScripts())
{
objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ...
}
else
{
if (ent.Velocity.Equals(ZeroVector))
{
objtype |= PASSIVE; // Passive non-moving
}
else
{
objtype |= ACTIVE; // moving so active
}
}
// If any of the objects attributes match any in the requested scan type
if (((ts.type & objtype) != 0))
{
// Right type too, what about the other params , key and name ?
if (ts.arc < Math.PI)
{
// not omni-directional. Can you see it ?
// vec forward_dir = llRot2Fwd(llGetRot())
// vec obj_dir = toRegionPos-fromRegionPos
// dot=dot(forward_dir,obj_dir)
// mag_fwd = mag(forward_dir)
// mag_obj = mag(obj_dir)
// ang = acos(dot /(mag_fwd*mag_obj))
double ang_obj = 0;
try
{
Vector3 diff = toRegionPos - fromRegionPos;
LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
}
catch
{
}
if (ang_obj > ts.arc) keep = false;
}
if (keep == true)
{
// add distance for sorting purposes later
sensedEntities.Add(new SensedEntity(dis, ent.UUID));
}
}
}
}
return sensedEntities;
}
private List<SensedEntity> doAgentSensor(SenseRepeatClass ts)
{
List<ScenePresence> presences;
List<SensedEntity> sensedEntities = new List<SensedEntity>();
// If this is an avatar sense by key try to get them directly
// rather than getting a list to scan through
if (ts.keyID != UUID.Zero)
{
ScenePresence p = m_CmdManager.m_ScriptEngine.World.GetScenePresence(ts.keyID);
if (p == null)
return sensedEntities;
presences = new List<ScenePresence>();
presences.Add(p);
}
else
{
presences = new List<ScenePresence>(m_CmdManager.m_ScriptEngine.World.GetScenePresences());
}
// If nobody about quit fast
if (presences.Count == 0)
return sensedEntities;
SceneObjectPart SensePoint = ts.host;
Vector3 fromRegionPos = SensePoint.AbsolutePosition;
Quaternion q = SensePoint.RotationOffset;
LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
bool attached = (SensePoint.AttachmentPoint != 0);
bool nameSearch = (ts.name != null && ts.name != "");
Vector3 toRegionPos;
double dis;
for (int i = 0; i < presences.Count; i++)
{
ScenePresence presence = presences[i];
bool keep = true;
if (presence.IsDeleted)
continue;
if (presence.IsChildAgent)
keep = false;
toRegionPos = presence.AbsolutePosition;
dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos));
// are they in range
if (keep && dis <= ts.range)
{
// if the object the script is in is attached and the avatar is the owner
// then this one is not wanted
if (attached && presence.UUID == SensePoint.OwnerID)
keep = false;
// check the name if needed
if (keep && nameSearch && ts.name != presence.Name)
keep = false;
// Are they in the required angle of view
if (keep && ts.arc < Math.PI)
{
// not omni-directional. Can you see it ?
// vec forward_dir = llRot2Fwd(llGetRot())
// vec obj_dir = toRegionPos-fromRegionPos
// dot=dot(forward_dir,obj_dir)
// mag_fwd = mag(forward_dir)
// mag_obj = mag(obj_dir)
// ang = acos(dot /(mag_fwd*mag_obj))
double ang_obj = 0;
try
{
Vector3 diff = toRegionPos - fromRegionPos;
LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
}
catch
{
}
if (ang_obj > ts.arc) keep = false;
}
}
else
{
keep = false;
}
// Do not report gods, not even minor ones
if (keep && presence.GodLevel > 0.0)
keep = false;
if (keep) // add to list with distance
{
sensedEntities.Add(new SensedEntity(dis, presence.UUID));
}
// If this is a search by name and we have just found it then no more to do
if (nameSearch && ts.name == presence.Name)
return sensedEntities;
}
return sensedEntities;
}
public Object[] GetSerializationData(UUID itemID)
{
List<Object> data = new List<Object>();
lock (SenseRepeatListLock)
{
foreach (SenseRepeatClass ts in SenseRepeaters)
{
if (ts.itemID == itemID)
{
data.Add(ts.interval);
data.Add(ts.name);
data.Add(ts.keyID);
data.Add(ts.type);
data.Add(ts.range);
data.Add(ts.arc);
}
}
}
return data.ToArray();
}
public void CreateFromData(uint localID, UUID itemID, UUID objectID,
Object[] data)
{
SceneObjectPart part =
m_CmdManager.m_ScriptEngine.World.GetSceneObjectPart(
objectID);
if (part == null)
return;
int idx = 0;
while (idx < data.Length)
{
SenseRepeatClass ts = new SenseRepeatClass();
ts.localID = localID;
ts.itemID = itemID;
ts.interval = (double)data[idx];
ts.name = (string)data[idx+1];
ts.keyID = (UUID)data[idx+2];
ts.type = (int)data[idx+3];
ts.range = (double)data[idx+4];
ts.arc = (double)data[idx+5];
ts.host = part;
ts.next =
DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
SenseRepeaters.Add(ts);
idx += 6;
}
}
}
}
| |
/*
* 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.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
namespace OpenSim
{
/// <summary>
/// Loads the Configuration files into nIni
/// </summary>
public class ConfigurationLoader
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Various Config settings the region needs to start
/// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor,
/// StorageDLL, Storage Connection String, Estate connection String, Client Stack
/// Standalone settings.
/// </summary>
protected ConfigSettings m_configSettings;
/// <summary>
/// A source of Configuration data
/// </summary>
protected OpenSimConfigSource m_config;
/// <summary>
/// Grid Service Information. This refers to classes and addresses of the grid service
/// </summary>
protected NetworkServersInfo m_networkServersInfo;
/// <summary>
/// Loads the region configuration
/// </summary>
/// <param name="argvSource">Parameters passed into the process when started</param>
/// <param name="configSettings"></param>
/// <param name="networkInfo"></param>
/// <returns>A configuration that gets passed to modules</returns>
public OpenSimConfigSource LoadConfigSettings(
IConfigSource argvSource, out ConfigSettings configSettings,
out NetworkServersInfo networkInfo)
{
m_configSettings = configSettings = new ConfigSettings();
m_networkServersInfo = networkInfo = new NetworkServersInfo();
bool iniFileExists = false;
IConfig startupConfig = argvSource.Configs["Startup"];
List<string> sources = new List<string>();
string masterFileName =
startupConfig.GetString("inimaster", String.Empty);
if (IsUri(masterFileName))
{
if (!sources.Contains(masterFileName))
sources.Add(masterFileName);
}
else
{
string masterFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), masterFileName));
if (masterFileName != String.Empty &&
File.Exists(masterFilePath) &&
(!sources.Contains(masterFilePath)))
sources.Add(masterFilePath);
}
string iniFileName =
startupConfig.GetString("inifile", "OpenSim.ini");
if (IsUri(iniFileName))
{
if (!sources.Contains(iniFileName))
sources.Add(iniFileName);
Application.iniFilePath = iniFileName;
}
else
{
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
if (!File.Exists(Application.iniFilePath))
{
iniFileName = "OpenSim.xml";
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
}
if (File.Exists(Application.iniFilePath))
{
if (!sources.Contains(Application.iniFilePath))
sources.Add(Application.iniFilePath);
}
}
string iniDirName =
startupConfig.GetString("inidirectory", "config");
string iniDirPath =
Path.Combine(Util.configDir(), iniDirName);
if (Directory.Exists(iniDirPath))
{
m_log.InfoFormat("Searching folder {0} for config ini files",
iniDirPath);
string[] fileEntries = Directory.GetFiles(iniDirName);
foreach (string filePath in fileEntries)
{
if (Path.GetExtension(filePath).ToLower() == ".ini")
{
if (!sources.Contains(Path.GetFullPath(filePath)))
sources.Add(Path.GetFullPath(filePath));
}
}
}
m_config = new OpenSimConfigSource();
m_config.Source = new IniConfigSource();
m_config.Source.Merge(DefaultConfig());
m_log.Info("[CONFIG]: Reading configuration settings");
if (sources.Count == 0)
{
m_log.FatalFormat("[CONFIG]: Could not load any configuration");
m_log.FatalFormat("[CONFIG]: Did you copy the OpenSim.ini.example file to OpenSim.ini?");
Environment.Exit(1);
}
for (int i = 0 ; i < sources.Count ; i++)
{
if (ReadConfig(sources[i]))
iniFileExists = true;
AddIncludes(sources);
}
if (!iniFileExists)
{
m_log.FatalFormat("[CONFIG]: Could not load any configuration");
m_log.FatalFormat("[CONFIG]: Configuration exists, but there was an error loading it!");
Environment.Exit(1);
}
// Make sure command line options take precedence
m_config.Source.Merge(argvSource);
ReadConfigSettings();
return m_config;
}
/// <summary>
/// Adds the included files as ini configuration files
/// </summary>
/// <param name="sources">List of URL strings or filename strings</param>
private void AddIncludes(List<string> sources)
{
//loop over config sources
foreach (IConfig config in m_config.Source.Configs)
{
// Look for Include-* in the key name
string[] keys = config.GetKeys();
foreach (string k in keys)
{
if (k.StartsWith("Include-"))
{
// read the config file to be included.
string file = config.GetString(k);
if (IsUri(file))
{
if (!sources.Contains(file))
sources.Add(file);
}
else
{
string basepath = Path.GetFullPath(Util.configDir());
// Resolve relative paths with wildcards
string chunkWithoutWildcards = file;
string chunkWithWildcards = string.Empty;
int wildcardIndex = file.IndexOfAny(new char[] { '*', '?' });
if (wildcardIndex != -1)
{
chunkWithoutWildcards = file.Substring(0, wildcardIndex);
chunkWithWildcards = file.Substring(wildcardIndex);
}
string path = Path.Combine(basepath, chunkWithoutWildcards);
path = Path.GetFullPath(path) + chunkWithWildcards;
string[] paths = Util.Glob(path);
foreach (string p in paths)
{
if (!sources.Contains(p))
sources.Add(p);
}
}
}
}
}
}
/// <summary>
/// Check if we can convert the string to a URI
/// </summary>
/// <param name="file">String uri to the remote resource</param>
/// <returns>true if we can convert the string to a Uri object</returns>
bool IsUri(string file)
{
Uri configUri;
return Uri.TryCreate(file, UriKind.Absolute,
out configUri) && configUri.Scheme == Uri.UriSchemeHttp;
}
/// <summary>
/// Provide same ini loader functionality for standard ini and master ini - file system or XML over http
/// </summary>
/// <param name="iniPath">Full path to the ini</param>
/// <returns></returns>
private bool ReadConfig(string iniPath)
{
bool success = false;
if (!IsUri(iniPath))
{
m_log.InfoFormat("[CONFIG]: Reading configuration file {0}", Path.GetFullPath(iniPath));
m_config.Source.Merge(new IniConfigSource(iniPath));
success = true;
}
else
{
m_log.InfoFormat("[CONFIG]: {0} is a http:// URI, fetching ...", iniPath);
// The ini file path is a http URI
// Try to read it
try
{
XmlReader r = XmlReader.Create(iniPath);
XmlConfigSource cs = new XmlConfigSource(r);
m_config.Source.Merge(cs);
success = true;
}
catch (Exception e)
{
m_log.FatalFormat("[CONFIG]: Exception reading config from URI {0}\n" + e.ToString(), iniPath);
Environment.Exit(1);
}
}
return success;
}
/// <summary>
/// Setup a default config values in case they aren't present in the ini file
/// </summary>
/// <returns>A Configuration source containing the default configuration</returns>
private static IConfigSource DefaultConfig()
{
IConfigSource defaultConfig = new IniConfigSource();
{
IConfig config = defaultConfig.Configs["Startup"];
if (null == config)
config = defaultConfig.AddConfig("Startup");
config.Set("region_info_source", "filesystem");
config.Set("physics", "OpenDynamicsEngine");
config.Set("meshing", "Meshmerizer");
config.Set("physical_prim", true);
config.Set("see_into_this_sim_from_neighbor", true);
config.Set("serverside_object_permissions", false);
config.Set("storage_plugin", "OpenSim.Data.SQLite.dll");
config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3");
config.Set("storage_prim_inventories", true);
config.Set("startup_console_commands_file", String.Empty);
config.Set("shutdown_console_commands_file", String.Empty);
config.Set("DefaultScriptEngine", "XEngine");
config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
// life doesn't really work without this
config.Set("EventQueue", true);
}
{
IConfig config = defaultConfig.Configs["Network"];
if (null == config)
config = defaultConfig.AddConfig("Network");
config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort);
}
return defaultConfig;
}
/// <summary>
/// Read initial region settings from the ConfigSource
/// </summary>
protected virtual void ReadConfigSettings()
{
IConfig startupConfig = m_config.Source.Configs["Startup"];
if (startupConfig != null)
{
m_configSettings.PhysicsEngine = startupConfig.GetString("physics");
m_configSettings.MeshEngineName = startupConfig.GetString("meshing");
m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true);
m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true);
m_configSettings.StorageDll = startupConfig.GetString("storage_plugin");
m_configSettings.StorageConnectionString
= startupConfig.GetString("storage_connection_string");
m_configSettings.EstateConnectionString
= startupConfig.GetString("estate_connection_string", m_configSettings.StorageConnectionString);
m_configSettings.ClientstackDll
= startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
}
IConfig standaloneConfig = m_config.Source.Configs["StandAlone"];
if (standaloneConfig != null)
{
m_configSettings.StandaloneAuthenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
m_configSettings.StandaloneWelcomeMessage = standaloneConfig.GetString("welcome_message");
m_configSettings.StandaloneInventoryPlugin = standaloneConfig.GetString("inventory_plugin");
m_configSettings.StandaloneInventorySource = standaloneConfig.GetString("inventory_source");
m_configSettings.StandaloneUserPlugin = standaloneConfig.GetString("userDatabase_plugin");
m_configSettings.StandaloneUserSource = standaloneConfig.GetString("user_source");
m_configSettings.LibrariesXMLFile = standaloneConfig.GetString("LibrariesXMLFile");
}
m_networkServersInfo.loadFromConfiguration(m_config.Source);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
/// <summary>
/// Represents a position within a <see cref="LargeArrayBuilder{T}"/>.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
internal struct CopyPosition
{
/// <summary>
/// Constructs a new <see cref="CopyPosition"/>.
/// </summary>
/// <param name="row">The index of the buffer to select.</param>
/// <param name="column">The index within the buffer to select.</param>
internal CopyPosition(int row, int column)
{
Debug.Assert(row >= 0);
Debug.Assert(column >= 0);
Row = row;
Column = column;
}
/// <summary>
/// Represents a position at the start of a <see cref="LargeArrayBuilder{T}"/>.
/// </summary>
public static CopyPosition Start => default(CopyPosition);
/// <summary>
/// The index of the buffer to select.
/// </summary>
internal int Row { get; }
/// <summary>
/// The index within the buffer to select.
/// </summary>
internal int Column { get; }
/// <summary>
/// If this position is at the end of the current buffer, returns the position
/// at the start of the next buffer. Otherwise, returns this position.
/// </summary>
/// <param name="endColumn">The length of the current buffer.</param>
public CopyPosition Normalize(int endColumn)
{
Debug.Assert(Column <= endColumn);
return Column == endColumn ?
new CopyPosition(Row + 1, 0) :
this;
}
/// <summary>
/// Gets a string suitable for display in the debugger.
/// </summary>
private string DebuggerDisplay => $"[{Row}, {Column}]";
}
/// <summary>
/// Helper type for building dynamically-sized arrays while minimizing allocations and copying.
/// </summary>
/// <typeparam name="T">The element type.</typeparam>
internal struct LargeArrayBuilder<T>
{
private const int StartingCapacity = 4;
private const int ResizeLimit = 8;
private readonly int _maxCapacity; // The maximum capacity this builder can have.
private T[] _first; // The first buffer we store items in. Resized until ResizeLimit.
private ArrayBuilder<T[]> _buffers; // After ResizeLimit * 2, we store previous buffers we've filled out here.
private T[] _current; // Current buffer we're reading into. If _count <= ResizeLimit, this is _first.
private int _index; // Index into the current buffer.
private int _count; // Count of all of the items in this builder.
/// <summary>
/// Constructs a new builder.
/// </summary>
/// <param name="initialize">Pass <c>true</c>.</param>
public LargeArrayBuilder(bool initialize)
: this(maxCapacity: int.MaxValue)
{
// This is a workaround for C# not having parameterless struct constructors yet.
// Once it gets them, replace this with a parameterless constructor.
Debug.Assert(initialize);
}
/// <summary>
/// Constructs a new builder with the specified maximum capacity.
/// </summary>
/// <param name="maxCapacity">The maximum capacity this builder can have.</param>
/// <remarks>
/// Do not add more than <paramref name="maxCapacity"/> items to this builder.
/// </remarks>
public LargeArrayBuilder(int maxCapacity)
: this()
{
Debug.Assert(maxCapacity >= 0);
_first = _current = Array.Empty<T>();
_maxCapacity = maxCapacity;
}
/// <summary>
/// Gets the number of items added to the builder.
/// </summary>
public int Count => _count;
/// <summary>
/// Adds an item to this builder.
/// </summary>
/// <param name="item">The item to add.</param>
/// <remarks>
/// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case.
/// Otherwise, use <see cref="SlowAdd"/>.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
Debug.Assert(_maxCapacity > _count);
if (_index == _current.Length)
{
AllocateBuffer();
}
_current[_index++] = item;
_count++;
}
/// <summary>
/// Adds a range of items to this builder.
/// </summary>
/// <param name="items">The sequence to add.</param>
/// <remarks>
/// It is the caller's responsibility to ensure that adding <paramref name="items"/>
/// does not cause the builder to exceed its maximum capacity.
/// </remarks>
public void AddRange(IEnumerable<T> items)
{
Debug.Assert(items != null);
using (IEnumerator<T> enumerator = items.GetEnumerator())
{
T[] destination = _current;
int index = _index;
// Continuously read in items from the enumerator, updating _count
// and _index when we run out of space.
while (enumerator.MoveNext())
{
if (index == destination.Length)
{
// No more space in this buffer. Resize.
_count += index - _index;
_index = index;
AllocateBuffer();
destination = _current;
index = _index; // May have been reset to 0
}
destination[index++] = enumerator.Current;
}
// Final update to _count and _index.
_count += index - _index;
_index = index;
}
}
/// <summary>
/// Copies the contents of this builder to the specified array.
/// </summary>
/// <param name="array">The destination array.</param>
/// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param>
/// <param name="count">The number of items to copy.</param>
public void CopyTo(T[] array, int arrayIndex, int count)
{
Debug.Assert(arrayIndex >= 0);
Debug.Assert(count >= 0 && count <= Count);
Debug.Assert(array?.Length - arrayIndex >= count);
for (int i = 0; count > 0; i++)
{
// Find the buffer we're copying from.
T[] buffer = GetBuffer(index: i);
// Copy until we satisfy count, or we reach the end of the buffer.
int toCopy = Math.Min(count, buffer.Length);
Array.Copy(buffer, 0, array, arrayIndex, toCopy);
// Increment variables to that position.
count -= toCopy;
arrayIndex += toCopy;
}
}
/// <summary>
/// Copies the contents of this builder to the specified array.
/// </summary>
/// <param name="position">The position in this builder to start copying from.</param>
/// <param name="array">The destination array.</param>
/// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param>
/// <param name="count">The number of items to copy.</param>
/// <returns>The position in this builder that was copied up to.</returns>
public CopyPosition CopyTo(CopyPosition position, T[] array, int arrayIndex, int count)
{
Debug.Assert(array != null);
Debug.Assert(arrayIndex >= 0);
Debug.Assert(count > 0 && count <= Count);
Debug.Assert(array.Length - arrayIndex >= count);
// Go through each buffer, which contains one 'row' of items.
// The index in each buffer is referred to as the 'column'.
/*
* Visual representation:
*
* C0 C1 C2 .. C31 .. C63
* R0: [0] [1] [2] .. [31]
* R1: [32] [33] [34] .. [63]
* R2: [64] [65] [66] .. [95] .. [127]
*/
int row = position.Row;
int column = position.Column;
T[] buffer = GetBuffer(row);
int copied = CopyToCore(buffer, column);
if (count == 0)
{
return new CopyPosition(row, column + copied).Normalize(buffer.Length);
}
do
{
buffer = GetBuffer(++row);
copied = CopyToCore(buffer, 0);
} while (count > 0);
return new CopyPosition(row, copied).Normalize(buffer.Length);
int CopyToCore(T[] sourceBuffer, int sourceIndex)
{
Debug.Assert(sourceBuffer.Length > sourceIndex);
// Copy until we satisfy `count` or reach the end of the current buffer.
int copyCount = Math.Min(sourceBuffer.Length - sourceIndex, count);
Array.Copy(sourceBuffer, sourceIndex, array, arrayIndex, copyCount);
arrayIndex += copyCount;
count -= copyCount;
return copyCount;
}
}
/// <summary>
/// Retrieves the buffer at the specified index.
/// </summary>
/// <param name="index">The index of the buffer.</param>
public T[] GetBuffer(int index)
{
Debug.Assert(index >= 0 && index < _buffers.Count + 2);
return index == 0 ? _first :
index <= _buffers.Count ? _buffers[index - 1] :
_current;
}
/// <summary>
/// Adds an item to this builder.
/// </summary>
/// <param name="item">The item to add.</param>
/// <remarks>
/// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case.
/// Otherwise, use <see cref="SlowAdd"/>.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public void SlowAdd(T item) => Add(item);
/// <summary>
/// Creates an array from the contents of this builder.
/// </summary>
public T[] ToArray()
{
if (TryMove(out T[] array))
{
// No resizing to do.
return array;
}
array = new T[_count];
CopyTo(array, 0, _count);
return array;
}
/// <summary>
/// Attempts to transfer this builder into an array without copying.
/// </summary>
/// <param name="array">The transferred array, if the operation succeeded.</param>
/// <returns><c>true</c> if the operation succeeded; otherwise, <c>false</c>.</returns>
public bool TryMove(out T[] array)
{
array = _first;
return _count == _first.Length;
}
private void AllocateBuffer()
{
// - On the first few adds, simply resize _first.
// - When we pass ResizeLimit, allocate ResizeLimit elements for _current
// and start reading into _current. Set _index to 0.
// - When _current runs out of space, add it to _buffers and repeat the
// above step, except with _current.Length * 2.
// - Make sure we never pass _maxCapacity in all of the above steps.
Debug.Assert((uint)_maxCapacity > (uint)_count);
Debug.Assert(_index == _current.Length, $"{nameof(AllocateBuffer)} was called, but there's more space.");
// If _count is int.MinValue, we want to go down the other path which will raise an exception.
if ((uint)_count < (uint)ResizeLimit)
{
// We haven't passed ResizeLimit. Resize _first, copying over the previous items.
Debug.Assert(_current == _first && _count == _first.Length);
int nextCapacity = Math.Min(_count == 0 ? StartingCapacity : _count * 2, _maxCapacity);
_current = new T[nextCapacity];
Array.Copy(_first, 0, _current, 0, _count);
_first = _current;
}
else
{
Debug.Assert(_maxCapacity > ResizeLimit);
Debug.Assert(_count == ResizeLimit ^ _current != _first);
int nextCapacity;
if (_count == ResizeLimit)
{
nextCapacity = ResizeLimit;
}
else
{
// Example scenario: Let's say _count == 64.
// Then our buffers look like this: | 8 | 8 | 16 | 32 |
// As you can see, our count will be just double the last buffer.
// Now, say _maxCapacity is 100. We will find the right amount to allocate by
// doing min(64, 100 - 64). The lhs represents double the last buffer,
// the rhs the limit minus the amount we've already allocated.
Debug.Assert(_count >= ResizeLimit * 2);
Debug.Assert(_count == _current.Length * 2);
_buffers.Add(_current);
nextCapacity = Math.Min(_count, _maxCapacity - _count);
}
_current = new T[nextCapacity];
_index = 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.
//testing float narrowing upon conv.r4 explicit cast
using System;
public struct VT
{
public float f1;
public float delta1;
public int a1;
public float b1;
public float temp;
}
public class CL
{
//used for add and sub
public float f1 = 1.0F;
public float delta1 = 1.0E-10F;
//used for mul and div
public int a1 = 3;
public float b1 = (1.0F / 3.0F);
//used as temp variable
public float temp;
}
public class ConvR4test
{
//static field of a1 class
private static float s_f1 = 1.0F;
private static float s_delta1 = 1.0E-10F;
private static int s_a1 = 3;
private static float s_b1 = (1.0F / 3.0F);
private static void disableInline(ref int x) { }
//f1 and delta1 are static filed of a1 class
private static float floatadd()
{
int i = 0;
disableInline(ref i);
return s_f1 + s_delta1;
}
private static float floatsub()
{
int i = 0;
disableInline(ref i);
return s_f1 - s_delta1;
}
private static float floatmul()
{
int i = 0;
disableInline(ref i);
return s_a1 * s_b1;
}
private static float floatdiv()
{
int i = 0;
disableInline(ref i);
return s_f1 / s_a1;
}
private static float floatadd_inline()
{
return s_f1 + s_delta1;
}
private static float floatsub_inline()
{
return s_f1 - s_delta1;
}
private static float floatmul_inline()
{
return s_a1 * s_b1;
}
private static float floatdiv_inline()
{
return s_f1 / s_a1;
}
public static int Main()
{
bool pass = true;
float temp;
float[] arr = new float[3];
VT vt1;
CL cl1 = new CL();
//*** add ***
Console.WriteLine();
Console.WriteLine("***add***");
//local, in-line
if (((float)(s_f1 + s_delta1)) != s_f1)
{
Console.WriteLine("((float)(f1+delta1))!=f1");
pass = false;
}
//local
temp = s_f1 + s_delta1;
if (((float)temp) != s_f1)
{
Console.WriteLine("((float)temp)!=f1, temp=f1+delta1");
pass = false;
}
//method call
if (((float)floatadd()) != s_f1)
{
Console.WriteLine("((float)floatadd())!=f1");
pass = false;
}
//inline method call
if (((float)floatadd_inline()) != s_f1)
{
Console.WriteLine("((float)floatadd_inline())!=f1");
pass = false;
}
//array element
arr[0] = s_f1;
arr[1] = s_delta1;
arr[2] = arr[0] + arr[1];
if (((float)arr[2]) != s_f1)
{
Console.WriteLine("((float)arr[2])!=f1");
pass = false;
}
//struct
vt1.f1 = 1.0F;
vt1.delta1 = 1.0E-10F;
vt1.temp = vt1.f1 + vt1.delta1;
if (((float)vt1.temp) != s_f1)
{
Console.WriteLine("((float)vt1.temp)!=f1");
pass = false;
}
//class
cl1.temp = cl1.f1 + cl1.delta1;
if (((float)cl1.temp) != s_f1)
{
Console.WriteLine("((float)cl1.temp)!=f1");
pass = false;
}
//*** minus ***
Console.WriteLine();
Console.WriteLine("***sub***");
//local, in-line
if (((float)(s_f1 - s_delta1)) != s_f1)
{
Console.WriteLine("((float)(f1-delta1))!=f1");
pass = false;
}
//local
temp = s_f1 - s_delta1;
if (((float)temp) != s_f1)
{
Console.WriteLine("((float)temp)!=f1, temp=f1-delta1");
pass = false;
}
//method call
if (((float)floatsub()) != s_f1)
{
Console.WriteLine("((float)floatsub())!=f1");
pass = false;
}
//inline method call
if (((float)floatsub_inline()) != s_f1)
{
Console.WriteLine("((float)floatsub_inline())!=f1");
pass = false;
}
//array element
arr[0] = s_f1;
arr[1] = s_delta1;
arr[2] = arr[0] - arr[1];
if (((float)arr[2]) != s_f1)
{
Console.WriteLine("((float)arr[2])!=f1");
pass = false;
}
//struct
vt1.f1 = 1.0F;
vt1.delta1 = 1.0E-10F;
vt1.temp = vt1.f1 - vt1.delta1;
if (((float)vt1.temp) != s_f1)
{
Console.WriteLine("((float)vt1.temp)!=f1");
pass = false;
}
//class
cl1.temp = cl1.f1 - cl1.delta1;
if (((float)cl1.temp) != s_f1)
{
Console.WriteLine("((float)cl1.temp)!=f1");
pass = false;
}
//*** multiply ***
Console.WriteLine();
Console.WriteLine("***mul***");
//local, in-line
if (((float)(s_a1 * s_b1)) != s_f1)
{
Console.WriteLine("((float)(a1*b1))!=f1");
pass = false;
}
//local
temp = s_a1 * s_b1;
if (((float)temp) != s_f1)
{
Console.WriteLine("((float)temp)!=f1, temp=a1*b1");
pass = false;
}
//method call
if (((float)floatmul()) != s_f1)
{
Console.WriteLine("((float)floatmul())!=f1");
pass = false;
}
//inline method call
if (((float)floatmul_inline()) != s_f1)
{
Console.WriteLine("((float)floatmul_inline())!=f1");
pass = false;
}
//array element
arr[0] = s_a1;
arr[1] = s_b1;
arr[2] = arr[0] * arr[1];
if (((float)arr[2]) != s_f1)
{
Console.WriteLine("((float)arr[2])!=f1");
pass = false;
}
//struct
vt1.a1 = 3;
vt1.b1 = 1.0F / 3.0F;
vt1.temp = vt1.a1 * vt1.b1;
if (((float)vt1.temp) != s_f1)
{
Console.WriteLine("((float)vt1.temp)!=f1");
pass = false;
}
//class
cl1.temp = cl1.a1 * cl1.b1;
if (((float)cl1.temp) != s_f1)
{
Console.WriteLine("((float)cl1.temp)!=f1");
pass = false;
}
//*** divide ***
Console.WriteLine();
Console.WriteLine("***div***");
//local, in-line
if (((float)(s_f1 / s_a1)) != s_b1)
{
Console.WriteLine("((float)(f1/a1))!=b1");
pass = false;
}
//local
temp = s_f1 / s_a1;
if (((float)temp) != s_b1)
{
Console.WriteLine("((float)temp)!=f1, temp=f1/a1");
pass = false;
}
//method call
if (((float)floatdiv()) != s_b1)
{
Console.WriteLine("((float)floatdivl())!=b1");
pass = false;
}
//method call
if (((float)floatdiv_inline()) != s_b1)
{
Console.WriteLine("((float)floatdiv_inline())!=b1");
pass = false;
}
//array element
arr[0] = s_f1;
arr[1] = s_a1;
arr[2] = arr[0] / arr[1];
if (((float)arr[2]) != s_b1)
{
Console.WriteLine("((float)arr[2])!=b1");
pass = false;
}
//struct
vt1.f1 = 1.0F;
vt1.a1 = 3;
vt1.temp = vt1.f1 / vt1.a1;
if (((float)vt1.temp) != s_b1)
{
Console.WriteLine("((float)vt1.temp)!=b1");
pass = false;
}
//class
cl1.temp = cl1.f1 / cl1.a1;
if (((float)cl1.temp) != s_b1)
{
Console.WriteLine("((float)cl1.temp)!=b1");
pass = false;
}
Console.WriteLine();
if (pass)
{
Console.WriteLine("SUCCESS");
return 100;
}
else
{
Console.WriteLine("FAILURE: float not truncated properly");
return 1;
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
namespace IcedFuzzer.Core {
enum FuzzerOperandKind {
None,
Immediate,
MemOffs,
ImpliedMem,
Mem,
Register,
}
class FuzzerOperand {
public readonly FuzzerOperandKind Kind;
public FuzzerOperand(FuzzerOperandKind kind) => Kind = kind;
}
enum FuzzerImmediateKind {
Imm1,
Imm2,
Imm4,
Imm8,
Imm2_2,
Imm4_2,
}
sealed class ImmediateFuzzerOperand : FuzzerOperand {
public readonly FuzzerImmediateKind ImmKind;
public ImmediateFuzzerOperand(FuzzerImmediateKind kind)
: base(FuzzerOperandKind.Immediate) => ImmKind = kind;
}
[Flags]
enum ModrmMemoryFuzzerOperandFlags : uint {
None = 0,
// 16/32-bit mode: must be 32-bit addressing, else #UD. 64-bit mode: 64-bit addressing is forced (67h has no effect)
MPX = 0x00000001,
// RIP-rel operands #UD
NoRipRel = 0x00000002,
// VSIB operand
Vsib = 0x00000004,
// SIB required
Sib = 0x00000008,
}
sealed class ModrmMemoryFuzzerOperand : FuzzerOperand {
readonly ModrmMemoryFuzzerOperandFlags flags;
public bool IsVSIB => (flags & ModrmMemoryFuzzerOperandFlags.Vsib) != 0;
public bool MustNotUseAddrSize16 => (flags & (ModrmMemoryFuzzerOperandFlags.MPX | ModrmMemoryFuzzerOperandFlags.Vsib | ModrmMemoryFuzzerOperandFlags.Sib)) != 0;
public bool NoRipRel => (flags & ModrmMemoryFuzzerOperandFlags.NoRipRel) != 0;
public bool MustUseSib => (flags & (ModrmMemoryFuzzerOperandFlags.Sib | ModrmMemoryFuzzerOperandFlags.Vsib)) != 0;
public ModrmMemoryFuzzerOperand(ModrmMemoryFuzzerOperandFlags flags)
: base(FuzzerOperandKind.Mem) => this.flags = flags;
}
enum FuzzerRegisterKind {
GPR8,
GPR16,
GPR32,
GPR64,
Segment,
ST,
CR,
DR,
TR,
BND,
K,
MM,
XMM,
YMM,
ZMM,
TMM,
}
enum FuzzerRegisterClass {
GPR,
Segment,
ST,
CR,
DR,
TR,
BND,
K,
MM,
Vector,
TMM,
}
enum FuzzerOperandRegLocation {
// [4] = EVEX.R'
// [3] = REX/VEX/EVEX/XOP.R
// [2:0] = modrm.reg
ModrmRegBits,
// [4] = EVEX.X
// [3] = REX/VEX/EVEX/XOP.B
// [2:0] = modrm.rm
ModrmRmBits,
// [4] = EVEX.V'
// [3:0] = VEX/EVEX/XOP.vvvv
VvvvBits,
// [3] = REX.B
// [2:0] = opcode[2:0]
OpCodeBits,
// [3:0] = imm8[7:4]
Is4Bits,
// [3:0] = imm8[7:4]
Is5Bits,
// [2:0] = aaa
AaaBits,
}
sealed partial class RegisterFuzzerOperand : FuzzerOperand {
public readonly FuzzerRegisterClass RegisterClass;
public readonly FuzzerRegisterKind Register;
public readonly FuzzerOperandRegLocation RegLocation;
public RegisterFuzzerOperand(FuzzerRegisterClass registerClass, FuzzerRegisterKind register, FuzzerOperandRegLocation regLocation)
: base(FuzzerOperandKind.Register) {
RegisterClass = registerClass;
Register = register;
RegLocation = regLocation;
}
public RegisterInfo GetRegisterInfo(int bitness, FuzzerEncodingKind encoding) {
switch (encoding) {
case FuzzerEncodingKind.Legacy:
case FuzzerEncodingKind.D3NOW:
switch (RegLocation) {
case FuzzerOperandRegLocation.ModrmRegBits:
case FuzzerOperandRegLocation.ModrmRmBits:
case FuzzerOperandRegLocation.OpCodeBits:
if (bitness < 64)
return new RegisterInfo(bitness, RegLocation, 8);
else
return new RegisterInfo(bitness, RegLocation, 16);
case FuzzerOperandRegLocation.VvvvBits:
case FuzzerOperandRegLocation.Is4Bits:
case FuzzerOperandRegLocation.Is5Bits:
case FuzzerOperandRegLocation.AaaBits:
throw ThrowHelpers.Unreachable;
default:
throw ThrowHelpers.Unreachable;
}
case FuzzerEncodingKind.VEX2:
switch (RegLocation) {
case FuzzerOperandRegLocation.ModrmRmBits:
return new RegisterInfo(bitness, RegLocation, 8);
case FuzzerOperandRegLocation.VvvvBits:
case FuzzerOperandRegLocation.ModrmRegBits:
if (bitness < 64)
return new RegisterInfo(bitness, RegLocation, 8);
else
return new RegisterInfo(bitness, RegLocation, 16);
case FuzzerOperandRegLocation.Is4Bits:
case FuzzerOperandRegLocation.Is5Bits:
return new RegisterInfo(bitness, RegLocation, 256);
case FuzzerOperandRegLocation.OpCodeBits:
case FuzzerOperandRegLocation.AaaBits:
throw ThrowHelpers.Unreachable;
default:
throw ThrowHelpers.Unreachable;
}
case FuzzerEncodingKind.VEX3:
case FuzzerEncodingKind.XOP:
switch (RegLocation) {
case FuzzerOperandRegLocation.ModrmRegBits:
if (bitness < 64 && encoding != FuzzerEncodingKind.XOP)
return new RegisterInfo(bitness, RegLocation, 8);
else
return new RegisterInfo(bitness, RegLocation, 16);
case FuzzerOperandRegLocation.ModrmRmBits:
case FuzzerOperandRegLocation.VvvvBits:
return new RegisterInfo(bitness, RegLocation, 16);
case FuzzerOperandRegLocation.Is4Bits:
case FuzzerOperandRegLocation.Is5Bits:
return new RegisterInfo(bitness, RegLocation, 256);
case FuzzerOperandRegLocation.OpCodeBits:
case FuzzerOperandRegLocation.AaaBits:
throw ThrowHelpers.Unreachable;
default:
throw ThrowHelpers.Unreachable;
}
case FuzzerEncodingKind.EVEX:
switch (RegLocation) {
case FuzzerOperandRegLocation.ModrmRegBits:
// 16/32-bit: it's R'Rrrr but R must be 0 (or it's BOUND). We return 8, and ignored-bits test will test R'
if (bitness < 64)
return new RegisterInfo(bitness, RegLocation, 8);
else
return new RegisterInfo(bitness, RegLocation, 32);
case FuzzerOperandRegLocation.ModrmRmBits:
// 16/32-bit: it's XBbbb but X must be 0 (inverted: 1) or it's BOUND
if (bitness < 64)
return new RegisterInfo(bitness, RegLocation, 16);
else
return new RegisterInfo(bitness, RegLocation, 32);
case FuzzerOperandRegLocation.VvvvBits:
return new RegisterInfo(bitness, RegLocation, 32);
case FuzzerOperandRegLocation.AaaBits:
return new RegisterInfo(bitness, RegLocation, 8);
case FuzzerOperandRegLocation.OpCodeBits:
case FuzzerOperandRegLocation.Is4Bits:
case FuzzerOperandRegLocation.Is5Bits:
throw ThrowHelpers.Unreachable;
default:
throw ThrowHelpers.Unreachable;
}
default:
throw ThrowHelpers.Unreachable;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using WinForms = System.Windows.Forms;
using IO = System.IO;
// 28/6/03
namespace NBM.Diagnostics
{
/// <summary>
/// Debug information window
/// Accessible through the protocol menu -> Debug Report
/// </summary>
public class Debug : System.Windows.Forms.Form
{
private System.Windows.Forms.Button closeButton;
private System.Windows.Forms.Button copyToClipboardButton;
private System.Windows.Forms.TextBox outputTextBox;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
///
/// </summary>
/// <param name="postfix">String to append to the end of the window text</param>
public Debug(string postfix)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.Text += " : " + postfix;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Overrided WndProc so the window is hidden when the X button is clicked
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref WinForms.Message m)
{
switch (m.Msg)
{
case 0x0010: // WM_CLOSE
this.Hide();
return;
}
base.WndProc(ref m);
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnActivated(EventArgs e)
{
NativeMethods.VerticalScrollToBottom(this.outputTextBox);
base.OnActivated(e);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.outputTextBox = new System.Windows.Forms.TextBox();
this.closeButton = new System.Windows.Forms.Button();
this.copyToClipboardButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// outputTextBox
//
this.outputTextBox.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.outputTextBox.Location = new System.Drawing.Point(8, 8);
this.outputTextBox.Multiline = true;
this.outputTextBox.Name = "outputTextBox";
this.outputTextBox.ReadOnly = true;
this.outputTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.outputTextBox.Size = new System.Drawing.Size(520, 272);
this.outputTextBox.TabIndex = 0;
this.outputTextBox.Text = "";
//
// closeButton
//
this.closeButton.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.closeButton.Location = new System.Drawing.Point(456, 296);
this.closeButton.Name = "closeButton";
this.closeButton.Size = new System.Drawing.Size(72, 32);
this.closeButton.TabIndex = 1;
this.closeButton.Text = "Hide";
this.closeButton.Click += new System.EventHandler(this.closeButton_Click);
//
// copyToClipboardButton
//
this.copyToClipboardButton.Anchor = (System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right);
this.copyToClipboardButton.Location = new System.Drawing.Point(312, 296);
this.copyToClipboardButton.Name = "copyToClipboardButton";
this.copyToClipboardButton.Size = new System.Drawing.Size(120, 32);
this.copyToClipboardButton.TabIndex = 2;
this.copyToClipboardButton.Text = "Copy To Clipboard";
this.copyToClipboardButton.Click += new System.EventHandler(this.copyToClipboardButton_Click);
//
// Debug
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(536, 334);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.copyToClipboardButton,
this.closeButton,
this.outputTextBox});
this.Name = "Debug";
this.Text = "Debug Output";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Copies the debug information to the clipboard.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void copyToClipboardButton_Click(object sender, System.EventArgs e)
{
WinForms.Clipboard.SetDataObject(this.outputTextBox.Text, true);
}
/// <summary>
/// Hides the window.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void closeButton_Click(object sender, System.EventArgs e)
{
this.Hide();
}
#region Write methods
/// <summary>
/// Writes a line to the debug window.
/// </summary>
/// <param name="text"></param>
public void WriteLine(string text)
{
this.outputTextBox.Text += text + "\r\n";
NativeMethods.VerticalScrollToBottom(this.outputTextBox);
}
/// <summary>
/// Writes a line to the debug window.
/// </summary>
/// <param name="format"></param>
/// <param name="args"></param>
public void WriteLine(string format, params object[] args)
{
WriteLine(string.Format(format, args));
}
#endregion
}
}
| |
//
// EditTagIconDialog.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (C) 2009-2010 Novell, Inc.
// Copyright (C) 2009 Stephane Delcroix
// Copyright (C) 2009-2010 Ruben Vermeersch
//
// 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 Mono.Unix;
using Gtk;
using FSpot.Core;
using FSpot.Database;
using FSpot.Imaging;
using FSpot.Query;
using FSpot.Settings;
using FSpot.Utils;
using FSpot.Widgets;
using Hyena;
using Hyena.Widgets;
namespace FSpot.UI.Dialog
{
public class EditTagIconDialog : BuilderDialog
{
PhotoQuery query;
PhotoImageView image_view;
Gtk.IconView icon_view;
ListStore icon_store;
string icon_name = string.Empty;
Gtk.FileChooserButton external_photo_chooser;
#pragma warning disable 649
[GtkBeans.Builder.Object] Gtk.Image preview_image;
[GtkBeans.Builder.Object] Gtk.ScrolledWindow photo_scrolled_window;
[GtkBeans.Builder.Object] Gtk.ScrolledWindow icon_scrolled_window;
[GtkBeans.Builder.Object] Label photo_label;
[GtkBeans.Builder.Object] Label from_photo_label;
[GtkBeans.Builder.Object] SpinButton photo_spin_button;
[GtkBeans.Builder.Object] HBox external_photo_chooser_hbox;
#pragma warning restore 649
public EditTagIconDialog (Db db, Tag t, Gtk.Window parent_window) : base ("EditTagIconDialog.ui", "edit_tag_icon_dialog")
{
TransientFor = parent_window;
Title = string.Format (Catalog.GetString ("Edit Icon for Tag {0}"), t.Name);
preview_pixbuf = t.Icon;
Cms.Profile screen_profile;
if (preview_pixbuf != null && ColorManagement.Profiles.TryGetValue (Preferences.Get<string> (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE), out screen_profile)) {
preview_image.Pixbuf = preview_pixbuf.Copy ();
ColorManagement.ApplyProfile (preview_image.Pixbuf, screen_profile);
} else
preview_image.Pixbuf = preview_pixbuf;
query = new PhotoQuery (db.Photos);
if (db.Tags.Hidden != null)
query.Terms = OrTerm.FromTags (new [] {t});
else
query.Terms = new Literal (t);
image_view = new PhotoImageView (query) {CropHelpers = false};
image_view.SelectionXyRatio = 1.0;
image_view.SelectionChanged += HandleSelectionChanged;
image_view.PhotoChanged += HandlePhotoChanged;
external_photo_chooser = new Gtk.FileChooserButton (Catalog.GetString ("Select Photo from file"),
Gtk.FileChooserAction.Open);
external_photo_chooser.Filter = new FileFilter();
external_photo_chooser.Filter.AddPixbufFormats();
external_photo_chooser.LocalOnly = false;
external_photo_chooser_hbox.PackStart (external_photo_chooser);
external_photo_chooser.Show ();
external_photo_chooser.SelectionChanged += HandleExternalFileSelectionChanged;
photo_scrolled_window.Add (image_view);
if (query.Count > 0) {
photo_spin_button.Wrap = true;
photo_spin_button.Adjustment.Lower = 1.0;
photo_spin_button.Adjustment.Upper = (double) query.Count;
photo_spin_button.Adjustment.StepIncrement = 1.0;
photo_spin_button.ValueChanged += HandleSpinButtonChanged;
image_view.Item.Index = 0;
} else {
from_photo_label.Markup = string.Format (Catalog.GetString (
"\n<b>From Photo</b>\n" +
" You can use one of your library photos as an icon for this tag.\n" +
" However, first you must have at least one photo associated\n" +
" with this tag. Please tag a photo as '{0}' and return here\n" +
" to use it as an icon."), t.Name);
photo_scrolled_window.Visible = false;
photo_label.Visible = false;
photo_spin_button.Visible = false;
}
icon_store = new ListStore (typeof (string), typeof (Gdk.Pixbuf));
icon_view = new Gtk.IconView (icon_store);
icon_view.PixbufColumn = 1;
icon_view.SelectionMode = SelectionMode.Single;
icon_view.SelectionChanged += HandleIconSelectionChanged;
icon_scrolled_window.Add (icon_view);
icon_view.Show();
image_view.Show ();
DelayedOperation fill_delay = new DelayedOperation (FillIconView);
fill_delay.Start ();
}
public BrowsablePointer Item {
get { return image_view.Item; }
}
Gdk.Pixbuf preview_pixbuf;
public Gdk.Pixbuf PreviewPixbuf {
get { return preview_pixbuf; }
set {
icon_name = null;
preview_pixbuf = value;
Cms.Profile screen_profile;
if (value!= null && ColorManagement.Profiles.TryGetValue (Preferences.Get<string> (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE), out screen_profile)) {
preview_image.Pixbuf = value.Copy ();
ColorManagement.ApplyProfile (preview_image.Pixbuf, screen_profile);
} else
preview_image.Pixbuf = value;
}
}
public string ThemeIconName {
get { return icon_name; }
set {
icon_name = value;
PreviewPixbuf = GtkUtil.TryLoadIcon (FSpot.Settings.Global.IconTheme, value, 48, (IconLookupFlags) 0);
}
}
void HandleSpinButtonChanged (object sender, EventArgs args)
{
int value = photo_spin_button.ValueAsInt - 1;
image_view.Item.Index = value;
}
void HandleExternalFileSelectionChanged (object sender, EventArgs args)
{ //Note: The filter on the FileChooserButton's dialog means that we will have a Pixbuf compatible uri here
CreateTagIconFromExternalPhoto ();
}
void CreateTagIconFromExternalPhoto ()
{
try {
using (var img = App.Instance.Container.Resolve<IImageFileFactory> ().Create (new SafeUri(external_photo_chooser.Uri, true))) {
using (Gdk.Pixbuf external_image = img.Load ()) {
PreviewPixbuf = PixbufUtils.TagIconFromPixbuf (external_image);
}
}
} catch (Exception) {
string caption = Catalog.GetString ("Unable to load image");
string message = string.Format (Catalog.GetString ("Unable to load \"{0}\" as icon for the tag"),
external_photo_chooser.Uri);
HigMessageDialog md = new HigMessageDialog (this,
DialogFlags.DestroyWithParent,
MessageType.Error,
ButtonsType.Close,
caption,
message);
md.Run();
md.Destroy();
}
}
void HandleSelectionChanged (object sender, EventArgs e)
{
int x = image_view.Selection.X;
int y = image_view.Selection.Y;
int width = image_view.Selection.Width;
int height = image_view.Selection.Height;
if (image_view.Pixbuf != null) {
if (image_view.Selection != Gdk.Rectangle.Zero) {
using (var tmp = new Gdk.Pixbuf (image_view.Pixbuf, x, y, width, height)) {
Gdk.Pixbuf transformed = FSpot.Utils.PixbufUtils.TransformOrientation (tmp, image_view.PixbufOrientation);
PreviewPixbuf = PixbufUtils.TagIconFromPixbuf (transformed);
transformed.Dispose ();
}
} else {
Gdk.Pixbuf transformed = FSpot.Utils.PixbufUtils.TransformOrientation (image_view.Pixbuf, image_view.PixbufOrientation);
PreviewPixbuf = PixbufUtils.TagIconFromPixbuf (transformed);
transformed.Dispose ();
}
}
}
public void HandlePhotoChanged (object sender, EventArgs e)
{
int item = image_view.Item.Index;
photo_label.Text = string.Format (Catalog.GetString ("Photo {0} of {1}"),
item + 1, query.Count);
photo_spin_button.Value = item + 1;
HandleSelectionChanged (null, null);
}
public void HandleIconSelectionChanged (object o, EventArgs args)
{
if (icon_view.SelectedItems.Length == 0)
return;
TreeIter iter;
icon_store.GetIter (out iter, icon_view.SelectedItems [0]);
ThemeIconName = (string) icon_store.GetValue (iter, 0);
}
public bool FillIconView ()
{
icon_store.Clear ();
string [] icon_list = FSpot.Settings.Global.IconTheme.ListIcons ("Emblems");
foreach (string item_name in icon_list)
icon_store.AppendValues (item_name, GtkUtil.TryLoadIcon (FSpot.Settings.Global.IconTheme, item_name, 32, (IconLookupFlags) 0));
return false;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Cinemachine.Utility;
using UnityEngine.Serialization;
using System;
namespace Cinemachine
{
/// <summary>
/// An add-on module for Cinemachine Virtual Camera that post-processes
/// the final position of the virtual camera. Based on the supplied settings,
/// the Collider will attempt to preserve the line of sight
/// with the LookAt target of the virtual camera by moving
/// away from objects that will obstruct the view.
///
/// Additionally, the Collider can be used to assess the shot quality and
/// report this as a field in the camera State.
/// </summary>
[DocumentationSorting(15, DocumentationSortingAttribute.Level.UserRef)]
[ExecuteInEditMode]
[AddComponentMenu("")] // Hide in menu
[SaveDuringPlay]
public class CinemachineCollider : CinemachineExtension
{
/// <summary>The Unity layer mask against which the collider will raycast.</summary>
[Header("Obstacle Detection")]
[Tooltip("The Unity layer mask against which the collider will raycast")]
public LayerMask m_CollideAgainst = 1;
/// <summary>Obstacles with this tag will be ignored. It is a good idea to set this field to the target's tag</summary>
[TagField]
[Tooltip("Obstacles with this tag will be ignored. It is a good idea to set this field to the target's tag")]
public string m_IgnoreTag = string.Empty;
/// <summary>Obstacles closer to the target than this will be ignored</summary>
[Tooltip("Obstacles closer to the target than this will be ignored")]
public float m_MinimumDistanceFromTarget = 0.1f;
/// <summary>
/// When enabled, will attempt to resolve situations where the line of sight to the
/// target is blocked by an obstacle
/// </summary>
[Space]
[Tooltip("When enabled, will attempt to resolve situations where the line of sight to the target is blocked by an obstacle")]
[FormerlySerializedAs("m_PreserveLineOfSight")]
public bool m_AvoidObstacles = true;
/// <summary>
/// The raycast distance to test for when checking if the line of sight to this camera's target is clear.
/// </summary>
[Tooltip("The maximum raycast distance when checking if the line of sight to this camera's target is clear. If the setting is 0 or less, the current actual distance to target will be used.")]
[FormerlySerializedAs("m_LineOfSightFeelerDistance")]
public float m_DistanceLimit = 0f;
/// <summary>
/// Camera will try to maintain this distance from any obstacle.
/// Increase this value if you are seeing inside obstacles due to a large
/// FOV on the camera.
/// </summary>
[Tooltip("Camera will try to maintain this distance from any obstacle. Try to keep this value small. Increase it if you are seeing inside obstacles due to a large FOV on the camera.")]
public float m_CameraRadius = 0.1f;
/// <summary>The way in which the Collider will attempt to preserve sight of the target.</summary>
public enum ResolutionStrategy
{
/// <summary>Camera will be pulled forward along its Z axis until it is in front of
/// the nearest obstacle</summary>
PullCameraForward,
/// <summary>In addition to pulling the camera forward, an effort will be made to
/// return the camera to its original height</summary>
PreserveCameraHeight,
/// <summary>In addition to pulling the camera forward, an effort will be made to
/// return the camera to its original distance from the target</summary>
PreserveCameraDistance
};
/// <summary>The way in which the Collider will attempt to preserve sight of the target.</summary>
[Tooltip("The way in which the Collider will attempt to preserve sight of the target.")]
public ResolutionStrategy m_Strategy = ResolutionStrategy.PreserveCameraHeight;
/// <summary>
/// Upper limit on how many obstacle hits to process. Higher numbers may impact performance.
/// In most environments, 4 is enough.
/// </summary>
[Range(1, 10)]
[Tooltip("Upper limit on how many obstacle hits to process. Higher numbers may impact performance. In most environments, 4 is enough.")]
public int m_MaximumEffort = 4;
/// <summary>
/// The gradualness of collision resolution. Higher numbers will move the
/// camera more gradually away from obstructions.
/// </summary>
[Range(0, 10)]
[Tooltip("The gradualness of collision resolution. Higher numbers will move the camera more gradually away from obstructions.")]
[FormerlySerializedAs("m_Smoothing")]
public float m_Damping = 0;
/// <summary>If greater than zero, a higher score will be given to shots when the target is closer to
/// this distance. Set this to zero to disable this feature</summary>
[Header("Shot Evaluation")]
[Tooltip("If greater than zero, a higher score will be given to shots when the target is closer to this distance. Set this to zero to disable this feature.")]
public float m_OptimalTargetDistance = 0;
/// <summary>See wheter an object is blocking the camera's view of the target</summary>
/// <param name="vcam">The virtual camera in question. This might be different from the
/// virtual camera that owns the collider, in the event that the camera has children</param>
/// <returns>True if something is blocking the view</returns>
public bool IsTargetObscured(ICinemachineCamera vcam)
{
return GetExtraState<VcamExtraState>(vcam).targetObscured;
}
/// <summary>See whether the virtual camera has been moved nby the collider</summary>
/// <param name="vcam">The virtual camera in question. This might be different from the
/// virtual camera that owns the collider, in the event that the camera has children</param>
/// <returns>True if the virtual camera has been displaced due to collision or
/// target obstruction</returns>
public bool CameraWasDisplaced(CinemachineVirtualCameraBase vcam)
{
return GetExtraState<VcamExtraState>(vcam).colliderDisplacement > 0;
}
private void OnValidate()
{
m_DistanceLimit = Mathf.Max(0, m_DistanceLimit);
m_CameraRadius = Mathf.Max(0, m_CameraRadius);
m_MinimumDistanceFromTarget = Mathf.Max(0.01f, m_MinimumDistanceFromTarget);
m_OptimalTargetDistance = Mathf.Max(0, m_OptimalTargetDistance);
}
/// <summary>Cleanup</summary>
protected override void OnDestroy()
{
base.OnDestroy();
CleanupCameraCollider();
}
/// This must be small but greater than 0 - reduces false results due to precision
const float PrecisionSlush = 0.001f;
// Per-vcam extra state info
class VcamExtraState
{
public Vector3 m_previousDisplacement;
public float colliderDisplacement;
public bool targetObscured;
public List<Vector3> debugResolutionPath;
public void AddPointToDebugPath(Vector3 p)
{
#if UNITY_EDITOR
if (debugResolutionPath == null)
debugResolutionPath = new List<Vector3>();
debugResolutionPath.Add(p);
#endif
}
};
/// <summary>Inspector API for debugging collision resolution path</summary>
public List<List<Vector3>> DebugPaths
{
get
{
List<List<Vector3>> list = new List<List<Vector3>>();
List<VcamExtraState> extraStates = GetAllExtraStates<VcamExtraState>();
foreach (var v in extraStates)
if (v.debugResolutionPath != null)
list.Add(v.debugResolutionPath);
return list;
}
}
/// <summary>Callcack to to the collision resolution and shot evaluation</summary>
protected override void PostPipelineStageCallback(
CinemachineVirtualCameraBase vcam,
CinemachineCore.Stage stage, ref CameraState state, float deltaTime)
{
VcamExtraState extra = null;
if (stage == CinemachineCore.Stage.Body)
{
extra = GetExtraState<VcamExtraState>(vcam);
extra.targetObscured = false;
extra.colliderDisplacement = 0;
extra.debugResolutionPath = null;
}
// Move the body before the Aim is calculated
if (stage == CinemachineCore.Stage.Body)
{
if (m_AvoidObstacles)
{
Vector3 displacement = PreserveLignOfSight(ref state, ref extra);
if (m_Damping > 0 && deltaTime >= 0)
{
Vector3 delta = displacement - extra.m_previousDisplacement;
delta = Damper.Damp(delta, m_Damping, deltaTime);
displacement = extra.m_previousDisplacement + delta;
}
extra.m_previousDisplacement = displacement;
state.PositionCorrection += displacement;
extra.colliderDisplacement += displacement.magnitude;
}
}
// Rate the shot after the aim was set
if (stage == CinemachineCore.Stage.Aim)
{
extra = GetExtraState<VcamExtraState>(vcam);
extra.targetObscured = CheckForTargetObstructions(state);
// GML these values are an initial arbitrary attempt at rating quality
if (extra.targetObscured)
state.ShotQuality *= 0.2f;
if (extra.colliderDisplacement > 0)
state.ShotQuality *= 0.8f;
float nearnessBoost = 0;
const float kMaxNearBoost = 0.2f;
if (m_OptimalTargetDistance > 0 && state.HasLookAt)
{
float distance = Vector3.Magnitude(state.ReferenceLookAt - state.FinalPosition);
if (distance <= m_OptimalTargetDistance)
{
float threshold = m_OptimalTargetDistance / 2;
if (distance >= threshold)
nearnessBoost = kMaxNearBoost * (distance - threshold)
/ (m_OptimalTargetDistance - threshold);
}
else
{
distance -= m_OptimalTargetDistance;
float threshold = m_OptimalTargetDistance * 3;
if (distance < threshold)
nearnessBoost = kMaxNearBoost * (1f - (distance / threshold));
}
state.ShotQuality *= (1f + nearnessBoost);
}
}
}
private Vector3 PreserveLignOfSight(ref CameraState state, ref VcamExtraState extra)
{
Vector3 displacement = Vector3.zero;
if (state.HasLookAt)
{
Vector3 cameraPos = state.CorrectedPosition;
Vector3 lookAtPos = state.ReferenceLookAt;
Vector3 pos = cameraPos;
Vector3 dir = pos - lookAtPos;
float targetDistance = dir.magnitude;
float minDistanceFromTarget = Mathf.Max(m_MinimumDistanceFromTarget, Epsilon);
if (targetDistance > minDistanceFromTarget)
{
dir.Normalize();
float rayLength = targetDistance - minDistanceFromTarget;
if (m_DistanceLimit > Epsilon)
rayLength = Mathf.Min(m_DistanceLimit, rayLength);
// Make a ray that looks towards the camera, to get the most distant obstruction
Ray ray = new Ray(pos - rayLength * dir, dir);
rayLength += PrecisionSlush;
if (rayLength > Epsilon)
{
RaycastHit hitInfo;
if (RaycastIgnoreTag(ray, out hitInfo, rayLength))
{
// Pull camera forward in front of obstacle
float adjustment = Mathf.Max(0, hitInfo.distance - PrecisionSlush);
pos = ray.GetPoint(adjustment);
extra.AddPointToDebugPath(pos);
if (m_Strategy != ResolutionStrategy.PullCameraForward)
{
pos = PushCameraBack(
pos, dir, hitInfo, lookAtPos,
new Plane(state.ReferenceUp, cameraPos),
targetDistance, m_MaximumEffort, ref extra);
}
}
}
}
if (m_CameraRadius > Epsilon)
pos += RespectCameraRadius(pos, state.ReferenceLookAt);
else if (mCameraColliderGameObject != null)
CleanupCameraCollider();
displacement = pos - cameraPos;
}
return displacement;
}
private bool RaycastIgnoreTag(Ray ray, out RaycastHit hitInfo, float rayLength)
{
while (Physics.Raycast(
ray, out hitInfo, rayLength, m_CollideAgainst.value,
QueryTriggerInteraction.Ignore))
{
if (m_IgnoreTag.Length == 0 || !hitInfo.collider.CompareTag(m_IgnoreTag))
return true;
// Pull ray origin forward in front of tagged obstacle
Ray inverseRay = new Ray(ray.GetPoint(rayLength), -ray.direction);
if (!hitInfo.collider.Raycast(inverseRay, out hitInfo, rayLength))
break; // should never happen!
rayLength = hitInfo.distance - PrecisionSlush;
if (rayLength < Epsilon)
break;
ray.origin = inverseRay.GetPoint(rayLength);
}
return false;
}
private Vector3 PushCameraBack(
Vector3 currentPos, Vector3 pushDir, RaycastHit obstacle,
Vector3 lookAtPos, Plane startPlane, float targetDistance, int iterations,
ref VcamExtraState extra)
{
// Take a step along the wall.
Vector3 pos = currentPos;
Vector3 dir = Vector3.zero;
if (!GetWalkingDirection(pos, pushDir, obstacle, ref dir))
return pos;
Ray ray = new Ray(pos, dir);
float distance = GetPushBackDistance(ray, startPlane, targetDistance, lookAtPos);
if (distance <= Epsilon)
return pos;
// Check only as far as the obstacle bounds
float clampedDistance = ClampRayToBounds(ray, distance, obstacle.collider.bounds);
distance = Mathf.Min(distance, clampedDistance + PrecisionSlush);
RaycastHit hitInfo;
if (RaycastIgnoreTag(ray, out hitInfo, distance))
{
// We hit something. Stop there and take a step along that wall.
float adjustment = hitInfo.distance - PrecisionSlush;
pos = ray.GetPoint(adjustment);
extra.AddPointToDebugPath(pos);
if (iterations > 1)
pos = PushCameraBack(
pos, dir, hitInfo,
lookAtPos, startPlane,
targetDistance, iterations-1, ref extra);
return pos;
}
// Didn't hit anything. Can we push back all the way now?
pos = ray.GetPoint(distance);
// First check if we can still see the target. If not, abort
dir = pos - lookAtPos;
float d = dir.magnitude;
RaycastHit hitInfo2;
if (d < Epsilon || RaycastIgnoreTag(new Ray(lookAtPos, dir), out hitInfo2, d - PrecisionSlush))
return currentPos;
// All clear
ray = new Ray(pos, dir);
extra.AddPointToDebugPath(pos);
distance = GetPushBackDistance(ray, startPlane, targetDistance, lookAtPos);
if (distance > Epsilon)
{
if (!RaycastIgnoreTag(ray, out hitInfo, distance))
{
pos = ray.GetPoint(distance); // no obstacles - all good
extra.AddPointToDebugPath(pos);
}
else
{
// We hit something. Stop there and maybe take a step along that wall
float adjustment = hitInfo.distance - PrecisionSlush;
pos = ray.GetPoint(adjustment);
extra.AddPointToDebugPath(pos);
if (iterations > 1)
pos = PushCameraBack(
pos, dir, hitInfo, lookAtPos, startPlane,
targetDistance, iterations-1, ref extra);
}
}
return pos;
}
private RaycastHit[] m_CornerBuffer = new RaycastHit[4];
private bool GetWalkingDirection(
Vector3 pos, Vector3 pushDir, RaycastHit obstacle, ref Vector3 outDir)
{
Vector3 normal2 = obstacle.normal;
// Check for nearby obstacles. Are we in a corner?
float nearbyDistance = PrecisionSlush * 5;
int numFound = Physics.SphereCastNonAlloc(
pos, nearbyDistance, pushDir.normalized, m_CornerBuffer, 0,
m_CollideAgainst.value, QueryTriggerInteraction.Ignore);
if (numFound > 1)
{
// Calculate the second normal
for (int i = 0; i < numFound; ++i)
{
if (m_IgnoreTag.Length > 0 && m_CornerBuffer[i].collider.CompareTag(m_IgnoreTag))
continue;
Type type = m_CornerBuffer[i].collider.GetType();
if (type == typeof(BoxCollider)
|| type == typeof(SphereCollider)
|| type == typeof(CapsuleCollider))
{
Vector3 p = m_CornerBuffer[i].collider.ClosestPoint(pos);
Vector3 d = p - pos;
if (d.magnitude > Vector3.kEpsilon)
{
if (m_CornerBuffer[i].collider.Raycast(
new Ray(pos, d), out m_CornerBuffer[i], nearbyDistance))
{
if (!(m_CornerBuffer[i].normal - obstacle.normal).AlmostZero())
normal2 = m_CornerBuffer[i].normal;
break;
}
}
}
}
}
// Walk along the wall. If we're in a corner, walk their intersecting line
Vector3 dir = Vector3.Cross(obstacle.normal, normal2);
if (dir.AlmostZero())
dir = Vector3.ProjectOnPlane(pushDir, obstacle.normal);
else
{
float dot = Vector3.Dot(dir, pushDir);
if (Mathf.Abs(dot) < Epsilon)
return false;
if (dot < 0)
dir = -dir;
}
if (dir.AlmostZero())
return false;
outDir = dir.normalized;
return true;
}
const float AngleThreshold = 0.1f;
float GetPushBackDistance(Ray ray, Plane startPlane, float targetDistance, Vector3 lookAtPos)
{
float maxDistance = targetDistance - (ray.origin - lookAtPos).magnitude;
if (maxDistance < Epsilon)
return 0;
if (m_Strategy == ResolutionStrategy.PreserveCameraDistance)
return maxDistance;
float distance;
if (!startPlane.Raycast(ray, out distance))
distance = 0;
distance = Mathf.Min(maxDistance, distance);
if (distance < Epsilon)
return 0;
// If we are close to parallel to the plane, we have to take special action
float angle = Mathf.Abs(Vector3.Angle(startPlane.normal, ray.direction) - 90);
if (angle < AngleThreshold)
distance = Mathf.Lerp(0, distance, angle / AngleThreshold);
return distance;
}
float ClampRayToBounds(Ray ray, float distance, Bounds bounds)
{
float d;
if (Vector3.Dot(ray.direction, Vector3.up) > 0)
{
if (new Plane(Vector3.down, bounds.max).Raycast(ray, out d) && d > Epsilon)
distance = Mathf.Min(distance, d);
}
else if (Vector3.Dot(ray.direction, Vector3.down) > 0)
{
if (new Plane(Vector3.up, bounds.min).Raycast(ray, out d) && d > Epsilon)
distance = Mathf.Min(distance, d);
}
if (Vector3.Dot(ray.direction, Vector3.right) > 0)
{
if (new Plane(Vector3.left, bounds.max).Raycast(ray, out d) && d > Epsilon)
distance = Mathf.Min(distance, d);
}
else if (Vector3.Dot(ray.direction, Vector3.left) > 0)
{
if (new Plane(Vector3.right, bounds.min).Raycast(ray, out d) && d > Epsilon)
distance = Mathf.Min(distance, d);
}
if (Vector3.Dot(ray.direction, Vector3.forward) > 0)
{
if (new Plane(Vector3.back, bounds.max).Raycast(ray, out d) && d > Epsilon)
distance = Mathf.Min(distance, d);
}
else if (Vector3.Dot(ray.direction, Vector3.back) > 0)
{
if (new Plane(Vector3.forward, bounds.min).Raycast(ray, out d) && d > Epsilon)
distance = Mathf.Min(distance, d);
}
return distance;
}
private Collider[] mColliderBuffer = new Collider[5];
private SphereCollider mCameraCollider;
private GameObject mCameraColliderGameObject;
private Vector3 RespectCameraRadius(Vector3 cameraPos, Vector3 lookAtPos)
{
Vector3 result = Vector3.zero;
int numObstacles = Physics.OverlapSphereNonAlloc(
cameraPos, m_CameraRadius, mColliderBuffer,
m_CollideAgainst, QueryTriggerInteraction.Ignore);
if (numObstacles > 0)
{
if (mCameraColliderGameObject == null)
{
mCameraColliderGameObject = new GameObject("Cinemachine Collider Collider");
mCameraColliderGameObject.hideFlags = HideFlags.HideAndDontSave;
mCameraColliderGameObject.transform.position = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
mCameraColliderGameObject.SetActive(true);
mCameraCollider = mCameraColliderGameObject.AddComponent<SphereCollider>();
}
mCameraCollider.radius = m_CameraRadius;
for (int i = 0; i < numObstacles; ++i)
{
Collider c = mColliderBuffer[i];
if (m_IgnoreTag.Length > 0 && c.CompareTag(m_IgnoreTag))
continue;
Vector3 dir;
float distance;
if (Physics.ComputePenetration(
mCameraCollider, cameraPos, Quaternion.identity,
c, c.transform.position, c.transform.rotation,
out dir, out distance))
{
result += dir * distance; // naive, but maybe enough
}
}
}
return result;
}
private void CleanupCameraCollider()
{
if (mCameraColliderGameObject != null)
DestroyImmediate(mCameraColliderGameObject);
mCameraColliderGameObject = null;
mCameraCollider = null;
}
private bool CheckForTargetObstructions(CameraState state)
{
if (state.HasLookAt)
{
Vector3 lookAtPos = state.ReferenceLookAt;
Vector3 pos = state.CorrectedPosition;
Vector3 dir = lookAtPos - pos;
float distance = dir.magnitude;
if (distance < Mathf.Max(m_MinimumDistanceFromTarget, Epsilon))
return true;
Ray ray = new Ray(pos, dir.normalized);
RaycastHit hitInfo;
if (RaycastIgnoreTag(ray, out hitInfo, distance - m_MinimumDistanceFromTarget))
return true;
}
return false;
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.Engine.Network.Activation;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Factory;
using Encog.ML.Factory.Train;
using Encog.ML.Train;
namespace Encog.Plugin.SystemPlugin
{
/// <summary>
/// Create the system training methods.
/// </summary>
public class SystemTrainingPlugin : IEncogPluginService1
{
/// <summary>
/// The factory for simulated annealing.
/// </summary>
private readonly AnnealFactory annealFactory = new AnnealFactory();
/// <summary>
/// The factory for backprop.
/// </summary>
private readonly BackPropFactory backpropFactory = new BackPropFactory();
/// <summary>
/// The factory for K2
/// </summary>
private readonly TrainBayesianFactory bayesianFactory = new TrainBayesianFactory();
/// <summary>
/// The factory for genetic.
/// </summary>
private readonly GeneticFactory geneticFactory = new GeneticFactory();
/// <summary>
/// The factory for LMA.
/// </summary>
private readonly LMAFactory lmaFactory = new LMAFactory();
/// <summary>
/// The factory for Manhattan networks.
/// </summary>
private readonly ManhattanFactory manhattanFactory = new ManhattanFactory();
/// <summary>
/// The factory for neighborhood SOM.
/// </summary>
private readonly NeighborhoodSOMFactory neighborhoodFactory
= new NeighborhoodSOMFactory();
/// <summary>
/// Nelder Mead Factory.
/// </summary>
private readonly NelderMeadFactory nmFactory = new NelderMeadFactory();
/// <summary>
/// Factory for PNN.
/// </summary>
private readonly PNNTrainFactory pnnFactory = new PNNTrainFactory();
/// <summary>
/// PSO training factory.
/// </summary>
private readonly PSOFactory psoFactory = new PSOFactory();
/// <summary>
/// Factory for quick prop.
/// </summary>
private readonly QuickPropFactory qpropFactory = new QuickPropFactory();
/// <summary>
/// The factory for RPROP.
/// </summary>
private readonly RPROPFactory rpropFactory = new RPROPFactory();
/// <summary>
/// The factory for SCG.
/// </summary>
private readonly SCGFactory scgFactory = new SCGFactory();
/// <summary>
/// The factory for SOM cluster.
/// </summary>
private readonly ClusterSOMFactory somClusterFactory = new ClusterSOMFactory();
/// <summary>
/// Factory for SVD.
/// </summary>
private readonly RBFSVDFactory svdFactory = new RBFSVDFactory();
/// <summary>
/// The factory for basic SVM.
/// </summary>
private readonly SVMFactory svmFactory = new SVMFactory();
/// <summary>
/// The factory for SVM-Search.
/// </summary>
private readonly SVMSearchFactory svmSearchFactory = new SVMSearchFactory();
private readonly NEATGAFactory neatGAFactory = new NEATGAFactory();
private readonly EPLGAFactory eplTrainFctory = new EPLGAFactory();
#region IEncogPluginService1 Members
/// <inheritdoc/>
public String PluginDescription
{
get
{
return "This plugin provides the built in training " +
"methods for Encog.";
}
}
/// <inheritdoc/>
public String PluginName
{
get { return "HRI-System-Training"; }
}
/// <summary>
/// This is a type-1 plugin.
/// </summary>
public int PluginType
{
get { return 1; }
}
/// <summary>
/// This plugin does not support activation functions, so it will
/// always return null.
/// </summary>
/// <param name="name">Not used.</param>
/// <returns>The activation function.</returns>
public IActivationFunction CreateActivationFunction(String name)
{
return null;
}
public IMLMethod CreateMethod(String methodType, String architecture,
int input, int output)
{
// TODO Auto-generated method stub
return null;
}
public IMLTrain CreateTraining(IMLMethod method, IMLDataSet training,
String type, String args)
{
String args2 = args;
if (args2 == null)
{
args2 = "";
}
if (String.Compare(MLTrainFactory.TypeRPROP, type) == 0)
{
return rpropFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeBackprop, type) == 0)
{
return backpropFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeSCG, type) == 0)
{
return scgFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeLma, type) == 0)
{
return lmaFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeSVM, type) == 0)
{
return svmFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeSVMSearch, type) == 0)
{
return svmSearchFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeSOMNeighborhood, type) == 0)
{
return neighborhoodFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeAnneal, type) == 0)
{
return annealFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeGenetic, type) == 0)
{
return geneticFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeSOMCluster, type) == 0)
{
return somClusterFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeManhattan, type) == 0)
{
return manhattanFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeSvd, type) == 0)
{
return svdFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypePNN, type) == 0)
{
return pnnFactory.Create(method, training, args2);
}
else if (String.Compare(MLTrainFactory.TypeQPROP, type) == 0)
{
return qpropFactory.Create(method, training, args2);
}
else if (MLTrainFactory.TypeBayesian.Equals(type))
{
return bayesianFactory.Create(method, training, args2);
}
else if (MLTrainFactory.TypeNelderMead.Equals(type))
{
return nmFactory.Create(method, training, args2);
}
else if (MLTrainFactory.TypePSO.Equals(type))
{
return psoFactory.Create(method, training, args2);
}
else if (MLTrainFactory.TypeNEATGA.Equals(type))
{
return this.neatGAFactory.Create(method, training, args2);
}
else if (MLTrainFactory.TypeEPLGA.Equals(type))
{
return this.eplTrainFctory.Create(method, training, args2);
}
else
{
throw new EncogError("Unknown training type: " + type);
}
}
/// <inheritdoc/>
public int PluginServiceType
{
get { return EncogPluginBaseConst.SERVICE_TYPE_GENERAL; }
}
#endregion
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// ProfileData
/// </summary>
[DataContract]
public partial class ProfileData : IEquatable<ProfileData>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ProfileData" /> class.
/// </summary>
/// <param name="Allergy">Allergy.</param>
/// <param name="Vegetarian">Vegetarian.</param>
/// <param name="Vip">Vip.</param>
/// <param name="HandicapAccessible">HandicapAccessible.</param>
/// <param name="Anniversary">Anniversary.</param>
/// <param name="CompanyName">CompanyName.</param>
/// <param name="OfficePhone">OfficePhone.</param>
/// <param name="OfficeAddress">OfficeAddress.</param>
/// <param name="TablePreferences">TablePreferences.</param>
public ProfileData(List<string> Allergy = null, bool? Vegetarian = null, bool? Vip = null, bool? HandicapAccessible = null, DateTimeOffset? Anniversary = null, string CompanyName = null, string OfficePhone = null, string OfficeAddress = null, string TablePreferences = null)
{
this.Allergy = Allergy;
this.Vegetarian = Vegetarian;
this.Vip = Vip;
this.HandicapAccessible = HandicapAccessible;
this.Anniversary = Anniversary;
this.CompanyName = CompanyName;
this.OfficePhone = OfficePhone;
this.OfficeAddress = OfficeAddress;
this.TablePreferences = TablePreferences;
}
/// <summary>
/// Gets or Sets Allergy
/// </summary>
[DataMember(Name="allergy", EmitDefaultValue=true)]
public List<string> Allergy { get; set; }
/// <summary>
/// Gets or Sets Vegetarian
/// </summary>
[DataMember(Name="vegetarian", EmitDefaultValue=true)]
public bool? Vegetarian { get; set; }
/// <summary>
/// Gets or Sets Vip
/// </summary>
[DataMember(Name="vip", EmitDefaultValue=true)]
public bool? Vip { get; set; }
/// <summary>
/// Gets or Sets HandicapAccessible
/// </summary>
[DataMember(Name="handicapAccessible", EmitDefaultValue=true)]
public bool? HandicapAccessible { get; set; }
/// <summary>
/// Gets or Sets Anniversary
/// </summary>
[DataMember(Name="anniversary", EmitDefaultValue=true)]
public DateTimeOffset? Anniversary { get; set; }
/// <summary>
/// Gets or Sets CompanyName
/// </summary>
[DataMember(Name="companyName", EmitDefaultValue=true)]
public string CompanyName { get; set; }
/// <summary>
/// Gets or Sets OfficePhone
/// </summary>
[DataMember(Name="officePhone", EmitDefaultValue=true)]
public string OfficePhone { get; set; }
/// <summary>
/// Gets or Sets OfficeAddress
/// </summary>
[DataMember(Name="officeAddress", EmitDefaultValue=true)]
public string OfficeAddress { get; set; }
/// <summary>
/// Gets or Sets TablePreferences
/// </summary>
[DataMember(Name="tablePreferences", EmitDefaultValue=true)]
public string TablePreferences { 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 ProfileData {\n");
sb.Append(" Allergy: ").Append(Allergy).Append("\n");
sb.Append(" Vegetarian: ").Append(Vegetarian).Append("\n");
sb.Append(" Vip: ").Append(Vip).Append("\n");
sb.Append(" HandicapAccessible: ").Append(HandicapAccessible).Append("\n");
sb.Append(" Anniversary: ").Append(Anniversary).Append("\n");
sb.Append(" CompanyName: ").Append(CompanyName).Append("\n");
sb.Append(" OfficePhone: ").Append(OfficePhone).Append("\n");
sb.Append(" OfficeAddress: ").Append(OfficeAddress).Append("\n");
sb.Append(" TablePreferences: ").Append(TablePreferences).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 ProfileData);
}
/// <summary>
/// Returns true if ProfileData instances are equal
/// </summary>
/// <param name="other">Instance of ProfileData to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ProfileData other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Allergy == other.Allergy ||
this.Allergy != null &&
this.Allergy.SequenceEqual(other.Allergy)
) &&
(
this.Vegetarian == other.Vegetarian ||
this.Vegetarian != null &&
this.Vegetarian.Equals(other.Vegetarian)
) &&
(
this.Vip == other.Vip ||
this.Vip != null &&
this.Vip.Equals(other.Vip)
) &&
(
this.HandicapAccessible == other.HandicapAccessible ||
this.HandicapAccessible != null &&
this.HandicapAccessible.Equals(other.HandicapAccessible)
) &&
(
this.Anniversary == other.Anniversary ||
this.Anniversary != null &&
this.Anniversary.Equals(other.Anniversary)
) &&
(
this.CompanyName == other.CompanyName ||
this.CompanyName != null &&
this.CompanyName.Equals(other.CompanyName)
) &&
(
this.OfficePhone == other.OfficePhone ||
this.OfficePhone != null &&
this.OfficePhone.Equals(other.OfficePhone)
) &&
(
this.OfficeAddress == other.OfficeAddress ||
this.OfficeAddress != null &&
this.OfficeAddress.Equals(other.OfficeAddress)
) &&
(
this.TablePreferences == other.TablePreferences ||
this.TablePreferences != null &&
this.TablePreferences.Equals(other.TablePreferences)
);
}
/// <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.Allergy != null)
hash = hash * 59 + this.Allergy.GetHashCode();
if (this.Vegetarian != null)
hash = hash * 59 + this.Vegetarian.GetHashCode();
if (this.Vip != null)
hash = hash * 59 + this.Vip.GetHashCode();
if (this.HandicapAccessible != null)
hash = hash * 59 + this.HandicapAccessible.GetHashCode();
if (this.Anniversary != null)
hash = hash * 59 + this.Anniversary.GetHashCode();
if (this.CompanyName != null)
hash = hash * 59 + this.CompanyName.GetHashCode();
if (this.OfficePhone != null)
hash = hash * 59 + this.OfficePhone.GetHashCode();
if (this.OfficeAddress != null)
hash = hash * 59 + this.OfficeAddress.GetHashCode();
if (this.TablePreferences != null)
hash = hash * 59 + this.TablePreferences.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Windows.Forms;
using Microsoft.VisualStudio.Designer.Interfaces;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// The base class for property pages.
/// </summary>
[CLSCompliant(false), ComVisible(true)]
public abstract class SettingsPage :
LocalizableProperties,
IPropertyPage,
IDisposable
{
#region fields
private Panel panel;
private bool active;
private bool dirty;
private IPropertyPageSite site;
private ProjectNode project;
private ProjectConfig[] projectConfigs;
private IVSMDPropertyGrid grid;
private string name;
private static volatile object Mutex = new object();
private bool isDisposed;
#endregion
#region properties
[Browsable(false)]
[AutomationBrowsable(false)]
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
[Browsable(false)]
[AutomationBrowsable(false)]
public ProjectNode ProjectMgr
{
get
{
return this.project;
}
}
protected IVSMDPropertyGrid Grid
{
get { return this.grid; }
}
protected bool IsDirty
{
get
{
return this.dirty;
}
set
{
if(this.dirty != value)
{
this.dirty = value;
if(this.site != null)
site.OnStatusChange((uint)(this.dirty ? PropPageStatus.Dirty : PropPageStatus.Clean));
}
}
}
protected Panel ThePanel
{
get
{
return this.panel;
}
}
#endregion
#region abstract methods
protected abstract void BindProperties();
protected abstract int ApplyChanges();
#endregion
#region public methods
public object GetTypedConfigProperty(string name, Type type)
{
string value = GetConfigProperty(name);
if(string.IsNullOrEmpty(value)) return null;
TypeConverter tc = TypeDescriptor.GetConverter(type);
return tc.ConvertFromInvariantString(value);
}
public object GetTypedProperty(string name, Type type)
{
string value = GetProperty(name);
if(string.IsNullOrEmpty(value)) return null;
TypeConverter tc = TypeDescriptor.GetConverter(type);
return tc.ConvertFromInvariantString(value);
}
public string GetProperty(string propertyName)
{
if(this.ProjectMgr != null)
{
string property;
bool found = this.ProjectMgr.BuildProject.GlobalProperties.TryGetValue(propertyName, out property);
if(found)
{
return property;
}
}
return String.Empty;
}
// relative to active configuration.
public string GetConfigProperty(string propertyName)
{
if(this.ProjectMgr != null)
{
string unifiedResult = null;
bool cacheNeedReset = true;
for(int i = 0; i < this.projectConfigs.Length; i++)
{
ProjectConfig config = projectConfigs[i];
string property = config.GetConfigurationProperty(propertyName, cacheNeedReset);
cacheNeedReset = false;
if(property != null)
{
string text = property.Trim();
if(i == 0)
unifiedResult = text;
else if(unifiedResult != text)
return ""; // tristate value is blank then
}
}
return unifiedResult;
}
return String.Empty;
}
/// <summary>
/// Sets the value of a configuration dependent property.
/// If the attribute does not exist it is created.
/// If value is null it will be set to an empty string.
/// </summary>
/// <param name="name">property name.</param>
/// <param name="value">value of property</param>
public void SetConfigProperty(string name, string value)
{
CCITracing.TraceCall();
if(value == null)
{
value = String.Empty;
}
if(this.ProjectMgr != null)
{
for(int i = 0, n = this.projectConfigs.Length; i < n; i++)
{
ProjectConfig config = projectConfigs[i];
config.SetConfigurationProperty(name, value);
}
this.ProjectMgr.SetProjectFileDirty(true);
}
}
#endregion
#region IPropertyPage methods.
public virtual void Activate(IntPtr parent, RECT[] pRect, int bModal)
{
if(this.panel == null)
{
if (pRect == null)
{
throw new ArgumentNullException("pRect");
}
this.panel = new Panel();
this.panel.Size = new Size(pRect[0].right - pRect[0].left, pRect[0].bottom - pRect[0].top);
this.panel.Text = SR.GetString(SR.Settings, CultureInfo.CurrentUICulture);
this.panel.Visible = false;
this.panel.Size = new Size(550, 300);
this.panel.CreateControl();
NativeMethods.SetParent(this.panel.Handle, parent);
}
if(this.grid == null && this.project != null && this.project.Site != null)
{
IVSMDPropertyBrowser pb = this.project.Site.GetService(typeof(IVSMDPropertyBrowser)) as IVSMDPropertyBrowser;
this.grid = pb.CreatePropertyGrid();
}
if(this.grid != null)
{
this.active = true;
Control cGrid = Control.FromHandle(new IntPtr(this.grid.Handle));
cGrid.Parent = Control.FromHandle(parent);//this.panel;
cGrid.Size = new Size(544, 294);
cGrid.Location = new Point(3, 3);
cGrid.Visible = true;
this.grid.SetOption(_PROPERTYGRIDOPTION.PGOPT_TOOLBAR, false);
this.grid.GridSort = _PROPERTYGRIDSORT.PGSORT_CATEGORIZED | _PROPERTYGRIDSORT.PGSORT_ALPHABETICAL;
NativeMethods.SetParent(new IntPtr(this.grid.Handle), this.panel.Handle);
UpdateObjects();
}
}
public virtual int Apply()
{
if(IsDirty)
{
return this.ApplyChanges();
}
return VSConstants.S_OK;
}
public virtual void Deactivate()
{
if(null != this.panel)
{
this.panel.Dispose();
this.panel = null;
}
this.active = false;
}
public virtual void GetPageInfo(PROPPAGEINFO[] arrInfo)
{
if (arrInfo == null)
{
throw new ArgumentNullException("arrInfo");
}
PROPPAGEINFO info = new PROPPAGEINFO();
info.cb = (uint)Marshal.SizeOf(typeof(PROPPAGEINFO));
info.dwHelpContext = 0;
info.pszDocString = null;
info.pszHelpFile = null;
info.pszTitle = this.name;
info.SIZE.cx = 550;
info.SIZE.cy = 300;
arrInfo[0] = info;
}
public virtual void Help(string helpDir)
{
}
public virtual int IsPageDirty()
{
// Note this returns an HRESULT not a Bool.
return (IsDirty ? (int)VSConstants.S_OK : (int)VSConstants.S_FALSE);
}
public virtual void Move(RECT[] arrRect)
{
if (arrRect == null)
{
throw new ArgumentNullException("arrRect");
}
RECT r = arrRect[0];
this.panel.Location = new Point(r.left, r.top);
this.panel.Size = new Size(r.right - r.left, r.bottom - r.top);
}
public virtual void SetObjects(uint count, object[] punk)
{
if (punk == null)
{
return;
}
if(count > 0)
{
if(punk[0] is ProjectConfig)
{
ArrayList configs = new ArrayList();
for(int i = 0; i < count; i++)
{
ProjectConfig config = (ProjectConfig)punk[i];
if(this.project == null || (this.project != (punk[0] as ProjectConfig).ProjectMgr))
{
this.project = config.ProjectMgr;
}
configs.Add(config);
}
this.projectConfigs = (ProjectConfig[])configs.ToArray(typeof(ProjectConfig));
}
else if(punk[0] is NodeProperties)
{
if (this.project == null || (this.project != (punk[0] as NodeProperties).Node.ProjectMgr))
{
this.project = (punk[0] as NodeProperties).Node.ProjectMgr;
}
System.Collections.Generic.Dictionary<string, ProjectConfig> configsMap = new System.Collections.Generic.Dictionary<string, ProjectConfig>();
for(int i = 0; i < count; i++)
{
NodeProperties property = (NodeProperties)punk[i];
IVsCfgProvider provider;
ErrorHandler.ThrowOnFailure(property.Node.ProjectMgr.GetCfgProvider(out provider));
uint[] expected = new uint[1];
ErrorHandler.ThrowOnFailure(provider.GetCfgs(0, null, expected, null));
if(expected[0] > 0)
{
ProjectConfig[] configs = new ProjectConfig[expected[0]];
uint[] actual = new uint[1];
ErrorHandler.ThrowOnFailure(provider.GetCfgs(expected[0], configs, actual, null));
foreach(ProjectConfig config in configs)
{
if(!configsMap.ContainsKey(config.ConfigName))
{
configsMap.Add(config.ConfigName, config);
}
}
}
}
if(configsMap.Count > 0)
{
if(this.projectConfigs == null)
{
this.projectConfigs = new ProjectConfig[configsMap.Keys.Count];
}
configsMap.Values.CopyTo(this.projectConfigs, 0);
}
}
}
else
{
this.project = null;
}
if(this.active && this.project != null)
{
UpdateObjects();
}
}
public virtual void SetPageSite(IPropertyPageSite theSite)
{
this.site = theSite;
}
public virtual void Show(uint cmd)
{
this.panel.Visible = true; // TODO: pass SW_SHOW* flags through
this.panel.Show();
}
public virtual int TranslateAccelerator(MSG[] arrMsg)
{
if (arrMsg == null)
{
throw new ArgumentNullException("arrMsg");
}
MSG msg = arrMsg[0];
if((msg.message < NativeMethods.WM_KEYFIRST || msg.message > NativeMethods.WM_KEYLAST) && (msg.message < NativeMethods.WM_MOUSEFIRST || msg.message > NativeMethods.WM_MOUSELAST))
return 1;
return (NativeMethods.IsDialogMessageA(this.panel.Handle, ref msg)) ? 0 : 1;
}
#endregion
#region helper methods
protected ProjectConfig[] GetProjectConfigurations()
{
return this.projectConfigs;
}
protected void UpdateObjects()
{
if(this.projectConfigs != null && this.project != null)
{
// Demand unmanaged permissions in order to access unmanaged memory.
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
IntPtr p = Marshal.GetIUnknownForObject(this);
IntPtr ppUnk = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr)));
try
{
Marshal.WriteIntPtr(ppUnk, p);
this.BindProperties();
// BUGBUG -- this is really bad casting a pointer to "int"...
this.grid.SetSelectedObjects(1, ppUnk.ToInt32());
this.grid.Refresh();
}
finally
{
if(ppUnk != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(ppUnk);
}
if(p != IntPtr.Zero)
{
Marshal.Release(p);
}
}
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void Dispose(bool disposing)
{
if(!this.isDisposed)
{
lock(Mutex)
{
if(disposing)
{
this.panel.Dispose();
}
this.isDisposed = true;
}
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Petstore
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SwaggerPetstore.
/// </summary>
public static partial class SwaggerPetstoreExtensions
{
/// <summary>
/// Fake endpoint to test byte array in body parameter for adding a new pet to
/// the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object in the form of byte array
/// </param>
public static void AddPetUsingByteArray(this ISwaggerPetstore operations, string body = default(string))
{
operations.AddPetUsingByteArrayAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Fake endpoint to test byte array in body parameter for adding a new pet to
/// the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object in the form of byte array
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddPetUsingByteArrayAsync(this ISwaggerPetstore operations, string body = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.AddPetUsingByteArrayWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <remarks>
/// Adds a new pet to the store. You may receive an HTTP invalid input if your
/// pet is invalid.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void AddPet(this ISwaggerPetstore operations, Pet body = default(Pet))
{
operations.AddPetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <remarks>
/// Adds a new pet to the store. You may receive an HTTP invalid input if your
/// pet is invalid.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task AddPetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void UpdatePet(this ISwaggerPetstore operations, Pet body = default(Pet))
{
operations.UpdatePetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetAsync(this ISwaggerPetstore operations, Pet body = default(Pet), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
public static IList<Pet> FindPetsByStatus(this ISwaggerPetstore operations, IList<string> status = default(IList<string>))
{
return operations.FindPetsByStatusAsync(status).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstore operations, IList<string> status = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
public static IList<Pet> FindPetsByTags(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>))
{
return operations.FindPetsByTagsAsync(tags).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstore operations, IList<string> tags = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Fake endpoint to test byte array return by 'Find pet by ID'
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
public static string FindPetsWithByteArray(this ISwaggerPetstore operations, long petId)
{
return operations.FindPetsWithByteArrayAsync(petId).GetAwaiter().GetResult();
}
/// <summary>
/// Fake endpoint to test byte array return by 'Find pet by ID'
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> FindPetsWithByteArrayAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsWithByteArrayWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
public static Pet GetPetById(this ISwaggerPetstore operations, long petId)
{
return operations.GetPetByIdAsync(petId).GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API
/// error conditions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstore operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be updated
/// </param>
/// <param name='name'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
public static void UpdatePetWithForm(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string))
{
operations.UpdatePetWithFormAsync(petId, name, status).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet that needs to be updated
/// </param>
/// <param name='name'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetWithFormAsync(this ISwaggerPetstore operations, string petId, string name = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, name, status, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
public static void DeletePet(this ISwaggerPetstore operations, long petId, string apiKey = default(string))
{
operations.DeletePetAsync(petId, apiKey).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeletePetAsync(this ISwaggerPetstore operations, long petId, string apiKey = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// uploads an image
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet to update
/// </param>
/// <param name='additionalMetadata'>
/// Additional data to pass to server
/// </param>
/// <param name='file'>
/// file to upload
/// </param>
public static void UploadFile(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), Stream file = default(Stream))
{
operations.UploadFileAsync(petId, additionalMetadata, file).GetAwaiter().GetResult();
}
/// <summary>
/// uploads an image
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// ID of pet to update
/// </param>
/// <param name='additionalMetadata'>
/// Additional data to pass to server
/// </param>
/// <param name='file'>
/// file to upload
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UploadFileAsync(this ISwaggerPetstore operations, long petId, string additionalMetadata = default(string), Stream file = default(Stream), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UploadFileWithHttpMessagesAsync(petId, additionalMetadata, file, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IDictionary<string, int?> GetInventory(this ISwaggerPetstore operations)
{
return operations.GetInventoryAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
public static Order PlaceOrder(this ISwaggerPetstore operations, Order body = default(Order))
{
return operations.PlaceOrderAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstore operations, Order body = default(Order), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of pet that needs to be fetched
/// </param>
public static Order GetOrderById(this ISwaggerPetstore operations, string orderId)
{
return operations.GetOrderByIdAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of the order that needs to be deleted
/// </param>
public static void DeleteOrder(this ISwaggerPetstore operations, string orderId)
{
operations.DeleteOrderAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// ID of the order that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteOrderAsync(this ISwaggerPetstore operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
public static void CreateUser(this ISwaggerPetstore operations, User body = default(User))
{
operations.CreateUserAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUserAsync(this ISwaggerPetstore operations, User body = default(User), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithArrayInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>))
{
operations.CreateUsersWithArrayInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithListInput(this ISwaggerPetstore operations, IList<User> body = default(IList<User>))
{
operations.CreateUsersWithListInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstore operations, IList<User> body = default(IList<User>), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
public static string LoginUser(this ISwaggerPetstore operations, string username = default(string), string password = default(string))
{
return operations.LoginUserAsync(username, password).GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> LoginUserAsync(this ISwaggerPetstore operations, string username = default(string), string password = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void LogoutUser(this ISwaggerPetstore operations)
{
operations.LogoutUserAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LogoutUserAsync(this ISwaggerPetstore operations, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
public static User GetUserByName(this ISwaggerPetstore operations, string username)
{
return operations.GetUserByNameAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetUserByNameAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
public static void UpdateUser(this ISwaggerPetstore operations, string username, User body = default(User))
{
operations.UpdateUserAsync(username, body).GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateUserAsync(this ISwaggerPetstore operations, string username, User body = default(User), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
public static void DeleteUser(this ISwaggerPetstore operations, string username)
{
operations.DeleteUserAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteUserAsync(this ISwaggerPetstore operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Web.Services;
using System.Web.Services.Protocols;
using WebsitePanel.Providers;
using WebsitePanel.Providers.DNS;
using WebsitePanel.Server.Utils;
using Microsoft.Web.Services3;
namespace WebsitePanel.Server
{
/// <summary>
/// Summary description for DNSServer
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/server/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class DNSServer : HostingServiceProviderWebService, IDnsServer
{
private IDnsServer DnsProvider
{
get { return (IDnsServer)Provider; }
}
private string GetAsciiZoneName(string zoneName)
{
if (string.IsNullOrEmpty(zoneName)) return zoneName;
var idn = new IdnMapping();
return idn.GetAscii(zoneName);
}
#region Zones
[WebMethod, SoapHeader("settings")]
public bool ZoneExists(string zoneName)
{
try
{
Log.WriteStart("'{0}' ZoneExists", ProviderSettings.ProviderName);
bool result = DnsProvider.ZoneExists(GetAsciiZoneName(zoneName));
Log.WriteEnd("'{0}' ZoneExists", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ZoneExists", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetZones()
{
try
{
Log.WriteStart("'{0}' GetZones", ProviderSettings.ProviderName);
string[] result = DnsProvider.GetZones();
Log.WriteEnd("'{0}' GetZones", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetZones", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void AddPrimaryZone(string zoneName, string[] secondaryServers)
{
try
{
Log.WriteStart("'{0}' AddPrimaryZone", ProviderSettings.ProviderName);
DnsProvider.AddPrimaryZone(GetAsciiZoneName(zoneName), secondaryServers);
Log.WriteEnd("'{0}' AddPrimaryZone", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddPrimaryZone", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void AddSecondaryZone(string zoneName, string[] masterServers)
{
try
{
Log.WriteStart("'{0}' AddSecondaryZone", ProviderSettings.ProviderName);
DnsProvider.AddSecondaryZone(GetAsciiZoneName(zoneName), masterServers);
Log.WriteEnd("'{0}' AddSecondaryZone", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddSecondaryZone", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteZone(string zoneName)
{
try
{
Log.WriteStart("'{0}' DeleteZone", ProviderSettings.ProviderName);
DnsProvider.DeleteZone(GetAsciiZoneName(zoneName));
Log.WriteEnd("'{0}' DeleteZone", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteZone", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void UpdateSoaRecord(string zoneName, string host, string primaryNsServer, string primaryPerson)
{
try
{
Log.WriteStart("'{0}' UpdateSoaRecord", ProviderSettings.ProviderName);
DnsProvider.UpdateSoaRecord(GetAsciiZoneName(zoneName), host, primaryNsServer, primaryPerson);
Log.WriteEnd("'{0}' UpdateSoaRecord", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateSoaRecord", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
#region Records
[WebMethod, SoapHeader("settings")]
public DnsRecord[] GetZoneRecords(string zoneName)
{
try
{
Log.WriteStart("'{0}' GetZoneRecords", ProviderSettings.ProviderName);
DnsRecord[] result = DnsProvider.GetZoneRecords(GetAsciiZoneName(zoneName));
Log.WriteEnd("'{0}' GetZoneRecords", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetZoneRecords", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void AddZoneRecord(string zoneName, DnsRecord record)
{
try
{
Log.WriteStart("'{0}' AddZoneRecord", ProviderSettings.ProviderName);
DnsProvider.AddZoneRecord(GetAsciiZoneName(zoneName), record);
Log.WriteEnd("'{0}' AddZoneRecord", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddZoneRecord", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteZoneRecord(string zoneName, DnsRecord record)
{
try
{
Log.WriteStart("'{0}' DeleteZoneRecord", ProviderSettings.ProviderName);
DnsProvider.DeleteZoneRecord(GetAsciiZoneName(zoneName), record);
Log.WriteEnd("'{0}' DeleteZoneRecord", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteZoneRecord", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void AddZoneRecords(string zoneName, DnsRecord[] records)
{
try
{
Log.WriteStart("'{0}' AddZoneRecords", ProviderSettings.ProviderName);
DnsProvider.AddZoneRecords(GetAsciiZoneName(zoneName), records);
Log.WriteEnd("'{0}' AddZoneRecords", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddZoneRecords", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void DeleteZoneRecords(string zoneName, DnsRecord[] records)
{
try
{
Log.WriteStart("'{0}' DeleteZoneRecords", ProviderSettings.ProviderName);
DnsProvider.DeleteZoneRecords(GetAsciiZoneName(zoneName), records);
Log.WriteEnd("'{0}' DeleteZoneRecords", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' DeleteZoneRecords", ProviderSettings.ProviderName), ex);
throw;
}
}
#endregion
}
}
| |
using System;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.WebEditing.Elements;
using System.ComponentModel;
namespace GuruComponents.Netrix.WebEditing.Elements
{
/// <summary>
/// This class allows access to additional information about an element and advanced element manipulation.
/// </summary>
/// <remarks>
/// This class enhances the basic Element class. It was introduced to avoid
/// the ability of non-HTML attributes for propertygrid access. The ScrollXX properties allow the
/// detection of the current scroll position to synchronize external controls like ruler or bars.
/// <para>
/// The positions are in pixel and relative to the control window.
/// </para>
/// </remarks>
public sealed class ExtendedProperties : IExtendedProperties
{
private Interop.IHTMLElement element;
/// <summary>
/// Constructor to create an instance of the class.
/// </summary>
/// <remarks>
/// THIS CTOR SUPPORTS THE NETRIX INFRASTRUCTURE AND IS NIT INTENDET TO BEING USED FROM USER CODE.
/// </remarks>
/// <param name="peer"></param>
public ExtendedProperties(Interop.IHTMLElement peer)
{
element = peer;
}
private Interop.IHTMLElement2 el2
{
get
{
return (Interop.IHTMLElement2) element;
}
}
private Interop.IHTMLElement3 el3
{
get
{
return (Interop.IHTMLElement3) element;
}
}
private Interop.IHTMLElement4 el4
{
get
{
return (Interop.IHTMLElement4) element;
}
}
/// <summary>
/// Simulates a click on a scroll-bar component.
/// </summary>
/// <remarks>
/// Cascading Style Sheets (CSS) allow you to scroll on all objects through the IHTMLStyle::overflow property.
/// <para>When the content of an element changes and causes scroll bars to display, the IHTMLElement2::doScroll method might not work correctly immediately following the content update. When this happens, you can use the IHTMLWindow2::setTimeout method to enable the browser to recognize the dynamic changes that affect scrolling.</para>
/// </remarks>
/// <param name="scroll"></param>
public void DoScroll(ScrollAction scroll)
{
el2.DoScroll(scroll.ToString());
}
/// <summary>
/// Returns the component located at the specified coordinates via certain events.
/// </summary>
/// <remarks>
/// A component is a part of the element, which acts as an specific interaction point. Typically these
/// are the scrollbars as well as parts of the scrollbar, and the resizing handles. The property can
/// be used to determine such an element at a specific client location.
/// <para>The ComponentFromPoint method, available as of MSHTML 5, is applicable to any object that can be given scroll bars
/// through Cascading Style Sheets (CSS).</para>
/// <para>The ComponentFromPoint method may not consistently return the same object when used with the <c>MouseOver</c> event. Because
/// a user's mouse speed and entry point can vary, different components of an element can fire the <c>MouseOver</c> event.
/// For example, when a user moves the cursor over a <see cref="AreaElement">AreaElement</see> object with scroll bars, the event might fire when the mouse
/// enters the component border, the scroll bars, or the client region. Once the event fires, the expected element may not
/// be returned unless the scroll bars were the point of entry for the mouse. In this case, the onmousemove event can be
/// used to provide more consistent results.</para>
/// <para>
/// A good idea to get the current handle is the <c>ResizeStart</c> event, which is fired when the mouse is on top of one
/// of the handles of an selected element. However, this will never return components other than "HandleXX" or nothing.
/// </para>
/// </remarks>
/// <param name="loc">Location in client coordinates of the point for which the component is retrieved.</param>
public ElementComponent ComponentFromPoint(System.Drawing.Point loc)
{
string c = el2.ComponentFromPoint(loc.X, loc.Y);
if (c == null || c.Equals(String.Empty))
{
return ElementComponent.ClientArea;
}
else
{
return (ElementComponent) Enum.Parse(typeof(ElementComponent), c, true);
}
}
/// <summary>
/// Sets or retrieves the distance between the left edge of the object and the leftmost portion of the content currently visible in the window.
/// </summary>
/// <remarks>
/// This property's value equals the current horizontal offset of the content within the scrollable range. Although you can set this property to any value, if you assign a value less than 0, the property is set to 0. If you assign a value greater than the maximum value, the property is set to the maximum value.
/// <para>This property is always 0 for objects that do not have scroll bars. For these objects, setting the property has no effect.</para>
/// <para>When a marquee object scrolls vertically, its ScrollLeft extended property is set to 0.</para>
/// </remarks>
[Browsable(false)]
public int ScrollLeft
{
get
{
return el2.GetScrollLeft();
}
}
/// <summary>
/// Sets or retrieves the distance between the top of the object and the topmost portion of the content currently visible in the window.
/// </summary>
/// <remarks>
/// This property's value equals the current vertical offset of the content within the scrollable range. Although you can set this property to any value, if you assign a value less than 0, the property is set to 0. If you assign a value greater than the maximum value, the property is set to the maximum value.
/// <para>This property is always 0 for objects that do not have scroll bars. For these objects, setting the property has no effect.</para>
/// <para>When a marquee object scrolls horizontally, its ScrollTop extended property is set to 0.</para>
/// </remarks>
[Browsable(false)]
public int ScrollTop
{
get
{
return el2.GetScrollTop();
}
}
/// <summary>
/// Retrieves the scrolling height of the object.
/// </summary>
/// <remarks>
/// The height is the distance between the top and bottom edges of the object's content.
/// </remarks>
[Browsable(false)]
public int ScrollHeight
{
get
{
return el2.GetScrollHeight();
}
}
/// <summary>
/// Retrieves the scrolling width of the object.
/// </summary>
/// <remarks>
/// The width is the distance between the left and right edges of the object's visible content.
/// </remarks>
[Browsable(false)]
public int ScrollWidth
{
get
{
return el2.GetScrollWidth();
}
}
/// <summary>
/// Retrieves the client area of the object including padding, but not including margin, border, or scroll bar.
/// </summary>
[Browsable(false)]
public System.Drawing.Rectangle ClientArea
{
get
{
System.Drawing.Rectangle r = new System.Drawing.Rectangle(
el2.GetClientLeft(),
el2.GetClientTop(),
el2.GetClientWidth(),
el2.GetClientHeight()
);
return r;
}
}
/// <summary>
/// Retrieves an object that specifies the bounds of the elements.
/// </summary>
[Browsable(false)]
public System.Drawing.Rectangle AbsoluteArea
{
get
{
Interop.IHTMLRect rect = el2.GetBoundingClientRect();
System.Drawing.Rectangle r = new System.Drawing.Rectangle(
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top
);
return r;
}
}
/// <summary>
/// Merges adjacent <see cref="TextNodeElement"/> objects to produce a normalized document object model.
/// </summary>
/// <remarks>
/// Calling Normalize before manipulating the subelements of an object ensures that the document object model has a consistent structure. The normal form is useful for operations that require a consistent document tree structure, and it ensures that the document object model view is identical when saved and reloaded.
/// </remarks>
public void Normalize()
{
el4.normalize();
}
/// <overloads/>
/// <summary>
/// Causes the object to scroll into view, aligning at the top of the window.
/// </summary>
/// <remarks>
/// The ScrollIntoView method is useful for immediately showing the user the result of some action without requiring the user to manually scroll through the document to find the result.
/// <para>Depending on the size of the given object and the current window, this method might not be able to put the item at the very top or very bottom, but will position the object as close to the requested position as possible.</para>
/// </remarks>
public void ScrollIntoView()
{
ScrollIntoView(true);
}
/// <summary>
/// Causes the object to scroll into view, aligning it either at the top or bottom of the window.
/// </summary>
/// <remarks>
/// The ScrollIntoView method is useful for immediately showing the user the result of some action without requiring the user to manually scroll through the document to find the result.
/// <para>Depending on the size of the given object and the current window, this method might not be able to put the item at the very top or very bottom, but will position the object as close to the requested position as possible.</para>
/// </remarks>
/// <param name="top">Specifies where to scroll to. If <c>true</c> the element is scrolled to top position.</param>
public void ScrollIntoView(bool top)
{
element.ScrollIntoView(top);
}
/// <summary>
/// Retrieves the ordinal position of the object, in source order, as the object appears in the document's all collection.
/// </summary>
[Browsable(false)]
public int DOMIndex
{
get
{
return element.GetSourceIndex();
}
}
/// <summary>
/// Sets the element as active without setting focus to the element.
/// </summary>
/// <remarks>The setActive method does not cause the document to scroll to the active object in the current page.</remarks>
public void SetActive()
{
el3.setActive();
}
/// <summary>
/// Set the ability to capture the focus.
/// </summary>
/// <param name="containerCapture"></param>
public void SetCapture(bool containerCapture)
{
el2.SetCapture(containerCapture);
}
/// <summary>
/// Release the ability to capture the focus.
/// </summary>
public void ReleaseCapture()
{
el2.ReleaseCapture();
}
/// <summary>
/// Sets or retrieves the value indicating whether the object visibly indicates that it has focus.
/// </summary>
public bool HideFocus
{
get { return el3.hideFocus; }
set { el3.hideFocus = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.Common
{
public class DbConnectionStringBuilder : System.Collections.IDictionary
{
// keyword->value currently listed in the connection string
private Dictionary<string, object> _currentValues;
// cached connectionstring to avoid constant rebuilding
// and to return a user's connectionstring as is until editing occurs
private string _connectionString = "";
public DbConnectionStringBuilder()
{
}
private ICollection Collection
{
get { return (ICollection)CurrentValues; }
}
private IDictionary Dictionary
{
get { return (IDictionary)CurrentValues; }
}
private Dictionary<string, object> CurrentValues
{
get
{
Dictionary<string, object> values = _currentValues;
if (null == values)
{
values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
_currentValues = values;
}
return values;
}
}
object System.Collections.IDictionary.this[object keyword]
{
// delegate to this[string keyword]
get { return this[ObjectToString(keyword)]; }
set { this[ObjectToString(keyword)] = value; }
}
public virtual object this[string keyword]
{
get
{
ADP.CheckArgumentNull(keyword, "keyword");
object value;
if (CurrentValues.TryGetValue(keyword, out value))
{
return value;
}
throw ADP.KeywordNotSupported(keyword);
}
set
{
ADP.CheckArgumentNull(keyword, "keyword");
if (null != value)
{
string keyvalue = DbConnectionStringBuilderUtil.ConvertToString(value);
DbConnectionOptions.ValidateKeyValuePair(keyword, keyvalue);
// store keyword/value pair
CurrentValues[keyword] = keyvalue;
}
_connectionString = null;
}
}
public string ConnectionString
{
get
{
string connectionString = _connectionString;
if (null == connectionString)
{
StringBuilder builder = new StringBuilder();
foreach (string keyword in Keys)
{
object value;
if (ShouldSerialize(keyword) && TryGetValue(keyword, out value))
{
string keyvalue = (null != value) ? Convert.ToString(value, CultureInfo.InvariantCulture) : (string)null;
AppendKeyValuePair(builder, keyword, keyvalue);
}
}
connectionString = builder.ToString();
_connectionString = connectionString;
}
return connectionString;
}
set
{
DbConnectionOptions constr = new DbConnectionOptions(value, null);
string originalValue = ConnectionString;
Clear();
try
{
for (NameValuePair pair = constr.KeyChain; null != pair; pair = pair.Next)
{
if (null != pair.Value)
{
this[pair.Name] = pair.Value;
}
else
{
Remove(pair.Name);
}
}
_connectionString = null;
}
catch (ArgumentException)
{ // restore original string
ConnectionString = originalValue;
_connectionString = originalValue;
throw;
}
}
}
public virtual int Count
{
get { return CurrentValues.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public virtual bool IsFixedSize
{
get { return false; }
}
bool System.Collections.ICollection.IsSynchronized
{
get { return Collection.IsSynchronized; }
}
public virtual ICollection Keys
{
get
{
return Dictionary.Keys;
}
}
object System.Collections.ICollection.SyncRoot
{
get { return Collection.SyncRoot; }
}
public virtual ICollection Values
{
get
{
System.Collections.Generic.ICollection<string> keys = (System.Collections.Generic.ICollection<string>)Keys;
System.Collections.Generic.IEnumerator<string> keylist = keys.GetEnumerator();
object[] values = new object[keys.Count];
for (int i = 0; i < values.Length; ++i)
{
keylist.MoveNext();
values[i] = this[keylist.Current];
Debug.Assert(null != values[i], "null value " + keylist.Current);
}
return new System.Data.Common.ReadOnlyCollection<object>(values);
}
}
void System.Collections.IDictionary.Add(object keyword, object value)
{
Add(ObjectToString(keyword), value);
}
public void Add(string keyword, object value)
{
this[keyword] = value;
}
public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value)
{
DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, false);
}
public virtual void Clear()
{
_connectionString = "";
CurrentValues.Clear();
}
// does the keyword exist as a strongly typed keyword or as a stored value
bool System.Collections.IDictionary.Contains(object keyword)
{
return ContainsKey(ObjectToString(keyword));
}
public virtual bool ContainsKey(string keyword)
{
ADP.CheckArgumentNull(keyword, "keyword");
return CurrentValues.ContainsKey(keyword);
}
void ICollection.CopyTo(Array array, int index)
{
Collection.CopyTo(array, index);
}
public virtual bool EquivalentTo(DbConnectionStringBuilder connectionStringBuilder)
{
ADP.CheckArgumentNull(connectionStringBuilder, "connectionStringBuilder");
if ((GetType() != connectionStringBuilder.GetType()) || (CurrentValues.Count != connectionStringBuilder.CurrentValues.Count))
{
return false;
}
object value;
foreach (KeyValuePair<string, object> entry in CurrentValues)
{
if (!connectionStringBuilder.CurrentValues.TryGetValue(entry.Key, out value) || !entry.Value.Equals(value))
{
return false;
}
}
return true;
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Collection.GetEnumerator();
}
IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator()
{
return Dictionary.GetEnumerator();
}
private string ObjectToString(object keyword)
{
try
{
return (string)keyword;
}
catch (InvalidCastException)
{
throw new ArgumentException(nameof(keyword), "not a string");
}
}
void System.Collections.IDictionary.Remove(object keyword)
{
Remove(ObjectToString(keyword));
}
public virtual bool Remove(string keyword)
{
ADP.CheckArgumentNull(keyword, "keyword");
if (CurrentValues.Remove(keyword))
{
_connectionString = null;
return true;
}
return false;
}
// does the keyword exist as a stored value or something that should always be persisted
public virtual bool ShouldSerialize(string keyword)
{
ADP.CheckArgumentNull(keyword, "keyword");
return CurrentValues.ContainsKey(keyword);
}
public override string ToString()
{
return ConnectionString;
}
public virtual bool TryGetValue(string keyword, out object value)
{
ADP.CheckArgumentNull(keyword, "keyword");
return CurrentValues.TryGetValue(keyword, out value);
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Last Years GL Financial Trans
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class GLFPREV : EduHubEntity
{
#region Navigation Property Cache
private GLPREV Cache_CODE_GLPREV;
private KGST Cache_GST_TYPE_KGST;
private KGLSUB Cache_SUBPROGRAM_KGLSUB;
private KGLPROG Cache_GLPROGRAM_KGLPROG;
private KGLINIT Cache_INITIATIVE_KGLINIT;
private SGFC Cache_FEE_CODE_SGFC;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Transaction ID (internal)
/// </summary>
public int TID { get; internal set; }
/// <summary>
/// General Ledger Code
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string CODE { get; internal set; }
/// <summary>
/// Batch number
/// </summary>
public int? TRBATCH { get; internal set; }
/// <summary>
/// GX period number eg. 199208
/// </summary>
public int? TRPERD { get; internal set; }
/// <summary>
/// Transaction type
/// J - Journal
/// R - Receipt
/// P - Payment
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string TRTYPE { get; internal set; }
/// <summary>
/// Transaction quantity
/// </summary>
public int? TRQTY { get; internal set; }
/// <summary>
/// Transaction date
/// </summary>
public DateTime? TRDATE { get; internal set; }
/// <summary>
/// Transaction reference
/// [Alphanumeric (10)]
/// </summary>
public string TRREF { get; internal set; }
/// <summary>
/// Transaction amount
/// </summary>
public decimal? TRAMT { get; internal set; }
/// <summary>
/// Transaction description
/// [Alphanumeric (30)]
/// </summary>
public string TRDET { get; internal set; }
/// <summary>
/// Ledger type eg DF, IV, AR, CR, DM
/// [Uppercase Alphanumeric (2)]
/// </summary>
public string TRXLEDGER { get; internal set; }
/// <summary>
/// Post code for through posting to subledgers
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string TRXCODE { get; internal set; }
/// <summary>
/// TRTYPE for through posting to subledgers
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string TRXTRTYPE { get; internal set; }
/// <summary>
/// DR/CR short/key
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string TRSHORT { get; internal set; }
/// <summary>
/// Not used in JX leave for
/// compatibility
/// Bank account for multiple bank
/// accounts
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string TRBANK { get; internal set; }
/// <summary>
/// Bank reconciliation flag
/// Y - reconciled
/// N - not yet reconciled
/// Not used for RX set leave for
/// compatibility
/// [Alphanumeric (1)]
/// </summary>
public string RECONCILE { get; internal set; }
/// <summary>
/// Transaction is flagged as reconcile pending
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string RECONCILE_FLAGGED { get; internal set; }
/// <summary>
/// Date that the transaction was reconciled
/// </summary>
public DateTime? RECONCILE_DATE { get; internal set; }
/// <summary>
/// User that reconciled the transaction
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string RECONCILE_USER { get; internal set; }
/// <summary>
/// The date of the bank statement that the transaction appeared in
/// </summary>
public DateTime? RECONCILE_STATEMENT { get; internal set; }
/// <summary>
/// "Y" - print cheque
/// [Alphanumeric (1)]
/// </summary>
public string PRINT_CHEQUE { get; internal set; }
/// <summary>
/// Cheque number
/// [Alphanumeric (10)]
/// </summary>
public string CHEQUE_NO { get; internal set; }
/// <summary>
/// Payee for cheques
/// [Alphanumeric (30)]
/// </summary>
public string PAYEE { get; internal set; }
/// <summary>
/// Payee address
/// [Alphanumeric (30)]
/// </summary>
public string ADDRESS01 { get; internal set; }
/// <summary>
/// Payee address
/// [Alphanumeric (30)]
/// </summary>
public string ADDRESS02 { get; internal set; }
/// <summary>
/// Creditor transaction's TID No
/// </summary>
public int? CHQ_TID { get; internal set; }
/// <summary>
/// where does this appear in the BAS
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string GST_BOX { get; internal set; }
/// <summary>
/// what Period was this Reported
/// </summary>
public int? GST_PERD { get; internal set; }
/// <summary>
/// GST Dollar amount for this
/// transaction
/// </summary>
public decimal? GST_AMOUNT { get; internal set; }
/// <summary>
/// Added for software compatibilty
/// See gl receipts
/// </summary>
public decimal? TRNETT { get; internal set; }
/// <summary>
/// Gross amount which includes GST
/// </summary>
public decimal? TRGROSS { get; internal set; }
/// <summary>
/// what rate was the GST apllied
/// </summary>
public double? GST_RATE { get; internal set; }
/// <summary>
/// What type of GST
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string GST_TYPE { get; internal set; }
/// <summary>
/// Is this being claimed
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string GST_RECLAIM { get; internal set; }
/// <summary>
/// S, PO, PC indicates type of
/// purchase or sale
/// [Uppercase Alphanumeric (2)]
/// </summary>
public string GST_SALE_PURCH { get; internal set; }
/// <summary>
/// Source tid from creditors or GL
/// </summary>
public int? SOURCE_TID { get; internal set; }
/// <summary>
/// Amount of Withholding TAX for this
/// invoice line
/// </summary>
public decimal? WITHHOLD_AMOUNT { get; internal set; }
/// <summary>
/// Required for GL payments with
/// withheld amounts
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string WITHHOLD_TYPE { get; internal set; }
/// <summary>
/// Withhold Rate
/// </summary>
public double? WITHHOLD_RATE { get; internal set; }
/// <summary>
/// Was this transaction retianed by
/// the eoy
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string EOY_KEPT { get; internal set; }
/// <summary>
/// Bank client
/// [Alphanumeric (20)]
/// </summary>
public string DRAWER { get; internal set; }
/// <summary>
/// Bank/State/Branch (Cheque)
/// [Alphanumeric (6)]
/// </summary>
public string BSB { get; internal set; }
/// <summary>
/// Bank name
/// [Alphanumeric (20)]
/// </summary>
public string BANK { get; internal set; }
/// <summary>
/// Branch location
/// [Alphanumeric (20)]
/// </summary>
public string BRANCH { get; internal set; }
/// <summary>
/// Bank account number
/// </summary>
public int? ACCOUNT_NUMBER { get; internal set; }
/// <summary>
/// <No documentation available>
/// [Uppercase Alphanumeric (2)]
/// </summary>
public string RTYPE { get; internal set; }
/// <summary>
/// Line number in the batch
/// </summary>
public int? LINE_NO { get; internal set; }
/// <summary>
/// Determines through posts
/// 0 = Don't show T/P
/// 1 = Show T/P
/// </summary>
public int? FLAG { get; internal set; }
/// <summary>
/// Mandatory field
/// </summary>
public decimal? DEBIT_TOTAL { get; internal set; }
/// <summary>
/// Mandatory field
/// </summary>
public decimal? CREDIT_TOTAL { get; internal set; }
/// <summary>
/// For every transaction there is a subprogram
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string SUBPROGRAM { get; internal set; }
/// <summary>
/// A subprogram always belongs to a program
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string GLPROGRAM { get; internal set; }
/// <summary>
/// Transaction might belong to an Initiative
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string INITIATIVE { get; internal set; }
/// <summary>
/// To allow journals processing
/// </summary>
public decimal? DEBIT { get; internal set; }
/// <summary>
/// <No documentation available>
/// </summary>
public decimal? CREDIT { get; internal set; }
/// <summary>
/// Only filled in for cancelled payment/receipt
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string CANCELLED { get; internal set; }
/// <summary>
/// Fee code
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string FEE_CODE { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// GLPREV (Last Years General Ledger) related entity by [GLFPREV.CODE]->[GLPREV.CODE]
/// General Ledger Code
/// </summary>
public GLPREV CODE_GLPREV
{
get
{
if (Cache_CODE_GLPREV == null)
{
Cache_CODE_GLPREV = Context.GLPREV.FindByCODE(CODE);
}
return Cache_CODE_GLPREV;
}
}
/// <summary>
/// KGST (GST Percentages) related entity by [GLFPREV.GST_TYPE]->[KGST.KGSTKEY]
/// What type of GST
/// </summary>
public KGST GST_TYPE_KGST
{
get
{
if (GST_TYPE == null)
{
return null;
}
if (Cache_GST_TYPE_KGST == null)
{
Cache_GST_TYPE_KGST = Context.KGST.FindByKGSTKEY(GST_TYPE);
}
return Cache_GST_TYPE_KGST;
}
}
/// <summary>
/// KGLSUB (General Ledger Sub Programs) related entity by [GLFPREV.SUBPROGRAM]->[KGLSUB.SUBPROGRAM]
/// For every transaction there is a subprogram
/// </summary>
public KGLSUB SUBPROGRAM_KGLSUB
{
get
{
if (SUBPROGRAM == null)
{
return null;
}
if (Cache_SUBPROGRAM_KGLSUB == null)
{
Cache_SUBPROGRAM_KGLSUB = Context.KGLSUB.FindBySUBPROGRAM(SUBPROGRAM);
}
return Cache_SUBPROGRAM_KGLSUB;
}
}
/// <summary>
/// KGLPROG (General Ledger Programs) related entity by [GLFPREV.GLPROGRAM]->[KGLPROG.GLPROGRAM]
/// A subprogram always belongs to a program
/// </summary>
public KGLPROG GLPROGRAM_KGLPROG
{
get
{
if (GLPROGRAM == null)
{
return null;
}
if (Cache_GLPROGRAM_KGLPROG == null)
{
Cache_GLPROGRAM_KGLPROG = Context.KGLPROG.FindByGLPROGRAM(GLPROGRAM);
}
return Cache_GLPROGRAM_KGLPROG;
}
}
/// <summary>
/// KGLINIT (General Ledger Initiatives) related entity by [GLFPREV.INITIATIVE]->[KGLINIT.INITIATIVE]
/// Transaction might belong to an Initiative
/// </summary>
public KGLINIT INITIATIVE_KGLINIT
{
get
{
if (INITIATIVE == null)
{
return null;
}
if (Cache_INITIATIVE_KGLINIT == null)
{
Cache_INITIATIVE_KGLINIT = Context.KGLINIT.FindByINITIATIVE(INITIATIVE);
}
return Cache_INITIATIVE_KGLINIT;
}
}
/// <summary>
/// SGFC (General Ledger Fees) related entity by [GLFPREV.FEE_CODE]->[SGFC.SGFCKEY]
/// Fee code
/// </summary>
public SGFC FEE_CODE_SGFC
{
get
{
if (FEE_CODE == null)
{
return null;
}
if (Cache_FEE_CODE_SGFC == null)
{
Cache_FEE_CODE_SGFC = Context.SGFC.FindBySGFCKEY(FEE_CODE);
}
return Cache_FEE_CODE_SGFC;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
public static class ParallelQueryTests
{
[Fact]
public static void RunTests()
{
LeftOperator[] leftOps = new LeftOperator[] {
new LeftOperator("MakeCast", MakeCast, true),
new LeftOperator("MakeConcat",MakeConcat, true),
new LeftOperator("MakeDefaultIfEmpty", MakeDefaultIfEmpty, true),
new LeftOperator("MakeDistinct", MakeDistinct, false),
new LeftOperator("MakeExcept", MakeExcept, false),
new LeftOperator("MakeGroupBy", MakeGroupBy, false),
new LeftOperator("MakeGroupJoin", MakeGroupJoin, false),
new LeftOperator("MakeIntersect", MakeIntersect, false),
new LeftOperator("MakeJoin", MakeJoin, false),
new LeftOperator("MakeOfType", MakeOfType, true),
new LeftOperator("MakeOrderBy", MakeOrderBy, true),
new LeftOperator("MakeOrderByThenBy", MakeOrderByThenBy, true),
new LeftOperator("MakeReverse", MakeReverse, true),
new LeftOperator("MakeSelect", MakeSelect, true),
new LeftOperator("MakeSelectMany", MakeSelectMany, false),
new LeftOperator("MakeSkip", MakeSkip, true),
new LeftOperator("MakeSkipWhile", MakeSkipWhile, true),
new LeftOperator("MakeSkipWhileIndexed", MakeSkipWhileIndexed, true),
new LeftOperator("MakeTakeWhile", MakeTakeWhile, true),
new LeftOperator("MakeTakeWhileIndexed", MakeTakeWhileIndexed, true),
new LeftOperator("MakeUnion", MakeUnion, false),
new LeftOperator("MakeWhere", MakeWhere, true),
new LeftOperator("MakeWhereIndexed", MakeWhereIndexed, true),
new LeftOperator("MakeZip", MakeZip, true)};
TestTracker result = new TestTracker();
List<Exception> all_ex = new List<Exception>();
foreach (bool orderPreserved in new bool[] { true, false })
{
foreach (LeftOperator leftOp in leftOps)
{
String operatorName = leftOp.OperatorName;
Console.WriteLine("Left Operator={0}, Options={1}", operatorName, orderPreserved);
ParallelQuery<int> q = leftOp.LeftOperatorFactory(orderPreserved);
try
{
RunAllTests(result, q, orderPreserved, operatorName, leftOp.OrderDefined);
}
catch (Exception ex)
{
all_ex.Add(ex);
}
}
}
if (all_ex.Count > 0)
{
throw new AggregateException(all_ex);
}
}
private static void RunAllTests(
TestTracker result, ParallelQuery<int> q, bool orderPreserved,
string leftOpName, bool leftOrderDefined)
{
LogTestRun(leftOpName, "All1", orderPreserved);
result.MustEqual(
q.All(i => i > 100),
q.ToArray().Any(i => i > 100));
LogTestRun(leftOpName, "All2", orderPreserved);
result.MustEqual(
q.All(i => i == 75),
q.ToArray().All(i => i == 75));
LogTestRun(leftOpName, "Any1", orderPreserved);
result.MustEqual(
q.Any(i => i > 100),
q.ToArray().Any(i => i > 100));
LogTestRun(leftOpName, "Any2", orderPreserved);
result.MustEqual(
q.Any(i => i == 75),
q.ToArray().Any(i => i == 75));
LogTestRun(leftOpName, "Concat", orderPreserved);
result.MustSequenceEqual(
q.Concat(q).Concat(new int[] { 1, 2, 3 }.AsParallel()),
q.Reverse().Reverse().ToArray().Concat(q.Reverse().Reverse()).Concat(new int[] { 1, 2, 3 }),
leftOrderDefined && orderPreserved);
LogTestRun(leftOpName, "DefaultIfEmpty", orderPreserved);
result.MustSequenceEqual(
q.DefaultIfEmpty(),
q.ToArray().DefaultIfEmpty(), orderPreserved && leftOrderDefined);
LogTestRun(leftOpName, "ElementAt", orderPreserved);
IEnumerable<int> q2 = q.ToArray();
int count1 = q.Count(), count2 = q2.Count();
List<int> list1 = new List<int>();
List<int> list2 = new List<int>();
for (int i = 0; i < count1; i++) list1.Add(q.ElementAt(i));
for (int i = 0; i < count2; i++) list2.Add(q2.ElementAt(i));
result.MustSequenceEqual(list1, list2, leftOrderDefined);
LogTestRun(leftOpName, "Except", orderPreserved);
result.MustSequenceEqual(
q.Except(Enumerable.Range(90, 50).AsParallel()),
q.ToArray().Except(Enumerable.Range(90, 50)),
false);
LogTestRun(leftOpName, "First", orderPreserved);
CheckFirstOrLast(
result,
q.First(),
q.ToArray().First(),
leftOrderDefined);
LogTestRun(leftOpName, "GroupBy", orderPreserved);
result.MustGroupByEqual(
q.GroupBy(i => i % 5, (i, e) => new Pair<int, IEnumerable<int>>(i, e)),
q.ToArray().GroupBy(i => i % 5, (i, e) => new Pair<int, IEnumerable<int>>(i, e)));
LogTestRun(leftOpName, "GroupJoin", orderPreserved);
result.MustSequenceEqual(
q.GroupJoin(q, i => i, i => i, (i, e) => e.FirstOrDefault()),
q.ToArray().GroupJoin(q.ToArray(), i => i, i => i, (i, e) => e.FirstOrDefault()),
false);
LogTestRun(leftOpName, "Intersect", orderPreserved);
result.MustSequenceEqual(
q.Intersect(Enumerable.Range(90, 50).AsParallel()),
q.ToArray().Intersect(Enumerable.Range(90, 50)),
false);
LogTestRun(leftOpName, "Join1", orderPreserved);
result.MustSequenceEqual(
q.Join((new int[] { 1, 1, 2, 3, 3 }).AsParallel(), i => i, i => i, (i, j) => i + j),
q.ToArray().Join(new int[] { 1, 1, 2, 3, 3 }, i => i, i => i, (i, j) => i + j),
false);
LogTestRun(leftOpName, "Join2", orderPreserved);
result.MustSequenceEqual(
q.Join((new int[] { 1, 1, 100, 3, 3 }).AsParallel(), i => new String('a', i), i => new String('a', i), (i, j) => i + j),
q.ToArray().Join(new int[] { 1, 1, 100, 3, 3 }, i => new String('a', i), i => new String('a', i), (i, j) => i + j),
false);
LogTestRun(leftOpName, "Last", orderPreserved);
CheckFirstOrLast(
result,
q.Last(),
q.ToArray().Last(),
leftOrderDefined);
LogTestRun(leftOpName, "Min", orderPreserved);
CheckFirstOrLast(
result,
q.Min(),
q.ToArray().Min(),
leftOrderDefined);
LogTestRun(leftOpName, "Max", orderPreserved);
CheckFirstOrLast(
result,
q.Min(),
q.ToArray().Min(),
leftOrderDefined);
LogTestRun(leftOpName, "OrderBy-ThenBy", orderPreserved);
result.MustSequenceEqual(
q.Concat(q).OrderBy(i => i % 5).ThenBy(i => -i),
q.ToArray().Concat(q).OrderBy(i => i % 5).ThenBy(i => -i),
true);
LogTestRun(leftOpName, "OrderByDescending-ThenByDescending", orderPreserved);
result.MustSequenceEqual(
q.Concat(q).OrderByDescending(i => i % 5).ThenByDescending(i => -i),
q.ToArray().Concat(q).OrderByDescending(i => i % 5).ThenByDescending(i => -i),
true);
LogTestRun(leftOpName, "Reverse", orderPreserved);
result.MustSequenceEqual(
q.Concat(q).Reverse(),
q.ToArray().Concat(q).Reverse(),
orderPreserved && leftOrderDefined);
LogTestRun(leftOpName, "Select", orderPreserved);
result.MustSequenceEqual(
q.Select(i => 5 * i - 17),
q.ToArray().Select(i => 5 * i - 17),
orderPreserved && leftOrderDefined);
LogTestRun(leftOpName, "SelectMany", orderPreserved);
result.MustSequenceEqual(
q.SelectMany(i => new int[] { 1, 2, 3 }, (i, j) => i + 100 * j),
q.ToArray().SelectMany(i => new int[] { 1, 2, 3 }, (i, j) => i + 100 * j),
false);
LogTestRun(leftOpName, "SequenceEqual", orderPreserved);
if (orderPreserved && leftOrderDefined)
{
result.MustEqual(q.SequenceEqual(q), true);
}
else
{
// We don't check the return value as it can be either true or false
q.SequenceEqual(q);
}
LogTestRun(leftOpName, "Skip", orderPreserved);
CheckTakeSkip(
result,
q.Skip(10),
q.ToArray().Skip(10),
leftOrderDefined && orderPreserved);
LogTestRun(leftOpName, "SkipWhile", orderPreserved);
CheckTakeSkip(
result,
q.SkipWhile(i => i < 30),
q.ToArray().SkipWhile(i => i < 30),
leftOrderDefined && orderPreserved);
LogTestRun(leftOpName, "SkipWhileIndexed", orderPreserved);
CheckTakeSkip(
result,
q.SkipWhile((i, j) => j < 30),
q.ToArray().SkipWhile((i, j) => j < 30),
leftOrderDefined && orderPreserved);
LogTestRun(leftOpName, "Take", orderPreserved);
CheckTakeSkip(
result,
q.Take(10),
q.ToArray().Take(10),
leftOrderDefined && orderPreserved);
LogTestRun(leftOpName, "TakeWhile", orderPreserved);
CheckTakeSkip(
result,
q.TakeWhile(i => i < 30),
q.ToArray().TakeWhile(i => i < 30),
leftOrderDefined && orderPreserved);
LogTestRun(leftOpName, "TakeWhileIndexed", orderPreserved);
CheckTakeSkip(
result,
q.TakeWhile((i, j) => j < 30),
q.ToArray().TakeWhile((i, j) => j < 30),
leftOrderDefined && orderPreserved);
LogTestRun(leftOpName, "Union", orderPreserved);
result.MustSequenceEqual(
q.Union(Enumerable.Range(90, 50).AsParallel()),
q.ToArray().Union(Enumerable.Range(90, 50)),
false);
LogTestRun(leftOpName, "Where", orderPreserved);
result.MustSequenceEqual(
q.Where(i => i < 20 || i > 80),
q.ToArray().Where(i => i < 20 || i > 80),
orderPreserved && leftOrderDefined);
LogTestRun(leftOpName, "Zip", orderPreserved);
IEnumerable<KeyValuePair<int, int>> zipQ = q.Zip(q, (i, j) => new KeyValuePair<int, int>(i, j));
result.MustSequenceEqual(
zipQ.Select(p => p.Key),
q.Reverse().Reverse().ToArray(),
orderPreserved && leftOrderDefined);
result.MustSequenceEqual(
zipQ.Select(p => p.Value),
q.Reverse().Reverse().ToArray(),
orderPreserved && leftOrderDefined);
}
#region Helper Classes
private delegate ParallelQuery<int> LeftOperatorFactory(bool orderPreserved);
private class LeftOperator
{
private LeftOperatorFactory _leftOperatorFactory;
private bool _orderWellDefined;
public LeftOperator(string name, LeftOperatorFactory leftOperatorFactory, bool orderWellDefined)
{
OperatorName = name;
_leftOperatorFactory = leftOperatorFactory;
_orderWellDefined = orderWellDefined;
//if (leftOperatorFactory.Method.Name.Substring(0, 4) != "Make")
//{
// throw new ArgumentException("LeftOperatorFactory method name must start with 'Make'");
//}
}
public LeftOperatorFactory LeftOperatorFactory
{
get { return _leftOperatorFactory; }
}
public bool OrderDefined
{
get { return _orderWellDefined; }
}
public string OperatorName
{
get;
set;
}
}
// Helper class to track whether the test passed or failed.
private class TestTracker
{
// Unfortunately, since MustEqual compares its parameters with an == operator, we can't have one
// generic method (C# compiler does not allow == operator to be applied to a generic type parameter
// that may be a value type for which == is not defined), but instead we need a separate MustEqual
// method for each type of parameters.
public void MustEqual(int a, int b)
{
if (a != b) AreNotEqual(a, b);
}
public void MustEqual(bool a, bool b)
{
if (a != b) AreNotEqual(a, b);
}
private void AreNotEqual<T>(T a, T b)
{
Assert.True(false, string.Format(" >> Failed. Expect: {0} Got: {1}", a, b));
}
internal void MustSequenceEqual(IEnumerable<int> a, IEnumerable<int> b, bool orderPreserved)
{
if (!orderPreserved) { a = a.OrderBy(i => i); b = b.OrderBy(i => i); }
int[] aa = a.ToArray(), ba = b.ToArray();
if (!aa.SequenceEqual(ba))
{
Assert.True(false, string.Format(" >> Failed. Sequence 1: {0} AND Sequence 2: {1}", EnumerableToString(aa), EnumerableToString(ba)));
}
}
private string EnumerableToString<T>(IEnumerable<T> e)
{
return String.Join(",", e.Select(x => x.ToString()).ToArray());
}
// Helper method to verify the output of a GroupBy operator
internal void MustGroupByEqual(IEnumerable<Pair<int, IEnumerable<int>>> e1, IEnumerable<Pair<int, IEnumerable<int>>> e2)
{
var es = new IEnumerable<Pair<int, IEnumerable<int>>>[] { e1, e2 };
var vals = new Dictionary<int, IEnumerable<int>>[2];
for (int i = 0; i < 2; i++)
{
vals[i] = new Dictionary<int, IEnumerable<int>>();
foreach (var group in es[i])
{
vals[i].Add(group.First, group.Second.OrderBy(x => x));
}
}
for (int i = 0; i < 2; i++)
{
foreach (var key in vals[i].Keys)
{
if (!vals[1 - i].ContainsKey(key) || !vals[1 - i][key].SequenceEqual(vals[i][key]))
{
Assert.True(false, string.Format(" >> Failed. GroupBy results differ."));
}
}
}
}
}
//-----------------------------------------------------------------------------------
// A pair just wraps two bits of data into a single addressable unit. This is a
// value type to ensure it remains very lightweight, since it is frequently used
// with other primitive data types as well.
//
// Note: this class is another copy of the Pair<T, U> class defined in CommonDataTypes.cs.
// For now, we have a copy of the class here, because we can't import the System.Linq.Parallel
// namespace.
//
private struct Pair<T, U>
{
// The first and second bits of data.
internal T m_first;
internal U m_second;
//-----------------------------------------------------------------------------------
// A simple constructor that initializes the first/second fields.
//
public Pair(T first, U second)
{
m_first = first;
m_second = second;
}
//-----------------------------------------------------------------------------------
// Accessors for the left and right data.
//
public T First
{
get { return m_first; }
set { m_first = value; }
}
public U Second
{
get { return m_second; }
set { m_second = value; }
}
}
#endregion
#region Helper Methods
//
// Left operator factory methods
//
internal static ParallelQuery<int> MakeCast(bool orderPreserved)
{
object[] a = Enumerable.Range(0, 100).Cast<object>().ToArray();
ParallelQuery<object> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Cast<int>();
}
internal static ParallelQuery<int> MakeConcat(bool orderPreserved)
{
int[] a = Enumerable.Range(1, 35).ToArray();
int[] b = Enumerable.Range(36, 65).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Concat(b.AsParallel());
}
internal static ParallelQuery<int> MakeDefaultIfEmpty(bool orderPreserved)
{
int[] a = Enumerable.Range(1, 100).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.DefaultIfEmpty();
}
internal static ParallelQuery<int> MakeDistinct(bool orderPreserved)
{
List<int> list = new List<int>();
for (int i = 1; i <= 100; i++) { list.Add(i); list.Add(i); list.Add(i); }
int[] a = list.Concat(list).Concat(list).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Distinct();
}
internal static ParallelQuery<int> MakeExcept(bool orderPreserved)
{
int[] a = Enumerable.Range(-5, 110).ToArray();
int[] b = { -100, -50, -5, -4, -3, -2, -1, 101, 102, 103, 104, 105, 106, 180 };
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Except(b.AsParallel());
}
internal static ParallelQuery<int> MakeGroupBy(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 1000).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.GroupBy(i => i % 100, i => i).Select(g => g.Key);
}
internal static ParallelQuery<int> MakeGroupJoin(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 100).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.GroupJoin(a.AsParallel(), i => i, i => i, (i, e) => e.FirstOrDefault());
}
internal static ParallelQuery<int> MakeIntersect(bool orderPreserved)
{
int[] a = Enumerable.Range(-99, 200).ToArray();
int[] b = Enumerable.Range(0, 200).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Intersect(b.AsParallel());
}
internal static ParallelQuery<int> MakeJoin(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 100).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Join(a.AsParallel(), i => i, i => i, (i, j) => i);
}
internal static ParallelQuery<int> MakeOfType(bool orderPreserved)
{
object[] a = Enumerable.Range(0, 50)
.Cast<object>()
.Concat(Enumerable.Repeat<object>(null, 50))
.Concat(Enumerable.Range(50, 50).Cast<object>()).ToArray();
ParallelQuery<object> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.OfType<int>();
}
internal static ParallelQuery<int> MakeOrderBy(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 100).Reverse().ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.OrderBy(i => i);
}
internal static ParallelQuery<int> MakeOrderByThenBy(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 100).Reverse().ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.OrderBy(i => i % 5).ThenBy(i => -i);
}
internal static ParallelQuery<int> MakeReverse(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 100).Reverse().ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Reverse();
}
internal static ParallelQuery<int> MakeSelect(bool orderPreserved)
{
int[] a = Enumerable.Range(-99, 100).Reverse().ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Select(i => -i);
}
internal static ParallelQuery<int> MakeSelectMany(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 10).ToArray();
int[] b = Enumerable.Range(0, 10).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.SelectMany(i => b, (i, j) => (10 * i + j));
}
internal static ParallelQuery<int> MakeSkip(bool orderPreserved)
{
int[] a = Enumerable.Range(-10, 110).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Skip(10);
}
internal static ParallelQuery<int> MakeSkipWhile(bool orderPreserved)
{
int[] a = Enumerable.Range(-10, 110).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.SkipWhile(i => i < 0);
}
internal static ParallelQuery<int> MakeSkipWhileIndexed(bool orderPreserved)
{
int[] a = Enumerable.Range(-10, 110).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.SkipWhile((i, j) => j < 10);
}
internal static ParallelQuery<int> MakeTake(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 110).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Take(100);
}
internal static ParallelQuery<int> MakeTakeWhile(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 110).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.TakeWhile(i => i < 100);
}
internal static ParallelQuery<int> MakeTakeWhileIndexed(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 110).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.TakeWhile((i, j) => j < 100);
}
internal static ParallelQuery<int> MakeUnion(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 80).ToArray();
int[] b = Enumerable.Range(20, 80).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Union(b.AsParallel());
}
internal static ParallelQuery<int> MakeWhere(bool orderPreserved)
{
int[] a = Enumerable.Range(-10, 120).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Where(i => (i >= 0 && i < 100));
}
internal static ParallelQuery<int> MakeWhereIndexed(bool orderPreserved)
{
int[] a = Enumerable.Range(-10, 120).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Where((i, j) => (j >= 10 && j < 110));
}
internal static ParallelQuery<int> MakeZip(bool orderPreserved)
{
int[] a = Enumerable.Range(0, 100).ToArray();
ParallelQuery<int> ipe = a.AsParallel();
if (orderPreserved) ipe = ipe.AsOrdered();
return ipe.Zip(a.AsParallel(), (i, j) => (i + j) / 2);
}
private static void CheckFirstOrLast(TestTracker result, int a, int b, bool leftOrderDefined)
{
if (leftOrderDefined) result.MustEqual(a, b);
}
private static void CheckTakeSkip(TestTracker result, IEnumerable<int> q1, IEnumerable<int> q2, bool leftOrderDefined)
{
if (leftOrderDefined)
{
result.MustSequenceEqual(q1, q2, true);
}
else
{
// Just run the queries, but don't compare the answer because it is not unique.
foreach (var x in q1) { }
foreach (var x in q2) { }
}
}
private static void LogTestRun(string leftOpName, string rightOpName, bool orderPreserved)
{
Console.WriteLine(" Running {0}/{1}, Order Preserved={2}", leftOpName, rightOpName, orderPreserved);
}
#endregion
}
}
| |
/*
"Miscellaneous Utility Library" Software Licence
Version 1.0
Copyright (c) 2004-2008 Jon Skeet and Marc Gravell.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if
any, must include the following acknowledgment:
"This product includes software developed by Jon Skeet
and Marc Gravell. Contact skeet@pobox.com, or see
http://www.pobox.com/~skeet/)."
Alternately, this acknowledgment may appear in the software itself,
if and wherever such third-party acknowledgments normally appear.
4. The name "Miscellaneous Utility Library" must not be used to endorse
or promote products derived from this software without prior written
permission. For written permission, please contact skeet@pobox.com.
5. Products derived from this software may not be called
"Miscellaneous Utility Library", nor may "Miscellaneous Utility Library"
appear in their name, without prior written permission of Jon Skeet.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
namespace MiscUtil.Conversion
{
/// <summary>
/// Equivalent of System.BitConverter, but with either endianness.
/// </summary>
public abstract class EndianBitConverter
{
#region Endianness of this converter
/// <summary>
/// Indicates the byte order ("endianess") in which data is converted using this class.
/// </summary>
/// <remarks>
/// Different computer architectures store data using different byte orders. "Big-endian"
/// means the most significant byte is on the left end of a word. "Little-endian" means the
/// most significant byte is on the right end of a word.
/// </remarks>
/// <returns>true if this converter is little-endian, false otherwise.</returns>
public abstract bool IsLittleEndian();
/// <summary>
/// Indicates the byte order ("endianess") in which data is converted using this class.
/// </summary>
public abstract Endianness Endianness { get; }
#endregion
#region Factory properties
static LittleEndianBitConverter little = new LittleEndianBitConverter();
/// <summary>
/// Returns a little-endian bit converter instance. The same instance is
/// always returned.
/// </summary>
public static LittleEndianBitConverter Little
{
get { return little; }
}
static BigEndianBitConverter big = new BigEndianBitConverter();
/// <summary>
/// Returns a big-endian bit converter instance. The same instance is
/// always returned.
/// </summary>
public static BigEndianBitConverter Big
{
get { return big; }
}
#endregion
#region Double/primitive conversions
/// <summary>
/// Converts the specified double-precision floating point number to a
/// 64-bit signed integer. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A 64-bit signed integer whose value is equivalent to value.</returns>
public long DoubleToInt64Bits(double value)
{
return BitConverter.DoubleToInt64Bits(value);
}
/// <summary>
/// Converts the specified 64-bit signed integer to a double-precision
/// floating point number. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A double-precision floating point number whose value is equivalent to value.</returns>
public double Int64BitsToDouble (long value)
{
return BitConverter.Int64BitsToDouble(value);
}
/// <summary>
/// Converts the specified single-precision floating point number to a
/// 32-bit signed integer. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A 32-bit signed integer whose value is equivalent to value.</returns>
public int SingleToInt32Bits(float value)
{
return new Int32SingleUnion(value).AsInt32;
}
/// <summary>
/// Converts the specified 32-bit signed integer to a single-precision floating point
/// number. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A single-precision floating point number whose value is equivalent to value.</returns>
public float Int32BitsToSingle (int value)
{
return new Int32SingleUnion(value).AsSingle;
}
#endregion
#region To(PrimitiveType) conversions
/// <summary>
/// Returns a Boolean value converted from one byte at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>true if the byte at startIndex in value is nonzero; otherwise, false.</returns>
public bool ToBoolean (byte[] value, int startIndex)
{
CheckByteArgument(value, startIndex, 1);
return BitConverter.ToBoolean(value, startIndex);
}
/// <summary>
/// Returns a Unicode character converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A character formed by two bytes beginning at startIndex.</returns>
public char ToChar (byte[] value, int startIndex)
{
return unchecked((char) (CheckedFromBytes(value, startIndex, 2)));
}
/// <summary>
/// Returns a double-precision floating point number converted from eight bytes
/// at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A double precision floating point number formed by eight bytes beginning at startIndex.</returns>
public double ToDouble (byte[] value, int startIndex)
{
return Int64BitsToDouble(ToInt64(value, startIndex));
}
/// <summary>
/// Returns a single-precision floating point number converted from four bytes
/// at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A single precision floating point number formed by four bytes beginning at startIndex.</returns>
public float ToSingle (byte[] value, int startIndex)
{
return Int32BitsToSingle(ToInt32(value, startIndex));
}
/// <summary>
/// Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit signed integer formed by two bytes beginning at startIndex.</returns>
public short ToInt16 (byte[] value, int startIndex)
{
return unchecked((short) (CheckedFromBytes(value, startIndex, 2)));
}
/// <summary>
/// Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit signed integer formed by four bytes beginning at startIndex.</returns>
public int ToInt32 (byte[] value, int startIndex)
{
return unchecked((int) (CheckedFromBytes(value, startIndex, 4)));
}
/// <summary>
/// Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit signed integer formed by eight bytes beginning at startIndex.</returns>
public long ToInt64 (byte[] value, int startIndex)
{
return CheckedFromBytes(value, startIndex, 8);
}
/// <summary>
/// Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit unsigned integer formed by two bytes beginning at startIndex.</returns>
public ushort ToUInt16 (byte[] value, int startIndex)
{
return unchecked((ushort) (CheckedFromBytes(value, startIndex, 2)));
}
/// <summary>
/// Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit unsigned integer formed by four bytes beginning at startIndex.</returns>
public uint ToUInt32 (byte[] value, int startIndex)
{
return unchecked((uint) (CheckedFromBytes(value, startIndex, 4)));
}
/// <summary>
/// Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit unsigned integer formed by eight bytes beginning at startIndex.</returns>
public ulong ToUInt64 (byte[] value, int startIndex)
{
return unchecked((ulong) (CheckedFromBytes(value, startIndex, 8)));
}
/// <summary>
/// Checks the given argument for validity.
/// </summary>
/// <param name="value">The byte array passed in</param>
/// <param name="startIndex">The start index passed in</param>
/// <param name="bytesRequired">The number of bytes required</param>
/// <exception cref="ArgumentNullException">value is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value minus bytesRequired.
/// </exception>
static void CheckByteArgument(byte[] value, int startIndex, int bytesRequired)
{
if (value==null)
{
throw new ArgumentNullException("value");
}
if (startIndex < 0 || startIndex > value.Length-bytesRequired)
{
throw new ArgumentOutOfRangeException("startIndex");
}
}
/// <summary>
/// Checks the arguments for validity before calling FromBytes
/// (which can therefore assume the arguments are valid).
/// </summary>
/// <param name="value">The bytes to convert after checking</param>
/// <param name="startIndex">The index of the first byte to convert</param>
/// <param name="bytesToConvert">The number of bytes to convert</param>
/// <returns></returns>
long CheckedFromBytes(byte[] value, int startIndex, int bytesToConvert)
{
CheckByteArgument(value, startIndex, bytesToConvert);
return FromBytes(value, startIndex, bytesToConvert);
}
/// <summary>
/// Convert the given number of bytes from the given array, from the given start
/// position, into a long, using the bytes as the least significant part of the long.
/// By the time this is called, the arguments have been checked for validity.
/// </summary>
/// <param name="value">The bytes to convert</param>
/// <param name="startIndex">The index of the first byte to convert</param>
/// <param name="bytesToConvert">The number of bytes to use in the conversion</param>
/// <returns>The converted number</returns>
protected abstract long FromBytes(byte[] value, int startIndex, int bytesToConvert);
#endregion
#region ToString conversions
/// <summary>
/// Returns a String converted from the elements of a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <remarks>All the elements of value are converted.</remarks>
/// <returns>
/// A String of hexadecimal pairs separated by hyphens, where each pair
/// represents the corresponding element in value; for example, "7F-2C-4A".
/// </returns>
public static string ToString(byte[] value)
{
return BitConverter.ToString(value);
}
/// <summary>
/// Returns a String converted from the elements of a byte array starting at a specified array position.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <remarks>The elements from array position startIndex to the end of the array are converted.</remarks>
/// <returns>
/// A String of hexadecimal pairs separated by hyphens, where each pair
/// represents the corresponding element in value; for example, "7F-2C-4A".
/// </returns>
public static string ToString(byte[] value, int startIndex)
{
return BitConverter.ToString(value, startIndex);
}
/// <summary>
/// Returns a String converted from a specified number of bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <param name="length">The number of bytes to convert.</param>
/// <remarks>The length elements from array position startIndex are converted.</remarks>
/// <returns>
/// A String of hexadecimal pairs separated by hyphens, where each pair
/// represents the corresponding element in value; for example, "7F-2C-4A".
/// </returns>
public static string ToString(byte[] value, int startIndex, int length)
{
return BitConverter.ToString(value, startIndex, length);
}
#endregion
#region Decimal conversions
/// <summary>
/// Returns a decimal value converted from sixteen bytes
/// at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A decimal formed by sixteen bytes beginning at startIndex.</returns>
public decimal ToDecimal (byte[] value, int startIndex)
{
// HACK: This always assumes four parts, each in their own endianness,
// starting with the first part at the start of the byte array.
// On the other hand, there's no real format specified...
int[] parts = new int[4];
for (int i=0; i < 4; i++)
{
parts[i] = ToInt32(value, startIndex+i*4);
}
return new Decimal(parts);
}
/// <summary>
/// Returns the specified decimal value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 16.</returns>
public byte[] GetBytes(decimal value)
{
byte[] bytes = new byte[16];
int[] parts = decimal.GetBits(value);
for (int i=0; i < 4; i++)
{
CopyBytesImpl(parts[i], 4, bytes, i*4);
}
return bytes;
}
/// <summary>
/// Copies the specified decimal value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">A character to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(decimal value, byte[] buffer, int index)
{
int[] parts = decimal.GetBits(value);
for (int i=0; i < 4; i++)
{
CopyBytesImpl(parts[i], 4, buffer, i*4+index);
}
}
#endregion
#region GetBytes conversions
/// <summary>
/// Returns an array with the given number of bytes formed
/// from the least significant bytes of the specified value.
/// This is used to implement the other GetBytes methods.
/// </summary>
/// <param name="value">The value to get bytes for</param>
/// <param name="bytes">The number of significant bytes to return</param>
byte[] GetBytes(long value, int bytes)
{
byte[] buffer = new byte[bytes];
CopyBytes(value, bytes, buffer, 0);
return buffer;
}
/// <summary>
/// Returns the specified Boolean value as an array of bytes.
/// </summary>
/// <param name="value">A Boolean value.</param>
/// <returns>An array of bytes with length 1.</returns>
public byte[] GetBytes(bool value)
{
return BitConverter.GetBytes(value);
}
/// <summary>
/// Returns the specified Unicode character value as an array of bytes.
/// </summary>
/// <param name="value">A character to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public byte[] GetBytes(char value)
{
return GetBytes(value, 2);
}
/// <summary>
/// Returns the specified double-precision floating point value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public byte[] GetBytes(double value)
{
return GetBytes(DoubleToInt64Bits(value), 8);
}
/// <summary>
/// Returns the specified 16-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public byte[] GetBytes(short value)
{
return GetBytes(value, 2);
}
/// <summary>
/// Returns the specified 32-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public byte[] GetBytes(int value)
{
return GetBytes(value, 4);
}
/// <summary>
/// Returns the specified 64-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public byte[] GetBytes(long value)
{
return GetBytes(value, 8);
}
/// <summary>
/// Returns the specified single-precision floating point value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public byte[] GetBytes(float value)
{
return GetBytes(SingleToInt32Bits(value), 4);
}
/// <summary>
/// Returns the specified 16-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public byte[] GetBytes(ushort value)
{
return GetBytes(value, 2);
}
/// <summary>
/// Returns the specified 32-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public byte[] GetBytes(uint value)
{
return GetBytes(value, 4);
}
/// <summary>
/// Returns the specified 64-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public byte[] GetBytes(ulong value)
{
return GetBytes(unchecked((long)value), 8);
}
#endregion
#region CopyBytes conversions
/// <summary>
/// Copies the given number of bytes from the least-specific
/// end of the specified value into the specified byte array, beginning
/// at the specified index.
/// This is used to implement the other CopyBytes methods.
/// </summary>
/// <param name="value">The value to copy bytes for</param>
/// <param name="bytes">The number of significant bytes to copy</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
void CopyBytes(long value, int bytes, byte[] buffer, int index)
{
if (buffer==null)
{
throw new ArgumentNullException("buffer", "Byte array must not be null");
}
if (buffer.Length < index+bytes)
{
throw new ArgumentOutOfRangeException("Buffer not big enough for value");
}
CopyBytesImpl(value, bytes, buffer, index);
}
/// <summary>
/// Copies the given number of bytes from the least-specific
/// end of the specified value into the specified byte array, beginning
/// at the specified index.
/// This must be implemented in concrete derived classes, but the implementation
/// may assume that the value will fit into the buffer.
/// </summary>
/// <param name="value">The value to copy bytes for</param>
/// <param name="bytes">The number of significant bytes to copy</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
protected abstract void CopyBytesImpl(long value, int bytes, byte[] buffer, int index);
/// <summary>
/// Copies the specified Boolean value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">A Boolean value.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(bool value, byte[] buffer, int index)
{
CopyBytes(value ? 1 : 0, 1, buffer, index);
}
/// <summary>
/// Copies the specified Unicode character value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">A character to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(char value, byte[] buffer, int index)
{
CopyBytes(value, 2, buffer, index);
}
/// <summary>
/// Copies the specified double-precision floating point value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(double value, byte[] buffer, int index)
{
CopyBytes(DoubleToInt64Bits(value), 8, buffer, index);
}
/// <summary>
/// Copies the specified 16-bit signed integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(short value, byte[] buffer, int index)
{
CopyBytes(value, 2, buffer, index);
}
/// <summary>
/// Copies the specified 32-bit signed integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(int value, byte[] buffer, int index)
{
CopyBytes(value, 4, buffer, index);
}
/// <summary>
/// Copies the specified 64-bit signed integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(long value, byte[] buffer, int index)
{
CopyBytes(value, 8, buffer, index);
}
/// <summary>
/// Copies the specified single-precision floating point value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(float value, byte[] buffer, int index)
{
CopyBytes(SingleToInt32Bits(value), 4, buffer, index);
}
/// <summary>
/// Copies the specified 16-bit unsigned integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(ushort value, byte[] buffer, int index)
{
CopyBytes(value, 2, buffer, index);
}
/// <summary>
/// Copies the specified 32-bit unsigned integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(uint value, byte[] buffer, int index)
{
CopyBytes(value, 4, buffer, index);
}
/// <summary>
/// Copies the specified 64-bit unsigned integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(ulong value, byte[] buffer, int index)
{
CopyBytes(unchecked((long)value), 8, buffer, index);
}
#endregion
#region Private struct used for Single/Int32 conversions
/// <summary>
/// Union used solely for the equivalent of DoubleToInt64Bits and vice versa.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
struct Int32SingleUnion
{
/// <summary>
/// Int32 version of the value.
/// </summary>
[FieldOffset(0)]
int i;
/// <summary>
/// Single version of the value.
/// </summary>
[FieldOffset(0)]
float f;
/// <summary>
/// Creates an instance representing the given integer.
/// </summary>
/// <param name="i">The integer value of the new instance.</param>
internal Int32SingleUnion(int i)
{
this.f = 0; // Just to keep the compiler happy
this.i = i;
}
/// <summary>
/// Creates an instance representing the given floating point number.
/// </summary>
/// <param name="f">The floating point value of the new instance.</param>
internal Int32SingleUnion(float f)
{
this.i = 0; // Just to keep the compiler happy
this.f = f;
}
/// <summary>
/// Returns the value of the instance as an integer.
/// </summary>
internal int AsInt32
{
get { return i; }
}
/// <summary>
/// Returns the value of the instance as a floating point number.
/// </summary>
internal float AsSingle
{
get { return f; }
}
}
#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.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Globalization
{
public partial class CompareInfo
{
internal static unsafe int InvariantIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0 && startIndex < source.Length);
fixed (char* pSource = source) fixed (char* pValue = value)
{
char* pSrc = &pSource[startIndex];
int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, fromBeginning: true);
if (index >= 0)
{
return index + startIndex;
}
return -1;
}
}
internal static unsafe int InvariantIndexOf(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase, bool fromBeginning = true)
{
Debug.Assert(source.Length != 0);
Debug.Assert(value.Length != 0);
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pValue = &MemoryMarshal.GetReference(value))
{
return InvariantFindString(pSource, source.Length, pValue, value.Length, ignoreCase, fromBeginning);
}
}
internal static unsafe int InvariantLastIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0 && startIndex < source.Length);
fixed (char* pSource = source) fixed (char* pValue = value)
{
char* pSrc = &pSource[startIndex - count + 1];
int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, fromBeginning: false);
if (index >= 0)
{
return index + startIndex - count + 1;
}
return -1;
}
}
private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool fromBeginning)
{
int ctrSource = 0; // index value into source
int ctrValue = 0; // index value into value
char sourceChar; // Character for case lookup in source
char valueChar; // Character for case lookup in value
int lastSourceStart;
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(sourceCount >= 0);
Debug.Assert(valueCount >= 0);
if (valueCount == 0)
{
return fromBeginning ? 0 : sourceCount - 1;
}
if (sourceCount < valueCount)
{
return -1;
}
if (fromBeginning)
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = InvariantToUpper(value[0]);
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = InvariantToUpper(source[ctrSource]);
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
valueChar = InvariantToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
else
{
char firstValueChar = value[0];
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = source[ctrSource];
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
else
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = InvariantToUpper(value[0]);
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = InvariantToUpper(source[ctrSource]);
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
valueChar = InvariantToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
else
{
char firstValueChar = value[0];
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = source[ctrSource];
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
return -1;
}
private static char InvariantToUpper(char c)
{
return (uint)(c - 'a') <= (uint)('z' - 'a') ? (char)(c - 0x20) : c;
}
private unsafe SortKey InvariantCreateSortKey(string source, CompareOptions options)
{
if (source == null) { throw new ArgumentNullException(nameof(source)); }
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte[] keyData;
if (source.Length == 0)
{
keyData = Array.Empty<byte>();
}
else
{
// In the invariant mode, all string comparisons are done as ordinal so when generating the sort keys we generate it according to this fact
keyData = new byte[source.Length * sizeof(char)];
fixed (char* pChar = source) fixed (byte* pByte = keyData)
{
if ((options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0)
{
short* pShort = (short*)pByte;
for (int i = 0; i < source.Length; i++)
{
pShort[i] = (short)InvariantToUpper(source[i]);
}
}
else
{
Buffer.MemoryCopy(pChar, pByte, keyData.Length, keyData.Length);
}
}
}
return new SortKey(Name, source, options, keyData);
}
}
}
| |
using System.Security;
using System;
using System.IO;
using TestLibrary;
/// <summary>
/// System.IO.Path.GetDirectoryName(string)
/// </summary>
public class PathGetDirectoryName
{
private const int c_MAX_PATH_LEN = 256;
public static int Main()
{
PathGetDirectoryName pGetDirectoryname = new PathGetDirectoryName();
TestLibrary.TestFramework.BeginTestCase("for Method:System.IO.Path.GetDirectoryName(string)");
if (pGetDirectoryname.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTesting
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1:the source path is a file name.";
const string c_TEST_ID = "P001";
string sourcePath = @"C:" + Env.FileSeperator + "mydir" + Env.FileSeperator + "myfolder" + Env.FileSeperator + "test.txt";
string directoryName = @"C:" + Env.FileSeperator + "mydir" + Env.FileSeperator + "myfolder";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string resDN = Path.GetDirectoryName(sourcePath);
if (resDN != directoryName)
{
string errorDesc = "Value is not " + directoryName + " as expected: Actual(" + resDN + ")";
errorDesc += GetDataString(sourcePath);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2:the source Path is a root directory";
const string c_TEST_ID = "P002";
string sourcePath = @"C:\";
string directoryName = Utilities.IsWindows?null:"C:";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string resDN = Path.GetDirectoryName(sourcePath);
if (resDN != directoryName)
{
string errorDesc = "Value is not " + directoryName + " as expected: Actual(" + resDN + ")";
errorDesc += GetDataString(sourcePath);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: source Path does not contain directory information";
const string c_TEST_ID = "P003";
string sourcePath = "mydiymyfolder.mydoc";
string directoryName = String.Empty;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string resDN = Path.GetDirectoryName(sourcePath);
if (resDN != directoryName)
{
string errorDesc = "Value is not empty string as expected: Actual(" + resDN + ")";
errorDesc += GetDataString(sourcePath);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4:the source Path is a null reference";
const string c_TEST_ID = "P004";
string sourcePath =null;
string directoryName = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string resDN = Path.GetDirectoryName(sourcePath);
if (resDN != directoryName)
{
string errorDesc = "Value is not " + directoryName + " as expected: Actual(" + resDN + ")";
errorDesc += GetDataString(sourcePath);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5:the source Path is a null reference";
const string c_TEST_ID = "P005";
string sourcePath = null;
string directoryName = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string resDN = Path.GetDirectoryName(sourcePath);
if (resDN != directoryName)
{
string errorDesc = "Value is not null as expected: Actual(" + resDN + ")";
errorDesc += GetDataString(sourcePath);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
#endregion
#region NagativeTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: the source path contains invalid characters";
const string c_TEST_ID = "N001";
string sourcePath = "C:\\mydir\\myfolder>\\test.txt";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Path.GetDirectoryName(sourcePath);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected." + GetDataString(sourcePath));
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: the source path contains only white spaces";
const string c_TEST_ID = "N002";
string sourcePath = " ";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Path.GetDirectoryName(sourcePath);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected" + GetDataString(sourcePath));
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: the source path contains a wildcard character";
const string c_TEST_ID = "N003";
string sourcePath = @"C:\<\myfolder\test.txt";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Path.GetDirectoryName(sourcePath);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected" + GetDataString(sourcePath));
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: the source path is longer than the system-defined maximum length ";
const string c_TEST_ID = "N004";
string strMaxLength = TestLibrary.Generator.GetString(-55, true, c_MAX_PATH_LEN, c_MAX_PATH_LEN);
string sourcePath = "C:\\"+strMaxLength+"\\test.txt";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Path.GetDirectoryName(sourcePath);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "PathTooLongException is not thrown as expected" + GetDataString(sourcePath));
retVal = false;
}
catch (PathTooLongException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(sourcePath));
retVal = false;
}
return retVal;
}
#endregion
#region Helper methords for testing
private string GetDataString(string path)
{
string str, strPath1;
if (null == path)
{
strPath1 = "null";
}
else if ("" == path)
{
strPath1 = "empty";
}
else
{
strPath1 = path;
}
str = string.Format("\n[souce Path value]\n \"{0}\"", strPath1);
return str;
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using Xunit;
namespace System.ServiceModel.Syndication.Tests
{
public class Rss20ItemFormatterTests
{
[Fact]
public void Ctor_Default()
{
var formatter = new Formatter();
Assert.Null(formatter.Item);
Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Rss20", formatter.Version);
}
[Fact]
public void Ctor_GenericDefault()
{
var formatter = new GenericFormatter<SyndicationItem>();
Assert.Null(formatter.Item);
Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Rss20", formatter.Version);
}
[Fact]
public void Ctor_SyndicationItem()
{
var item = new SyndicationItem();
var formatter = new Formatter(item);
Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint);
Assert.Same(item, formatter.Item);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Rss20", formatter.Version);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Ctor_SyndicationItem_Bool(bool serializeExtensionsAsAtom)
{
var item = new SyndicationItem();
var formatter = new Formatter(item, serializeExtensionsAsAtom);
Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint);
Assert.Same(item, formatter.Item);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Rss20", formatter.Version);
}
[Fact]
public void Ctor_GenericSyndicationItem()
{
var item = new SyndicationItem();
var formatter = new GenericFormatter<SyndicationItem>(item);
Assert.Same(item, formatter.Item);
Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Rss20", formatter.Version);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void Ctor_GenericSyndicationItem_Bool(bool serializeExtensionsAsAtom)
{
var item = new SyndicationItem();
var formatter = new GenericFormatter<SyndicationItem>(item, serializeExtensionsAsAtom);
Assert.Equal(typeof(SyndicationItem), formatter.ItemTypeEntryPoint);
Assert.Same(item, formatter.Item);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Rss20", formatter.Version);
}
[Fact]
public void Ctor_NullItemToWrite_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("itemToWrite", () => new Rss20ItemFormatter((SyndicationItem)null));
AssertExtensions.Throws<ArgumentNullException>("itemToWrite", () => new Rss20ItemFormatter<SyndicationItem>(null));
}
[Theory]
[InlineData(typeof(SyndicationItem))]
[InlineData(typeof(SyndicationItemSubclass))]
public void Ctor_Type(Type itemTypeToCreate)
{
var formatter = new Formatter(itemTypeToCreate);
Assert.Null(formatter.Item);
Assert.Equal(itemTypeToCreate, formatter.ItemTypeEntryPoint);
Assert.True(formatter.PreserveAttributeExtensions);
Assert.True(formatter.PreserveElementExtensions);
Assert.Equal("Rss20", formatter.Version);
}
[Fact]
public void Ctor_NullItemTypeToCreate_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("itemTypeToCreate", () => new Rss20ItemFormatter((Type)null));
}
[Fact]
public void Ctor_InvalidItemTypeToCreate_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("itemTypeToCreate", () => new Rss20ItemFormatter(typeof(int)));
}
[Fact]
public void GetSchema_Invoke_ReturnsNull()
{
IXmlSerializable formatter = new Rss20ItemFormatter();
Assert.Null(formatter.GetSchema());
}
public static IEnumerable<object[]> WriteTo_TestData()
{
yield return new object[]
{
new SyndicationItem(),
true,
@"<item>
<description />
</item>"
};
yield return new object[]
{
new SyndicationItem(),
false,
@"<item>
<description />
</item>"
};
// Full item.
SyndicationPerson CreatePerson(string prefix)
{
var person = new SyndicationPerson();
person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name1"), null);
person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name2", prefix + "_namespace"), "");
person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name3", prefix + "_namespace"), prefix + "_value");
person.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name4", "xmlns"), "");
person.ElementExtensions.Add(new ExtensionObject { Value = 10 });
person.Email = prefix + "_email";
person.Name = prefix + "_name";
person.Uri = prefix + "_uri";
return person;
}
TextSyndicationContent CreateContent(string prefix)
{
var content = new TextSyndicationContent(prefix + "_title", TextSyndicationContentKind.Html);
content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name1"), null);
content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name2", prefix + "_namespace"), "");
content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name3", prefix + "_namespace"), prefix + "_value");
content.AttributeExtensions.Add(new XmlQualifiedName(prefix + "_name4", "xmlns"), "");
return content;
}
var fullSyndicationCategory = new SyndicationCategory();
fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name1"), null);
fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name2", "category_namespace"), "");
fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name3", "category_namespace"), "category_value");
fullSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("category_name4", "xmlns"), "");
fullSyndicationCategory.ElementExtensions.Add(new ExtensionObject { Value = 10 });
fullSyndicationCategory.Label = "category_label";
fullSyndicationCategory.Name = "category_name";
fullSyndicationCategory.Scheme = "category_scheme";
var attributeSyndicationCategory = new SyndicationCategory();
attributeSyndicationCategory.AttributeExtensions.Add(new XmlQualifiedName("term"), "term_value");
attributeSyndicationCategory.Name = "name";
var fullSyndicationLink = new SyndicationLink();
fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name1"), null);
fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name2", "link_namespace"), "");
fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name3", "link_namespace"), "link_value");
fullSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("link_name4", "xmlns"), "");
fullSyndicationLink.BaseUri = new Uri("http://link_url.com");
fullSyndicationLink.ElementExtensions.Add(new ExtensionObject { Value = 10 });
fullSyndicationLink.Length = 10;
fullSyndicationLink.MediaType = "link_mediaType";
fullSyndicationLink.RelationshipType = "link_relationshipType";
fullSyndicationLink.Title = "link_title";
fullSyndicationLink.Uri = new Uri("http://link_uri.com");
var fullEnclosureLink = new SyndicationLink();
fullEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("enclosure_name1"), null);
fullEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("enclosure_name2", "enclosure_namespace"), "");
fullEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("enclosure_name3", "enclosure_namespace"), "item_value");
fullEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("enclosure_name4", "xmlns"), "");
fullEnclosureLink.BaseUri = new Uri("http://link_url.com");
fullEnclosureLink.ElementExtensions.Add(new ExtensionObject { Value = 10 });
fullEnclosureLink.Length = 10;
fullEnclosureLink.MediaType = "enclosure_mediaType";
fullEnclosureLink.RelationshipType = "enclosure";
fullEnclosureLink.Title = "enclosure_title";
fullEnclosureLink.Uri = new Uri("http://enclosure_uri.com");
var fullAlternateLink = new SyndicationLink();
fullAlternateLink.AttributeExtensions.Add(new XmlQualifiedName("alternate_name1"), null);
fullAlternateLink.AttributeExtensions.Add(new XmlQualifiedName("alternate_name2", "alternate_namespace"), "");
fullAlternateLink.AttributeExtensions.Add(new XmlQualifiedName("alternate_name3", "alternate_namespace"), "alternate_value");
fullAlternateLink.AttributeExtensions.Add(new XmlQualifiedName("alternate_name4", "xmlns"), "");
fullAlternateLink.BaseUri = new Uri("http://alternate_url.com");
fullAlternateLink.ElementExtensions.Add(new ExtensionObject { Value = 10 });
fullAlternateLink.Length = 10;
fullAlternateLink.MediaType = "alternate_mediaType";
fullAlternateLink.RelationshipType = "alternate";
fullAlternateLink.Title = "alternate_title";
fullAlternateLink.Uri = new Uri("http://alternate_uri.com");
var attributeSyndicationLink = new SyndicationLink
{
Uri = new Uri("http://link_uri.com")
};
attributeSyndicationLink.AttributeExtensions.Add(new XmlQualifiedName("href"), "link_href");
var fullSyndicationItem = new SyndicationItem();
fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name1"), null);
fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name2", "item_namespace"), "");
fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name3", "item_namespace"), "item_value");
fullSyndicationItem.AttributeExtensions.Add(new XmlQualifiedName("item_name4", "xmlns"), "");
fullSyndicationItem.Authors.Add(new SyndicationPerson());
fullSyndicationItem.Authors.Add(CreatePerson("author"));
fullSyndicationItem.BaseUri = new Uri("/relative", UriKind.Relative);
fullSyndicationItem.Categories.Add(new SyndicationCategory());
fullSyndicationItem.Categories.Add(fullSyndicationCategory);
fullSyndicationItem.Categories.Add(attributeSyndicationCategory);
fullSyndicationItem.Content = CreateContent("content");
fullSyndicationItem.Contributors.Add(new SyndicationPerson());
fullSyndicationItem.Contributors.Add(CreatePerson("contributor"));
fullSyndicationItem.Copyright = CreateContent("copyright");
fullSyndicationItem.ElementExtensions.Add(new ExtensionObject { Value = 10 });
fullSyndicationItem.Id = "id";
fullSyndicationItem.LastUpdatedTime = DateTimeOffset.MinValue.AddTicks(100);
fullSyndicationItem.Links.Add(new SyndicationLink());
fullSyndicationItem.Links.Add(fullSyndicationLink);
fullSyndicationItem.Links.Add(fullEnclosureLink);
fullSyndicationItem.Links.Add(new SyndicationLink { RelationshipType = "enclosure" });
fullSyndicationItem.Links.Add(new SyndicationLink { RelationshipType = "alternate" });
fullSyndicationItem.Links.Add(fullAlternateLink);
fullSyndicationItem.Links.Add(attributeSyndicationLink);
fullSyndicationItem.PublishDate = DateTimeOffset.MinValue.AddTicks(200);
fullSyndicationItem.Summary = CreateContent("summary");
fullSyndicationItem.Title = CreateContent("title");
yield return new object[]
{
fullSyndicationItem,
true,
@"<item xml:base=""/relative"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"">
<guid isPermaLink=""false"">id</guid>
<link />
<author xmlns=""http://www.w3.org/2005/Atom"" />
<author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<name>author_name</name>
<uri>author_uri</uri>
<email>author_email</email>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</author>
<category />
<category category_name1="""" d2p1:category_name2="""" d2p1:category_name3=""category_value"" d1p2:category_name4="""" domain=""category_scheme"" xmlns:d2p1=""category_namespace"">category_name</category>
<category term=""term_value"">name</category>
<title>title_title</title>
<description>summary_title</description>
<pubDate>Mon, 01 Jan 0001 00:00:00 Z</pubDate>
<link href="""" xmlns=""http://www.w3.org/2005/Atom"" />
<link xml:base=""http://link_url.com/"" link_name1="""" d2p1:link_name2="""" d2p1:link_name3=""link_value"" d1p2:link_name4="""" rel=""link_relationshipType"" type=""link_mediaType"" title=""link_title"" length=""10"" href=""http://link_uri.com/"" xmlns:d2p1=""link_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</link>
<enclosure xml:base=""http://link_url.com/"" enclosure_name1="""" d2p1:enclosure_name2="""" d2p1:enclosure_name3=""item_value"" d1p2:enclosure_name4="""" url=""http://enclosure_uri.com/"" type=""enclosure_mediaType"" length=""10"" xmlns:d2p1=""enclosure_namespace"" />
<link rel=""enclosure"" href="""" xmlns=""http://www.w3.org/2005/Atom"" />
<link xml:base=""http://alternate_url.com/"" alternate_name1="""" d2p1:alternate_name2="""" d2p1:alternate_name3=""alternate_value"" d1p2:alternate_name4="""" rel=""alternate"" type=""alternate_mediaType"" title=""alternate_title"" length=""10"" href=""http://alternate_uri.com/"" xmlns:d2p1=""alternate_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</link>
<link href=""link_href"" xmlns=""http://www.w3.org/2005/Atom"" />
<updated xmlns=""http://www.w3.org/2005/Atom"">0001-01-01T00:00:00Z</updated>
<rights type=""html"" copyright_name1="""" d2p1:copyright_name2="""" d2p1:copyright_name3=""copyright_value"" d1p2:copyright_name4="""" xmlns:d2p1=""copyright_namespace"" xmlns=""http://www.w3.org/2005/Atom"">copyright_title</rights>
<content type=""html"" content_name1="""" d2p1:content_name2="""" d2p1:content_name3=""content_value"" d1p2:content_name4="""" xmlns:d2p1=""content_namespace"" xmlns=""http://www.w3.org/2005/Atom"">content_title</content>
<contributor xmlns=""http://www.w3.org/2005/Atom"" />
<contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<name>contributor_name</name>
<uri>contributor_uri</uri>
<email>contributor_email</email>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</contributor>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</item>"
};
yield return new object[]
{
fullSyndicationItem,
false,
@"<item xml:base=""/relative"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"">
<guid isPermaLink=""false"">id</guid>
<link />
<category />
<category category_name1="""" d2p1:category_name2="""" d2p1:category_name3=""category_value"" d1p2:category_name4="""" domain=""category_scheme"" xmlns:d2p1=""category_namespace"">category_name</category>
<category term=""term_value"">name</category>
<title>title_title</title>
<description>summary_title</description>
<pubDate>Mon, 01 Jan 0001 00:00:00 Z</pubDate>
<enclosure xml:base=""http://link_url.com/"" enclosure_name1="""" d2p1:enclosure_name2="""" d2p1:enclosure_name3=""item_value"" d1p2:enclosure_name4="""" url=""http://enclosure_uri.com/"" type=""enclosure_mediaType"" length=""10"" xmlns:d2p1=""enclosure_namespace"" />
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</item>"
};
foreach (string email in new string[] { null, "" })
{
var oneAuthorWithInvalidEmail = new SyndicationItem();
oneAuthorWithInvalidEmail.Authors.Add(new SyndicationPerson(email));
yield return new object[]
{
oneAuthorWithInvalidEmail,
true,
@"<item>
<author xmlns=""http://www.w3.org/2005/Atom"" />
<description />
</item>"
};
yield return new object[]
{
oneAuthorWithInvalidEmail,
false,
@"<item>
<description />
</item>"
};
}
var oneAuthorWithValidEmail = new SyndicationItem();
oneAuthorWithValidEmail.Authors.Add(CreatePerson("author"));
foreach (bool serializeExtensionsAsAtom in new bool[] { true, false })
{
yield return new object[]
{
oneAuthorWithValidEmail,
serializeExtensionsAsAtom,
@"<item>
<author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d2p2:author_name4="""" xmlns:d2p2=""xmlns"" xmlns:d2p1=""author_namespace"">author_email</author>
<description />
</item>"
};
};
var attributeEnclosureLink = new SyndicationLink();
attributeEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("length"), "100");
attributeEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("type"), "custom_type");
attributeEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("url"), "http://custom_url.com");
attributeEnclosureLink.AttributeExtensions.Add(new XmlQualifiedName("enclosure_name4", "xmlns"), "");
attributeEnclosureLink.Length = 10;
attributeEnclosureLink.MediaType = "enclosure_mediaType";
attributeEnclosureLink.RelationshipType = "enclosure";
attributeEnclosureLink.Uri = new Uri("http://enclosure_uri.com");
var attributeEnclosureItem = new SyndicationItem();
attributeEnclosureItem.Links.Add(attributeEnclosureLink);
foreach (bool serializeExtensionsAsAtom in new bool[] { true, false })
{
yield return new object[]
{
attributeEnclosureItem,
serializeExtensionsAsAtom,
@"<item>
<description />
<enclosure length=""100"" type=""custom_type"" url=""http://custom_url.com"" d2p1:enclosure_name4="""" xmlns:d2p1=""xmlns"" />
</item>"
};
}
var fullFeed = new SyndicationFeed();
fullFeed.AttributeExtensions.Add(new XmlQualifiedName("name"), "value");
fullFeed.Authors.Add(new SyndicationPerson("email", "author", "uri"));
fullFeed.BaseUri = new Uri("http://feed_baseuri.com");
fullFeed.Categories.Add(new SyndicationCategory("category"));
fullFeed.Contributors.Add(new SyndicationPerson("email", "contributor", "uri"));
fullFeed.Copyright = new TextSyndicationContent("copyright");
fullFeed.Description = new TextSyndicationContent("description");
fullFeed.ElementExtensions.Add(new ExtensionObject { Value = 10 });
fullFeed.Generator = "generator";
fullFeed.Id = "id";
fullFeed.ImageUrl = new Uri("http://imageurl.com");
fullFeed.Items = new SyndicationItem[]
{
new SyndicationItem("title", "content", null)
};
fullFeed.Language = "language";
fullFeed.LastUpdatedTime = DateTimeOffset.MinValue.AddTicks(10);
fullFeed.Links.Add(new SyndicationLink(new Uri("http://microsoft.com")));
fullFeed.Title = new TextSyndicationContent("title");
var itemWithSourceFeed = new SyndicationItem() { SourceFeed = fullFeed };
foreach (bool serializeExtensionsAsAtom in new bool[] { true, false })
{
yield return new object[]
{
itemWithSourceFeed,
serializeExtensionsAsAtom,
@"<item>
<description />
<source name=""value"">title</source>
</item>"
};
};
var itemWithEmptyFeed = new SyndicationItem() { SourceFeed = new SyndicationFeed() };
foreach (bool serializeExtensionsAsAtom in new bool[] { true, false })
{
yield return new object[]
{
itemWithEmptyFeed,
serializeExtensionsAsAtom,
@"<item>
<description />
<source />
</item>"
};
};
var selfLinkFeed = new SyndicationFeed();
selfLinkFeed.Links.Add(new SyndicationLink() { RelationshipType = "self", Uri = new Uri("http://microsoft.com") });
var itemWithSelfLinkFeed = new SyndicationItem() { SourceFeed = selfLinkFeed };
foreach (bool serializeExtensionsAsAtom in new bool[] { true, false })
{
yield return new object[]
{
itemWithSelfLinkFeed,
serializeExtensionsAsAtom,
@"<item>
<description />
<source url=""http://microsoft.com/"" />
</item>"
};
};
var selfAttributeLinkFeed = new SyndicationFeed();
selfAttributeLinkFeed.AttributeExtensions.Add(new XmlQualifiedName("url"), "url_value");
selfAttributeLinkFeed.Links.Add(new SyndicationLink() { RelationshipType = "self", Uri = new Uri("http://microsoft.com") });
var itemWithSelfAttributeLinkFeed = new SyndicationItem() { SourceFeed = selfAttributeLinkFeed };
foreach (bool serializeExtensionsAsAtom in new bool[] { true, false })
{
yield return new object[]
{
itemWithSelfAttributeLinkFeed,
serializeExtensionsAsAtom,
@"<item>
<description />
<source url=""url_value"" />
</item>"
};
};
}
[Theory]
[MemberData(nameof(WriteTo_TestData))]
public void WriteTo_Invoke_SerializesExpected(SyndicationItem item, bool serializeExtensionsAsAtom, string expected)
{
var formatter = new Rss20ItemFormatter(item) { SerializeExtensionsAsAtom = serializeExtensionsAsAtom };
CompareHelper.AssertEqualWriteOutput(expected, writer => formatter.WriteTo(writer));
if (serializeExtensionsAsAtom)
{
CompareHelper.AssertEqualWriteOutput(expected, writer => item.SaveAsRss20(writer));
}
CompareHelper.AssertEqualWriteOutput(expected, writer =>
{
writer.WriteStartElement("item");
((IXmlSerializable)formatter).WriteXml(writer);
writer.WriteEndElement();
});
var genericFormatter = new Rss20ItemFormatter<SyndicationItem>(item) { SerializeExtensionsAsAtom = serializeExtensionsAsAtom };
CompareHelper.AssertEqualWriteOutput(expected, writer => formatter.WriteTo(writer));
if (serializeExtensionsAsAtom)
{
CompareHelper.AssertEqualWriteOutput(expected, writer => item.SaveAsRss20(writer));
}
CompareHelper.AssertEqualWriteOutput(expected, writer =>
{
writer.WriteStartElement("item");
((IXmlSerializable)genericFormatter).WriteXml(writer);
writer.WriteEndElement();
});
}
[Fact]
public void WriteTo_NullWriter_ThrowsArgumentNullException()
{
var formatter = new Rss20ItemFormatter(new SyndicationItem());
AssertExtensions.Throws<ArgumentNullException>("writer", () => formatter.WriteTo(null));
}
[Fact]
public void WriteTo_NoItem_ThrowsInvalidOperationException()
{
using (var stringWriter = new StringWriter())
using (var writer = XmlWriter.Create(stringWriter))
{
var formatter = new Rss20ItemFormatter();
Assert.Throws<InvalidOperationException>(() => formatter.WriteTo(writer));
}
}
[Fact]
public void WriteXml_NullWriter_ThrowsArgumentNullException()
{
IXmlSerializable formatter = new Rss20ItemFormatter();
AssertExtensions.Throws<ArgumentNullException>("writer", () => formatter.WriteXml(null));
}
[Fact]
public void WriteXml_NoItem_ThrowsInvalidOperationException()
{
using (var stringWriter = new StringWriter())
using (var writer = XmlWriter.Create(stringWriter))
{
IXmlSerializable formatter = new Rss20ItemFormatter();
Assert.Throws<InvalidOperationException>(() => formatter.WriteXml(writer));
}
}
public static IEnumerable<object[]> CanRead_TestData()
{
yield return new object[] { @"<item xmlns=""different"" />", false };
yield return new object[] { @"<different />", false };
yield return new object[] { @"<item />", true };
yield return new object[] { @"<item></item>", true };
}
[Theory]
[MemberData(nameof(CanRead_TestData))]
public void CanRead_ValidReader_ReturnsExpected(string xmlString, bool expected)
{
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter();
Assert.Equal(expected, formatter.CanRead(reader));
}
}
[Fact]
public void CanRead_NullReader_ThrowsArgumentNullException()
{
var formatter = new Rss20ItemFormatter();
AssertExtensions.Throws<ArgumentNullException>("reader", () => formatter.CanRead(null));
}
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public void ReadFrom_FullItem_ReturnsExpected(bool preserveAttributeExtensions, bool preserveElementExtensions)
{
string xmlString =
@"<item xml:base=""/relative"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"">
<guid isPermaLink=""false"">id</guid>
<link />
<author xmlns=""http://www.w3.org/2005/Atom"" />
<author xmlns=""http://www.w3.org/2005/Atom""></author>
<author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<name>author_name</name>
<uri>author_uri</uri>
<email>author_email</email>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</author>
<author />
<author></author>
<author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace"">email</author>
<category />
<category></category>
<category category_name1="""" d2p1:category_name2="""" d2p1:category_name3=""category_value"" d1p2:category_name4="""" domain=""category_scheme"" xmlns:d2p1=""category_namespace"">category_name</category>
<title>title_title</title>
<description>summary_title</description>
<pubDate />
<pubDate></pubDate>
<pubDate>Mon, 01 Jan 0001 00:00:00 Z</pubDate>
<link href="""" xmlns=""http://www.w3.org/2005/Atom"" />
<link xml:base=""http://link_url.com/"" link_name1="""" d2p1:link_name2="""" d2p1:link_name3=""link_value"" d1p2:link_name4="""" rel=""link_relationshipType"" type=""link_mediaType"" title=""link_title"" length=""10"" href=""http://link_uri.com/"" xmlns:d2p1=""link_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</link>
<enclosure xml:base=""http://link_url.com/"" enclosure_name1="""" d2p1:enclosure_name2="""" d2p1:enclosure_name3=""item_value"" d1p2:enclosure_name4="""" url=""http://enclosure_uri.com/"" type=""enclosure_mediaType"" length=""10"" xmlns:d2p1=""enclosure_namespace"" />
<link rel=""enclosure"" href="""" xmlns=""http://www.w3.org/2005/Atom"" />
<link xml:base=""http://alternate_url.com/"" alternate_name1="""" d2p1:alternate_name2="""" d2p1:alternate_name3=""alternate_value"" d1p2:alternate_name4="""" rel=""alternate"" type=""alternate_mediaType"" title=""alternate_title"" length=""10"" href=""http://alternate_uri.com/"" xmlns:d2p1=""alternate_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</link>
<link href=""link_href"" xmlns=""http://www.w3.org/2005/Atom"" />
<enclosure />
<enclosure></enclosure>
<enclosure length="""" />
<enclosure xmlns=""http://www.w3.org/2005/Atom""/>
<link />
<link></link>
<link xml:ignored=""true"" alternate_name1="""" d2p1:alternate_name2="""" d2p1:alternate_name3=""alternate_value"" d1p2:alternate_name4="""" xmlns:d2p1=""alternate_namespace"">http://microsoft.com</link>
<updated xmlns=""http://www.w3.org/2005/Atom"">0001-01-01T00:00:00Z</updated>
<rights type=""html"" copyright_name1="""" d2p1:copyright_name2="""" d2p1:copyright_name3=""copyright_value"" d1p2:copyright_name4="""" xmlns:d2p1=""copyright_namespace"" xmlns=""http://www.w3.org/2005/Atom"">copyright_title</rights>
<content type=""html"" content_name1="""" d2p1:content_name2="""" d2p1:content_name3=""content_value"" d1p2:content_name4="""" xmlns:d2p1=""content_namespace"" xmlns=""http://www.w3.org/2005/Atom"">content_title</content>
<contributor xmlns=""http://www.w3.org/2005/Atom"" />
<contributor xmlns=""http://www.w3.org/2005/Atom""></contributor>
<contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<name>contributor_name</name>
<uri>contributor_uri</uri>
<email>contributor_email</email>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</contributor>
<contributor />
<contributor></contributor>
<contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace"">email</contributor>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</item>";
VerifyRead(xmlString, preserveAttributeExtensions, preserveElementExtensions, item =>
{
if (preserveAttributeExtensions)
{
Assert.Equal(4, item.AttributeExtensions.Count);
Assert.Equal("", item.AttributeExtensions[new XmlQualifiedName("item_name1")]);
Assert.Equal("", item.AttributeExtensions[new XmlQualifiedName("item_name2", "item_namespace")]);
Assert.Equal("item_value", item.AttributeExtensions[new XmlQualifiedName("item_name3", "item_namespace")]);
Assert.Equal("", item.AttributeExtensions[new XmlQualifiedName("item_name4", "xmlns")]);
}
else
{
Assert.Empty(item.AttributeExtensions);
}
Assert.Equal(6, item.Authors.Count);
SyndicationPerson firstAuthor = item.Authors[0];
Assert.Empty(firstAuthor.AttributeExtensions);
Assert.Empty(firstAuthor.ElementExtensions);
Assert.Null(firstAuthor.Email);
Assert.Null(firstAuthor.Name);
Assert.Null(firstAuthor.Uri);
SyndicationPerson secondAuthor = item.Authors[1];
Assert.Empty(secondAuthor.AttributeExtensions);
Assert.Empty(secondAuthor.ElementExtensions);
Assert.Null(secondAuthor.Email);
Assert.Null(secondAuthor.Name);
Assert.Null(secondAuthor.Uri);
SyndicationPerson thirdAuthor = item.Authors[2];
Assert.Equal(4, thirdAuthor.AttributeExtensions.Count);
Assert.Equal("", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name1")]);
Assert.Equal("", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name2", "author_namespace")]);
Assert.Equal("author_value", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name3", "author_namespace")]);
Assert.Equal("", thirdAuthor.AttributeExtensions[new XmlQualifiedName("author_name4", "xmlns")]);
Assert.Equal(1, thirdAuthor.ElementExtensions.Count);
Assert.Equal(10, thirdAuthor.ElementExtensions[0].GetObject<ExtensionObject>().Value);
Assert.Equal("author_email", thirdAuthor.Email);
Assert.Equal("author_name", thirdAuthor.Name);
Assert.Equal("author_uri", thirdAuthor.Uri);
SyndicationPerson fourthAuthor = item.Authors[3];
Assert.Empty(firstAuthor.AttributeExtensions);
Assert.Empty(firstAuthor.ElementExtensions);
Assert.Null(firstAuthor.Email);
Assert.Null(firstAuthor.Name);
Assert.Null(firstAuthor.Uri);
SyndicationPerson fifthAuthor = item.Authors[4];
Assert.Empty(fifthAuthor.AttributeExtensions);
Assert.Empty(fifthAuthor.ElementExtensions);
Assert.Empty(fifthAuthor.Email);
Assert.Null(fifthAuthor.Name);
Assert.Null(fifthAuthor.Uri);
SyndicationPerson sixthAuthor = item.Authors[5];
if (preserveAttributeExtensions)
{
Assert.Equal(4, sixthAuthor.AttributeExtensions.Count);
Assert.Equal("", sixthAuthor.AttributeExtensions[new XmlQualifiedName("author_name1")]);
Assert.Equal("", sixthAuthor.AttributeExtensions[new XmlQualifiedName("author_name2", "author_namespace")]);
Assert.Equal("author_value", sixthAuthor.AttributeExtensions[new XmlQualifiedName("author_name3", "author_namespace")]);
Assert.Equal("", sixthAuthor.AttributeExtensions[new XmlQualifiedName("author_name4", "xmlns")]);
}
else
{
Assert.Empty(sixthAuthor.AttributeExtensions);
}
Assert.Empty(sixthAuthor.ElementExtensions);
Assert.Equal("email", sixthAuthor.Email);
Assert.Null(sixthAuthor.Name);
Assert.Null(sixthAuthor.Uri);
Assert.Equal(new Uri("/relative", UriKind.Relative), item.BaseUri);
SyndicationCategory firstCategory = item.Categories[0];
Assert.Empty(firstCategory.AttributeExtensions);
Assert.Empty(firstCategory.ElementExtensions);
Assert.Null(firstCategory.Name);
Assert.Null(firstCategory.Scheme);
Assert.Null(firstCategory.Label);
SyndicationCategory secondCategory = item.Categories[1];
Assert.Empty(secondCategory.AttributeExtensions);
Assert.Empty(secondCategory.ElementExtensions);
Assert.Empty(secondCategory.Name);
Assert.Null(secondCategory.Scheme);
Assert.Null(secondCategory.Label);
SyndicationCategory thirdCategory = item.Categories[2];
if (preserveAttributeExtensions)
{
Assert.Equal(4, thirdCategory.AttributeExtensions.Count);
Assert.Equal("", thirdCategory.AttributeExtensions[new XmlQualifiedName("category_name1")]);
Assert.Equal("", thirdCategory.AttributeExtensions[new XmlQualifiedName("category_name2", "category_namespace")]);
Assert.Equal("category_value", thirdCategory.AttributeExtensions[new XmlQualifiedName("category_name3", "category_namespace")]);
Assert.Equal("", thirdCategory.AttributeExtensions[new XmlQualifiedName("category_name4", "xmlns")]);
}
else
{
Assert.Empty(thirdCategory.AttributeExtensions);
}
Assert.Empty(thirdCategory.ElementExtensions);
Assert.Equal("category_name", thirdCategory.Name);
Assert.Equal("category_scheme", thirdCategory.Scheme);
Assert.Null(thirdCategory.Label);
TextSyndicationContent content = Assert.IsType<TextSyndicationContent>(item.Content);
Assert.Equal(4, content.AttributeExtensions.Count);
Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name1")]);
Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name2", "content_namespace")]);
Assert.Equal("content_value", content.AttributeExtensions[new XmlQualifiedName("content_name3", "content_namespace")]);
Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name4", "xmlns")]);
Assert.Equal("content_title", content.Text);
Assert.Equal("html", content.Type);
Assert.Equal(3, item.Contributors.Count);
SyndicationPerson firstContributor = item.Contributors[0];
Assert.Empty(firstContributor.AttributeExtensions);
Assert.Empty(firstContributor.ElementExtensions);
Assert.Null(firstContributor.Email);
Assert.Null(firstContributor.Name);
Assert.Null(firstContributor.Uri);
SyndicationPerson secondContributor = item.Contributors[1];
Assert.Empty(secondContributor.AttributeExtensions);
Assert.Empty(secondContributor.ElementExtensions);
Assert.Null(secondContributor.Email);
Assert.Null(secondContributor.Name);
Assert.Null(secondContributor.Uri);
SyndicationPerson thirdContributor = item.Contributors[2];
Assert.Equal(4, thirdContributor.AttributeExtensions.Count);
Assert.Equal("", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name1")]);
Assert.Equal("", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name2", "contributor_namespace")]);
Assert.Equal("contributor_value", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name3", "contributor_namespace")]);
Assert.Equal("", thirdContributor.AttributeExtensions[new XmlQualifiedName("contributor_name4", "xmlns")]);
Assert.Equal(1, thirdContributor.ElementExtensions.Count);
Assert.Equal(10, thirdContributor.ElementExtensions[0].GetObject<ExtensionObject>().Value);
Assert.Equal("contributor_email", thirdContributor.Email);
Assert.Equal("contributor_name", thirdContributor.Name);
Assert.Equal("contributor_uri", thirdContributor.Uri);
Assert.Equal(4, item.Copyright.AttributeExtensions.Count);
Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name1")]);
Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name2", "copyright_namespace")]);
Assert.Equal("copyright_value", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name3", "copyright_namespace")]);
Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name4", "xmlns")]);
Assert.Equal("copyright_title", item.Copyright.Text);
Assert.Equal("html", item.Copyright.Type);
if (preserveElementExtensions)
{
Assert.Equal(5, item.ElementExtensions.Count);
Assert.Equal(10, item.ElementExtensions[item.ElementExtensions.Count - 1].GetObject<ExtensionObject>().Value);
}
else
{
Assert.Empty(item.ElementExtensions);
}
Assert.Equal("id", item.Id);
Assert.Equal(DateTimeOffset.MinValue, item.LastUpdatedTime);
Assert.Equal(13, item.Links.Count);
SyndicationLink firstLink = item.Links[0];
Assert.Empty(firstLink.AttributeExtensions);
Assert.Empty(firstLink.ElementExtensions);
Assert.Equal(0, firstLink.Length);
Assert.Null(firstLink.MediaType);
Assert.Equal("alternate", firstLink.RelationshipType);
Assert.Null(firstLink.Title);
Assert.Empty(firstLink.Uri.OriginalString);
SyndicationLink secondLink = item.Links[1];
Assert.Empty(secondLink.AttributeExtensions);
Assert.Empty(secondLink.ElementExtensions);
Assert.Equal(new Uri("/relative", UriKind.Relative), secondLink.BaseUri);
Assert.Equal(0, secondLink.Length);
Assert.Null(secondLink.MediaType);
Assert.Null(secondLink.RelationshipType);
Assert.Null(secondLink.Title);
Assert.Empty(secondLink.Uri.OriginalString);
SyndicationLink thirdLink = item.Links[2];
Assert.Equal(4, thirdLink.AttributeExtensions.Count);
Assert.Equal("", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name1")]);
Assert.Equal("", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name2", "link_namespace")]);
Assert.Equal("link_value", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name3", "link_namespace")]);
Assert.Equal("", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name4", "xmlns")]);
Assert.Equal(1, thirdLink.ElementExtensions.Count);
Assert.Equal(10, thirdLink.ElementExtensions[0].GetObject<ExtensionObject>().Value);
Assert.Equal(new Uri("http://link_url.com/"), thirdLink.BaseUri);
Assert.Equal(10, thirdLink.Length);
Assert.Equal("link_mediaType", thirdLink.MediaType);
Assert.Equal("link_relationshipType", thirdLink.RelationshipType);
Assert.Equal("link_title", thirdLink.Title);
Assert.Equal(new Uri("http://link_uri.com/"), thirdLink.Uri);
SyndicationLink fourthLink = item.Links[3];
if (preserveAttributeExtensions)
{
Assert.Equal(4, fourthLink.AttributeExtensions.Count);
Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name1")]);
Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name2", "enclosure_namespace")]);
Assert.Equal("item_value", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name3", "enclosure_namespace")]);
Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name4", "xmlns")]);
}
else
{
Assert.Empty(fourthLink.AttributeExtensions);
}
Assert.Empty(fourthLink.ElementExtensions);
Assert.Equal(new Uri("http://link_url.com/"), fourthLink.BaseUri);
Assert.Equal(10, fourthLink.Length);
Assert.Equal("enclosure_mediaType", fourthLink.MediaType);
Assert.Equal("enclosure", fourthLink.RelationshipType);
Assert.Null(fourthLink.Title);
Assert.Equal(new Uri("http://enclosure_uri.com/"), fourthLink.Uri);
SyndicationLink fifthLink = item.Links[4];
Assert.Empty(fifthLink.AttributeExtensions);
Assert.Empty(fifthLink.ElementExtensions);
Assert.Equal(new Uri("/relative", UriKind.Relative), fifthLink.BaseUri);
Assert.Equal(0, fifthLink.Length);
Assert.Null(fifthLink.MediaType);
Assert.Equal("enclosure", fifthLink.RelationshipType);
Assert.Null(fifthLink.Title);
Assert.Empty(fifthLink.Uri.OriginalString);
SyndicationLink sixthLink = item.Links[5];
Assert.Equal(4, sixthLink.AttributeExtensions.Count);
Assert.Equal("", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name1")]);
Assert.Equal("", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name2", "alternate_namespace")]);
Assert.Equal("alternate_value", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name3", "alternate_namespace")]);
Assert.Equal("", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name4", "xmlns")]);
Assert.Equal(1, sixthLink.ElementExtensions.Count);
Assert.Equal(10, sixthLink.ElementExtensions[0].GetObject<ExtensionObject>().Value);
Assert.Equal(new Uri("http://alternate_url.com/"), sixthLink.BaseUri);
Assert.Equal(10, sixthLink.Length);
Assert.Equal("alternate_mediaType", sixthLink.MediaType);
Assert.Equal("alternate", sixthLink.RelationshipType);
Assert.Equal("alternate_title", sixthLink.Title);
Assert.Equal(new Uri("http://alternate_uri.com/"), sixthLink.Uri);
Assert.Equal(DateTimeOffset.MinValue, item.PublishDate);
SyndicationLink seventhLink = item.Links[6];
Assert.Empty(seventhLink.AttributeExtensions);
Assert.Empty(seventhLink.ElementExtensions);
Assert.Equal(new Uri("/relative", UriKind.Relative), seventhLink.BaseUri);
Assert.Equal(0, seventhLink.Length);
Assert.Null(seventhLink.MediaType);
Assert.Null(seventhLink.RelationshipType);
Assert.Null(seventhLink.Title);
Assert.Equal(new Uri("link_href", UriKind.Relative), seventhLink.Uri);
SyndicationLink eighthLink = item.Links[7];
Assert.Empty(eighthLink.AttributeExtensions);
Assert.Empty(eighthLink.ElementExtensions);
Assert.Equal(0, eighthLink.Length);
Assert.Null(eighthLink.MediaType);
Assert.Equal("enclosure", eighthLink.RelationshipType);
Assert.Null(eighthLink.Title);
Assert.Null(eighthLink.Uri);
SyndicationLink ninthLink = item.Links[8];
Assert.Empty(ninthLink.AttributeExtensions);
Assert.Empty(ninthLink.ElementExtensions);
Assert.Equal(0, ninthLink.Length);
Assert.Null(ninthLink.MediaType);
Assert.Equal("enclosure", ninthLink.RelationshipType);
Assert.Null(ninthLink.Title);
Assert.Null(ninthLink.Uri);
SyndicationLink tenthLink = item.Links[9];
Assert.Empty(tenthLink.AttributeExtensions);
Assert.Empty(tenthLink.ElementExtensions);
Assert.Equal(0, tenthLink.Length);
Assert.Null(tenthLink.MediaType);
Assert.Equal("enclosure", tenthLink.RelationshipType);
Assert.Null(tenthLink.Title);
Assert.Null(tenthLink.Uri);
SyndicationLink eleventhLink = item.Links[10];
Assert.Empty(eleventhLink.AttributeExtensions);
Assert.Empty(eleventhLink.ElementExtensions);
Assert.Equal(0, eleventhLink.Length);
Assert.Null(eleventhLink.MediaType);
Assert.Equal("alternate", eleventhLink.RelationshipType);
Assert.Null(eleventhLink.Title);
Assert.Empty(eleventhLink.Uri.OriginalString);
SyndicationLink twelfthLink = item.Links[11];
Assert.Empty(twelfthLink.AttributeExtensions);
Assert.Empty(twelfthLink.ElementExtensions);
Assert.Equal(0, twelfthLink.Length);
Assert.Null(twelfthLink.MediaType);
Assert.Equal("alternate", twelfthLink.RelationshipType);
Assert.Null(twelfthLink.Title);
Assert.Empty(twelfthLink.Uri.OriginalString);
SyndicationLink thirteenthLink = item.Links[12];
if (preserveAttributeExtensions)
{
Assert.Equal(5, thirteenthLink.AttributeExtensions.Count);
Assert.Equal("true", thirteenthLink.AttributeExtensions[new XmlQualifiedName("ignored", "http://www.w3.org/XML/1998/namespace")]);
Assert.Equal("", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name1")]);
Assert.Equal("", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name2", "alternate_namespace")]);
Assert.Equal("alternate_value", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name3", "alternate_namespace")]);
Assert.Equal("", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name4", "xmlns")]);
}
else
{
Assert.Empty(thirteenthLink.AttributeExtensions);
}
Assert.Empty(thirteenthLink.ElementExtensions);
Assert.Equal(0, thirteenthLink.Length);
Assert.Null(thirteenthLink.MediaType);
Assert.Equal("alternate", thirteenthLink.RelationshipType);
Assert.Null(thirteenthLink.Title);
Assert.Equal(new Uri("http://microsoft.com"), thirteenthLink.Uri);
Assert.Null(item.SourceFeed);
Assert.Empty(item.Summary.AttributeExtensions);
Assert.Equal("summary_title", item.Summary.Text);
Assert.Equal("text", item.Summary.Type);
Assert.Empty(item.Title.AttributeExtensions);
Assert.Equal("title_title", item.Title.Text);
Assert.Equal("text", item.Title.Type);
});
}
[Theory]
[InlineData(true, true)]
[InlineData(false, false)]
public void ReadFrom_TryParseReturnsTrue_ReturnsExpected(bool preserveAttributeExtensions, bool preserveElementExtensions)
{
using (var stringReader = new StringReader(
@"<item xml:base=""/relative"" item_name1="""" d1p1:item_name2="""" d1p1:item_name3=""item_value"" d1p2:item_name4="""" xmlns:d1p2=""xmlns"" xmlns:d1p1=""item_namespace"">
<guid isPermaLink=""false"">id</guid>
<link />
<author xmlns=""http://www.w3.org/2005/Atom"" />
<author xmlns=""http://www.w3.org/2005/Atom""></author>
<author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<name>author_name</name>
<uri>author_uri</uri>
<email>author_email</email>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</author>
<author />
<author></author>
<author author_name1="""" d2p1:author_name2="""" d2p1:author_name3=""author_value"" d1p2:author_name4="""" xmlns:d2p1=""author_namespace"">email</author>
<category />
<category></category>
<category category_name1="""" d2p1:category_name2="""" d2p1:category_name3=""category_value"" d1p2:category_name4="""" domain=""category_scheme"" xmlns:d2p1=""category_namespace"">category_name</category>
<title>title_title</title>
<description>summary_title</description>
<pubDate />
<pubDate></pubDate>
<pubDate>Mon, 01 Jan 0001 00:00:00 Z</pubDate>
<link href="""" xmlns=""http://www.w3.org/2005/Atom"" />
<link xml:base=""http://link_url.com/"" link_name1="""" d2p1:link_name2="""" d2p1:link_name3=""link_value"" d1p2:link_name4="""" rel=""link_relationshipType"" type=""link_mediaType"" title=""link_title"" length=""10"" href=""http://link_uri.com/"" xmlns:d2p1=""link_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</link>
<enclosure xml:base=""http://link_url.com/"" enclosure_name1="""" d2p1:enclosure_name2="""" d2p1:enclosure_name3=""item_value"" d1p2:enclosure_name4="""" url=""http://enclosure_uri.com/"" type=""enclosure_mediaType"" length=""10"" xmlns:d2p1=""enclosure_namespace"" />
<link rel=""enclosure"" href="""" xmlns=""http://www.w3.org/2005/Atom"" />
<link xml:base=""http://alternate_url.com/"" alternate_name1="""" d2p1:alternate_name2="""" d2p1:alternate_name3=""alternate_value"" d1p2:alternate_name4="""" rel=""alternate"" type=""alternate_mediaType"" title=""alternate_title"" length=""10"" href=""http://alternate_uri.com/"" xmlns:d2p1=""alternate_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</link>
<link href=""link_href"" xmlns=""http://www.w3.org/2005/Atom"" />
<enclosure />
<enclosure></enclosure>
<enclosure length="""" />
<enclosure xmlns=""http://www.w3.org/2005/Atom""/>
<link />
<link></link>
<link xml:ignored=""true"" alternate_name1="""" d2p1:alternate_name2="""" d2p1:alternate_name3=""alternate_value"" d1p2:alternate_name4="""" xmlns:d2p1=""alternate_namespace"">http://microsoft.com</link>
<updated xmlns=""http://www.w3.org/2005/Atom"">0001-01-01T00:00:00Z</updated>
<rights type=""html"" copyright_name1="""" d2p1:copyright_name2="""" d2p1:copyright_name3=""copyright_value"" d1p2:copyright_name4="""" xmlns:d2p1=""copyright_namespace"" xmlns=""http://www.w3.org/2005/Atom"">copyright_title</rights>
<content type=""html"" content_name1="""" d2p1:content_name2="""" d2p1:content_name3=""content_value"" d1p2:content_name4="""" xmlns:d2p1=""content_namespace"" xmlns=""http://www.w3.org/2005/Atom"">content_title</content>
<contributor xmlns=""http://www.w3.org/2005/Atom"" />
<contributor xmlns=""http://www.w3.org/2005/Atom""></contributor>
<contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace"" xmlns=""http://www.w3.org/2005/Atom"">
<name>contributor_name</name>
<uri>contributor_uri</uri>
<email>contributor_email</email>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</contributor>
<contributor />
<contributor></contributor>
<contributor contributor_name1="""" d2p1:contributor_name2="""" d2p1:contributor_name3=""contributor_value"" d1p2:contributor_name4="""" xmlns:d2p1=""contributor_namespace"">email</contributor>
<Rss20ItemFormatterTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests"">
<Value>10</Value>
</Rss20ItemFormatterTests.ExtensionObject>
</item>"))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter<SyndicationItemTryParseTrueSubclass>()
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
formatter.ReadFrom(reader);
SyndicationItem item = formatter.Item;
Assert.Empty(item.AttributeExtensions);
Assert.Equal(6, item.Authors.Count);
SyndicationPerson firstAuthor = item.Authors[0];
Assert.Empty(firstAuthor.AttributeExtensions);
Assert.Empty(firstAuthor.ElementExtensions);
Assert.Null(firstAuthor.Email);
Assert.Null(firstAuthor.Name);
Assert.Null(firstAuthor.Uri);
SyndicationPerson secondAuthor = item.Authors[1];
Assert.Empty(secondAuthor.AttributeExtensions);
Assert.Empty(secondAuthor.ElementExtensions);
Assert.Null(secondAuthor.Email);
Assert.Null(secondAuthor.Name);
Assert.Null(secondAuthor.Uri);
SyndicationPerson thirdAuthor = item.Authors[2];
Assert.Empty(thirdAuthor.AttributeExtensions);
Assert.Empty(thirdAuthor.ElementExtensions);
Assert.Equal("author_email", thirdAuthor.Email);
Assert.Equal("author_name", thirdAuthor.Name);
Assert.Equal("author_uri", thirdAuthor.Uri);
SyndicationPerson fourthAuthor = item.Authors[3];
Assert.Empty(firstAuthor.AttributeExtensions);
Assert.Empty(firstAuthor.ElementExtensions);
Assert.Null(firstAuthor.Email);
Assert.Null(firstAuthor.Name);
Assert.Null(firstAuthor.Uri);
SyndicationPerson fifthAuthor = item.Authors[4];
Assert.Empty(fifthAuthor.AttributeExtensions);
Assert.Empty(fifthAuthor.ElementExtensions);
Assert.Empty(fifthAuthor.Email);
Assert.Null(fifthAuthor.Name);
Assert.Null(fifthAuthor.Uri);
SyndicationPerson sixthAuthor = item.Authors[5];
Assert.Empty(sixthAuthor.AttributeExtensions);
Assert.Empty(sixthAuthor.ElementExtensions);
Assert.Equal("email", sixthAuthor.Email);
Assert.Null(sixthAuthor.Name);
Assert.Null(sixthAuthor.Uri);
Assert.Equal(new Uri("/relative", UriKind.Relative), item.BaseUri);
SyndicationCategory firstCategory = item.Categories[0];
Assert.Empty(firstCategory.AttributeExtensions);
Assert.Empty(firstCategory.ElementExtensions);
Assert.Null(firstCategory.Name);
Assert.Null(firstCategory.Scheme);
Assert.Null(firstCategory.Label);
SyndicationCategory secondCategory = item.Categories[1];
Assert.Empty(secondCategory.AttributeExtensions);
Assert.Empty(secondCategory.ElementExtensions);
Assert.Empty(secondCategory.Name);
Assert.Null(secondCategory.Scheme);
Assert.Null(secondCategory.Label);
SyndicationCategory thirdCategory = item.Categories[2];
Assert.Empty(thirdCategory.AttributeExtensions);
Assert.Empty(thirdCategory.ElementExtensions);
Assert.Equal("category_name", thirdCategory.Name);
Assert.Equal("category_scheme", thirdCategory.Scheme);
Assert.Null(thirdCategory.Label);
TextSyndicationContent content = Assert.IsType<TextSyndicationContent>(item.Content);
Assert.Equal(4, content.AttributeExtensions.Count);
Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name1")]);
Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name2", "content_namespace")]);
Assert.Equal("content_value", content.AttributeExtensions[new XmlQualifiedName("content_name3", "content_namespace")]);
Assert.Equal("", content.AttributeExtensions[new XmlQualifiedName("content_name4", "xmlns")]);
Assert.Equal("content_title", content.Text);
Assert.Equal("html", content.Type);
Assert.Equal(3, item.Contributors.Count);
SyndicationPerson firstContributor = item.Contributors[0];
Assert.Empty(firstContributor.AttributeExtensions);
Assert.Empty(firstContributor.ElementExtensions);
Assert.Null(firstContributor.Email);
Assert.Null(firstContributor.Name);
Assert.Null(firstContributor.Uri);
SyndicationPerson secondContributor = item.Contributors[1];
Assert.Empty(secondContributor.AttributeExtensions);
Assert.Empty(secondContributor.ElementExtensions);
Assert.Null(secondContributor.Email);
Assert.Null(secondContributor.Name);
Assert.Null(secondContributor.Uri);
SyndicationPerson thirdContributor = item.Contributors[2];
Assert.Empty(thirdContributor.AttributeExtensions);
Assert.Empty(thirdContributor.ElementExtensions);
Assert.Equal("contributor_email", thirdContributor.Email);
Assert.Equal("contributor_name", thirdContributor.Name);
Assert.Equal("contributor_uri", thirdContributor.Uri);
Assert.Equal(4, item.Copyright.AttributeExtensions.Count);
Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name1")]);
Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name2", "copyright_namespace")]);
Assert.Equal("copyright_value", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name3", "copyright_namespace")]);
Assert.Equal("", item.Copyright.AttributeExtensions[new XmlQualifiedName("copyright_name4", "xmlns")]);
Assert.Equal("copyright_title", item.Copyright.Text);
Assert.Equal("html", item.Copyright.Type);
Assert.Empty(item.ElementExtensions);
Assert.Equal("id", item.Id);
Assert.Equal(DateTimeOffset.MinValue, item.LastUpdatedTime);
Assert.Equal(13, item.Links.Count);
SyndicationLink firstLink = item.Links[0];
Assert.Empty(firstLink.AttributeExtensions);
Assert.Empty(firstLink.ElementExtensions);
Assert.Equal(0, firstLink.Length);
Assert.Null(firstLink.MediaType);
Assert.Equal("alternate", firstLink.RelationshipType);
Assert.Null(firstLink.Title);
Assert.Empty(firstLink.Uri.OriginalString);
SyndicationLink secondLink = item.Links[1];
Assert.Empty(secondLink.AttributeExtensions);
Assert.Empty(secondLink.ElementExtensions);
Assert.Equal(new Uri("/relative", UriKind.Relative), secondLink.BaseUri);
Assert.Equal(0, secondLink.Length);
Assert.Null(secondLink.MediaType);
Assert.Null(secondLink.RelationshipType);
Assert.Null(secondLink.Title);
Assert.Empty(secondLink.Uri.OriginalString);
SyndicationLink thirdLink = item.Links[2];
Assert.Equal(4, thirdLink.AttributeExtensions.Count);
Assert.Equal("", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name1")]);
Assert.Equal("", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name2", "link_namespace")]);
Assert.Equal("link_value", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name3", "link_namespace")]);
Assert.Equal("", thirdLink.AttributeExtensions[new XmlQualifiedName("link_name4", "xmlns")]);
Assert.Empty(thirdLink.ElementExtensions);
Assert.Equal(new Uri("http://link_url.com/"), thirdLink.BaseUri);
Assert.Equal(10, thirdLink.Length);
Assert.Equal("link_mediaType", thirdLink.MediaType);
Assert.Equal("link_relationshipType", thirdLink.RelationshipType);
Assert.Equal("link_title", thirdLink.Title);
Assert.Equal(new Uri("http://link_uri.com/"), thirdLink.Uri);
SyndicationLink fourthLink = item.Links[3];
if (preserveAttributeExtensions)
{
Assert.Equal(4, fourthLink.AttributeExtensions.Count);
Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name1")]);
Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name2", "enclosure_namespace")]);
Assert.Equal("item_value", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name3", "enclosure_namespace")]);
Assert.Equal("", fourthLink.AttributeExtensions[new XmlQualifiedName("enclosure_name4", "xmlns")]);
}
else
{
Assert.Empty(fourthLink.AttributeExtensions);
}
Assert.Empty(fourthLink.ElementExtensions);
Assert.Equal(new Uri("http://link_url.com/"), fourthLink.BaseUri);
Assert.Equal(10, fourthLink.Length);
Assert.Equal("enclosure_mediaType", fourthLink.MediaType);
Assert.Equal("enclosure", fourthLink.RelationshipType);
Assert.Null(fourthLink.Title);
Assert.Equal(new Uri("http://enclosure_uri.com/"), fourthLink.Uri);
SyndicationLink fifthLink = item.Links[4];
Assert.Empty(fifthLink.AttributeExtensions);
Assert.Empty(fifthLink.ElementExtensions);
Assert.Equal(new Uri("/relative", UriKind.Relative), fifthLink.BaseUri);
Assert.Equal(0, fifthLink.Length);
Assert.Null(fifthLink.MediaType);
Assert.Equal("enclosure", fifthLink.RelationshipType);
Assert.Null(fifthLink.Title);
Assert.Empty(fifthLink.Uri.OriginalString);
SyndicationLink sixthLink = item.Links[5];
Assert.Equal(4, sixthLink.AttributeExtensions.Count);
Assert.Equal("", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name1")]);
Assert.Equal("", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name2", "alternate_namespace")]);
Assert.Equal("alternate_value", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name3", "alternate_namespace")]);
Assert.Equal("", sixthLink.AttributeExtensions[new XmlQualifiedName("alternate_name4", "xmlns")]);
Assert.Empty(sixthLink.ElementExtensions);
Assert.Equal(new Uri("http://alternate_url.com/"), sixthLink.BaseUri);
Assert.Equal(10, sixthLink.Length);
Assert.Equal("alternate_mediaType", sixthLink.MediaType);
Assert.Equal("alternate", sixthLink.RelationshipType);
Assert.Equal("alternate_title", sixthLink.Title);
Assert.Equal(new Uri("http://alternate_uri.com/"), sixthLink.Uri);
Assert.Equal(DateTimeOffset.MinValue, item.PublishDate);
SyndicationLink seventhLink = item.Links[6];
Assert.Empty(seventhLink.AttributeExtensions);
Assert.Empty(seventhLink.ElementExtensions);
Assert.Equal(new Uri("/relative", UriKind.Relative), seventhLink.BaseUri);
Assert.Equal(0, seventhLink.Length);
Assert.Null(seventhLink.MediaType);
Assert.Null(seventhLink.RelationshipType);
Assert.Null(seventhLink.Title);
Assert.Equal(new Uri("link_href", UriKind.Relative), seventhLink.Uri);
SyndicationLink eighthLink = item.Links[7];
Assert.Empty(eighthLink.AttributeExtensions);
Assert.Empty(eighthLink.ElementExtensions);
Assert.Equal(0, eighthLink.Length);
Assert.Null(eighthLink.MediaType);
Assert.Equal("enclosure", eighthLink.RelationshipType);
Assert.Null(eighthLink.Title);
Assert.Null(eighthLink.Uri);
SyndicationLink ninthLink = item.Links[8];
Assert.Empty(ninthLink.AttributeExtensions);
Assert.Empty(ninthLink.ElementExtensions);
Assert.Equal(0, ninthLink.Length);
Assert.Null(ninthLink.MediaType);
Assert.Equal("enclosure", ninthLink.RelationshipType);
Assert.Null(ninthLink.Title);
Assert.Null(ninthLink.Uri);
SyndicationLink tenthLink = item.Links[9];
Assert.Empty(tenthLink.AttributeExtensions);
Assert.Empty(tenthLink.ElementExtensions);
Assert.Equal(0, tenthLink.Length);
Assert.Null(tenthLink.MediaType);
Assert.Equal("enclosure", tenthLink.RelationshipType);
Assert.Null(tenthLink.Title);
Assert.Null(tenthLink.Uri);
SyndicationLink eleventhLink = item.Links[10];
Assert.Empty(eleventhLink.AttributeExtensions);
Assert.Empty(eleventhLink.ElementExtensions);
Assert.Equal(0, eleventhLink.Length);
Assert.Null(eleventhLink.MediaType);
Assert.Equal("alternate", eleventhLink.RelationshipType);
Assert.Null(eleventhLink.Title);
Assert.Empty(eleventhLink.Uri.OriginalString);
SyndicationLink twelfthLink = item.Links[11];
Assert.Empty(twelfthLink.AttributeExtensions);
Assert.Empty(twelfthLink.ElementExtensions);
Assert.Equal(0, twelfthLink.Length);
Assert.Null(twelfthLink.MediaType);
Assert.Equal("alternate", twelfthLink.RelationshipType);
Assert.Null(twelfthLink.Title);
Assert.Empty(twelfthLink.Uri.OriginalString);
SyndicationLink thirteenthLink = item.Links[12];
if (preserveAttributeExtensions)
{
Assert.Equal(5, thirteenthLink.AttributeExtensions.Count);
Assert.Equal("true", thirteenthLink.AttributeExtensions[new XmlQualifiedName("ignored", "http://www.w3.org/XML/1998/namespace")]);
Assert.Equal("", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name1")]);
Assert.Equal("", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name2", "alternate_namespace")]);
Assert.Equal("alternate_value", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name3", "alternate_namespace")]);
Assert.Equal("", thirteenthLink.AttributeExtensions[new XmlQualifiedName("alternate_name4", "xmlns")]);
}
else
{
Assert.Empty(thirteenthLink.AttributeExtensions);
}
Assert.Empty(thirteenthLink.ElementExtensions);
Assert.Equal(0, thirteenthLink.Length);
Assert.Null(thirteenthLink.MediaType);
Assert.Equal("alternate", thirteenthLink.RelationshipType);
Assert.Null(thirteenthLink.Title);
Assert.Equal(new Uri("http://microsoft.com"), thirteenthLink.Uri);
Assert.Null(item.SourceFeed);
Assert.Empty(item.Summary.AttributeExtensions);
Assert.Equal("summary_title", item.Summary.Text);
Assert.Equal("text", item.Summary.Type);
Assert.Empty(item.Title.AttributeExtensions);
Assert.Equal("title_title", item.Title.Text);
Assert.Equal("text", item.Title.Type);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadFrom_EmptySource_ReturnsExpected(bool preserveElementExtensions)
{
VerifyRead(@"<item><source></source></item>", preserveElementExtensions, preserveElementExtensions, item =>
{
Assert.Empty(item.AttributeExtensions);
Assert.Empty(item.Authors);
Assert.Null(item.BaseUri);
Assert.Empty(item.Categories);
Assert.Null(item.Content);
Assert.Null(item.Copyright);
Assert.Empty(item.ElementExtensions);
Assert.Null(item.Id);
Assert.Equal(default, item.LastUpdatedTime);
Assert.Empty(item.Links);
Assert.Equal(default, item.PublishDate);
Assert.NotNull(item.SourceFeed);
Assert.Null(item.Summary);
Assert.Null(item.Title);
});
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ReadFrom_EmptyItem_ReturnsExpected(bool preserveElementExtensions)
{
VerifyRead(@"<item></item>", preserveElementExtensions, preserveElementExtensions, item =>
{
Assert.Empty(item.AttributeExtensions);
Assert.Empty(item.Authors);
Assert.Null(item.BaseUri);
Assert.Empty(item.Categories);
Assert.Null(item.Content);
Assert.Null(item.Copyright);
Assert.Empty(item.ElementExtensions);
Assert.Null(item.Id);
Assert.Equal(default, item.LastUpdatedTime);
Assert.Empty(item.Links);
Assert.Equal(default, item.PublishDate);
Assert.Null(item.SourceFeed);
Assert.Null(item.Summary);
Assert.Null(item.Title);
});
}
private static void VerifyRead(string xmlString, bool preserveAttributeExtensions, bool preserveElementExtensions, Action<SyndicationItem> verifyAction)
{
// ReadFrom.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter()
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
formatter.ReadFrom(reader);
verifyAction(formatter.Item);
}
// ReadXml.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
reader.MoveToContent();
var formatter = new Rss20ItemFormatter()
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
((IXmlSerializable)formatter).ReadXml(reader);
verifyAction(formatter.Item);
}
// Derived ReadFrom.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter(typeof(SyndicationItemSubclass))
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
formatter.ReadFrom(reader);
verifyAction(formatter.Item);
}
// Derived ReadXml.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
reader.MoveToContent();
var formatter = new Rss20ItemFormatter(typeof(SyndicationItemSubclass))
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
((IXmlSerializable)formatter).ReadXml(reader);
verifyAction(formatter.Item);
}
// Generic ReadFrom.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter<SyndicationItem>()
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
formatter.ReadFrom(reader);
verifyAction(formatter.Item);
}
// Generic ReadXml.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
reader.MoveToContent();
var formatter = new Rss20ItemFormatter<SyndicationItem>()
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
((IXmlSerializable)formatter).ReadXml(reader);
verifyAction(formatter.Item);
}
// Generic Derived ReadFrom.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter<SyndicationItemSubclass>()
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
formatter.ReadFrom(reader);
verifyAction(formatter.Item);
}
// Generic Derived ReadXml.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
reader.MoveToContent();
var formatter = new Rss20ItemFormatter<SyndicationItemSubclass>()
{
PreserveAttributeExtensions = preserveAttributeExtensions,
PreserveElementExtensions = preserveElementExtensions
};
((IXmlSerializable)formatter).ReadXml(reader);
verifyAction(formatter.Item);
}
if (preserveAttributeExtensions && preserveElementExtensions)
{
// Load.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
SyndicationItem item = SyndicationItem.Load(reader);
verifyAction(item);
}
// Generic Load.
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
SyndicationItemSubclass item = SyndicationItem.Load<SyndicationItemSubclass>(reader);
verifyAction(item);
}
}
}
[Fact]
public void ReadFrom_NullReader_ThrowsArgumentNullException()
{
var formatter = new Rss20ItemFormatter();
AssertExtensions.Throws<ArgumentNullException>("reader", () => formatter.ReadFrom(null));
}
[Fact]
public void ReadFrom_NullCreatedItem_ThrowsArgumentNullException()
{
using (var stringReader = new StringReader(@"<item></item>"))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new NullCreatedDocumentFormatter();
AssertExtensions.Throws<ArgumentNullException>("item", () => formatter.ReadFrom(reader));
}
}
[Theory]
[InlineData(@"<different></different>")]
[InlineData(@"<item xmlns=""different""></item>")]
public void ReadFrom_CantRead_ThrowsXmlException(string xmlString)
{
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter();
Assert.Throws<XmlException>(() => formatter.ReadFrom(reader));
}
}
[Theory]
[InlineData("<item />")]
[InlineData("<item></item>")]
[InlineData(@"<app:item xmlns:app=""http://www.w3.org/2005/Atom""></app:item>")]
[InlineData(@"<item xmlns=""different""></item>")]
public void ReadXml_ValidReader_Success(string xmlString)
{
using (var stringReader = new StringReader(xmlString))
using (XmlReader reader = XmlReader.Create(stringReader))
{
reader.MoveToContent();
var formatter = new Rss20ItemFormatter();
((IXmlSerializable)formatter).ReadXml(reader);
SyndicationItem item = formatter.Item;
Assert.Empty(item.AttributeExtensions);
Assert.Empty(item.Authors);
Assert.Null(item.BaseUri);
Assert.Empty(item.Categories);
Assert.Null(item.Content);
Assert.Null(item.Copyright);
Assert.Empty(item.ElementExtensions);
Assert.Null(item.Id);
Assert.Equal(default, item.LastUpdatedTime);
Assert.Empty(item.Links);
Assert.Equal(default, item.PublishDate);
Assert.Null(item.SourceFeed);
Assert.Null(item.Summary);
Assert.Null(item.Title);
}
}
[Fact]
public void ReadXml_NullReader_ThrowsArgumentNullException()
{
IXmlSerializable formatter = new Rss20ItemFormatter();
AssertExtensions.Throws<ArgumentNullException>("reader", () => formatter.ReadXml(null));
}
[Fact]
public void ReadXml_NullCreatedItem_ThrowsArgumentNullException()
{
using (var stringReader = new StringReader(@"<item></item>"))
using (XmlReader reader = XmlReader.Create(stringReader))
{
reader.MoveToContent();
IXmlSerializable formatter = new NullCreatedDocumentFormatter();
AssertExtensions.Throws<ArgumentNullException>("item", () => formatter.ReadXml(reader));
}
}
[Fact]
public void ReadXml_ThrowsArgumentException_RethrowsAsXmlException()
{
var reader = new ThrowingXmlReader(new ArgumentException());
IXmlSerializable formatter = new Rss20ItemFormatter();
Assert.Throws<XmlException>(() => formatter.ReadXml(reader));
}
[Fact]
public void ReadXml_ThrowsFormatException_RethrowsAsXmlException()
{
var reader = new ThrowingXmlReader(new FormatException());
IXmlSerializable formatter = new Rss20ItemFormatter();
Assert.Throws<XmlException>(() => formatter.ReadXml(reader));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Custom date parsing added in .NET Core changes this behaviour")]
public void Read_InvalidPublishDate_GetThrowsXmlExcepton()
{
using (var stringReader = new StringReader(@"<item><pubDate>invalid</pubDate></item>"))
using (XmlReader reader = XmlReader.Create(stringReader))
{
var formatter = new Rss20ItemFormatter();
formatter.ReadFrom(reader);
Assert.Throws<XmlException>(() => formatter.Item.PublishDate);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void PreserveAttributeExtensions_Set_GetReturnsExpected(bool preserveAttributeExtensions)
{
var formatter = new Rss20ItemFormatter() { PreserveAttributeExtensions = preserveAttributeExtensions };
Assert.Equal(preserveAttributeExtensions, formatter.PreserveAttributeExtensions);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void PreserveElementExtensions_Set_GetReturnsExpected(bool preserveElementExtensions)
{
var formatter = new Rss20ItemFormatter() { PreserveElementExtensions = preserveElementExtensions };
Assert.Equal(preserveElementExtensions, formatter.PreserveElementExtensions);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void SerializeExtensionsAsAtom_Set_GetReturnsExpected(bool serializeExtensionsAsAtom)
{
var formatter = new Rss20ItemFormatter() { SerializeExtensionsAsAtom = serializeExtensionsAsAtom };
Assert.Equal(serializeExtensionsAsAtom, formatter.SerializeExtensionsAsAtom);
}
[Fact]
public void CreateItemInstance_NonGeneric_Success()
{
var formatter = new Formatter();
SyndicationItem item = Assert.IsType<SyndicationItem>(formatter.CreateItemInstanceEntryPoint());
Assert.Empty(item.AttributeExtensions);
Assert.Empty(item.Authors);
Assert.Null(item.BaseUri);
Assert.Empty(item.Categories);
Assert.Null(item.Content);
Assert.Null(item.Copyright);
Assert.Empty(item.ElementExtensions);
Assert.Null(item.Id);
Assert.Equal(default, item.LastUpdatedTime);
Assert.Empty(item.Links);
Assert.Equal(default, item.PublishDate);
Assert.Null(item.SourceFeed);
Assert.Null(item.Summary);
Assert.Null(item.Title);
var typedFormatter = new Formatter(typeof(SyndicationItemSubclass));
item = Assert.IsType<SyndicationItemSubclass>(typedFormatter.CreateItemInstanceEntryPoint());
Assert.Empty(item.AttributeExtensions);
Assert.Empty(item.Authors);
Assert.Null(item.BaseUri);
Assert.Empty(item.Categories);
Assert.Null(item.Content);
Assert.Null(item.Copyright);
Assert.Empty(item.ElementExtensions);
Assert.Null(item.Id);
Assert.Equal(default, item.LastUpdatedTime);
Assert.Empty(item.Links);
Assert.Equal(default, item.PublishDate);
Assert.Null(item.SourceFeed);
Assert.Null(item.Summary);
Assert.Null(item.Title);
}
[Fact]
public void CreateItemInstance_Generic_Success()
{
var formatter = new GenericFormatter<SyndicationItem>();
SyndicationItem item = Assert.IsType<SyndicationItem>(formatter.CreateItemInstanceEntryPoint());
Assert.Empty(item.AttributeExtensions);
Assert.Empty(item.Authors);
Assert.Null(item.BaseUri);
Assert.Empty(item.Categories);
Assert.Null(item.Content);
Assert.Null(item.Copyright);
Assert.Empty(item.ElementExtensions);
Assert.Null(item.Id);
Assert.Equal(default, item.LastUpdatedTime);
Assert.Empty(item.Links);
Assert.Equal(default, item.PublishDate);
Assert.Null(item.SourceFeed);
Assert.Null(item.Summary);
Assert.Null(item.Title);
var typedFormatter = new GenericFormatter<SyndicationItemSubclass>();
item = Assert.IsType<SyndicationItemSubclass>(typedFormatter.CreateItemInstanceEntryPoint());
Assert.Empty(item.AttributeExtensions);
Assert.Empty(item.Authors);
Assert.Null(item.BaseUri);
Assert.Empty(item.Categories);
Assert.Null(item.Content);
Assert.Null(item.Copyright);
Assert.Empty(item.ElementExtensions);
Assert.Null(item.Id);
Assert.Equal(default, item.LastUpdatedTime);
Assert.Empty(item.Links);
Assert.Equal(default, item.PublishDate);
Assert.Null(item.SourceFeed);
Assert.Null(item.Summary);
Assert.Null(item.Title);
}
public class SyndicationItemSubclass : SyndicationItem { }
public class SyndicationItemTryParseTrueSubclass : SyndicationItem
{
protected override bool TryParseAttribute(string name, string ns, string value, string version) => true;
protected override bool TryParseElement(XmlReader reader, string version)
{
reader.Skip();
return true;
}
protected override SyndicationCategory CreateCategory() => new SyndicationCategoryTryParseTrueSubclass();
protected override SyndicationPerson CreatePerson() => new SyndicationPersonTryParseTrueSubclass();
protected override SyndicationLink CreateLink() => new SyndicationLinkTryParseTrueSubclass();
}
public class SyndicationCategoryTryParseTrueSubclass : SyndicationCategory
{
protected override bool TryParseAttribute(string name, string ns, string value, string version) => true;
protected override bool TryParseElement(XmlReader reader, string version)
{
reader.Skip();
return true;
}
}
public class SyndicationPersonTryParseTrueSubclass : SyndicationPerson
{
protected override bool TryParseAttribute(string name, string ns, string value, string version) => true;
protected override bool TryParseElement(XmlReader reader, string version)
{
reader.Skip();
return true;
}
}
public class SyndicationLinkTryParseTrueSubclass : SyndicationLink
{
protected override bool TryParseAttribute(string name, string ns, string value, string version) => true;
protected override bool TryParseElement(XmlReader reader, string version)
{
reader.Skip();
return true;
}
}
public class NullCreatedDocumentFormatter : Rss20ItemFormatter
{
protected override SyndicationItem CreateItemInstance() => null;
}
public class Formatter : Rss20ItemFormatter
{
public Formatter() : base() { }
public Formatter(SyndicationItem itemToWrite) : base(itemToWrite) { }
public Formatter(SyndicationItem itemToWrite, bool serializeExtensionsAsAtom) : base(itemToWrite, serializeExtensionsAsAtom) { }
public Formatter(Type itemTypeToCreate) : base(itemTypeToCreate) { }
public Type ItemTypeEntryPoint => ItemType;
public SyndicationItem CreateItemInstanceEntryPoint() => CreateItemInstance();
}
public class GenericFormatter<T> : Rss20ItemFormatter<T> where T : SyndicationItem, new()
{
public GenericFormatter() : base() { }
public GenericFormatter(T itemToWrite) : base(itemToWrite) { }
public GenericFormatter(T itemToWrite, bool serializeExtensionsAsAtom) : base(itemToWrite, serializeExtensionsAsAtom) { }
public Type ItemTypeEntryPoint => ItemType;
public SyndicationItem CreateItemInstanceEntryPoint() => CreateItemInstance();
}
[DataContract]
public class ExtensionObject
{
[DataMember]
public int Value { get; set; }
}
}
}
| |
// -----------------------------------------------------------------------
// Copyright (c) David Kean. All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using AudioSwitcher.IO;
using AudioSwitcher.Presentation.Drawing.Interop;
using AudioSwitcher.Win32.InteropServices;
namespace AudioSwitcher.Presentation.Drawing
{
/// <summary>
/// Get icon resources (RT_GROUP_ICON and RT_ICON) from an executable module (either a .dll or an .exe file).
/// </summary>
internal class IconExtractor : IDisposable
{
private readonly ReadOnlyCollection<ResourceName> _iconNames;
private readonly SafeModuleHandle _moduleHandle;
public IconExtractor(SafeModuleHandle moduleHandle, IList<ResourceName> iconNames)
{
_moduleHandle = moduleHandle;
_iconNames = new ReadOnlyCollection<ResourceName>(iconNames);
}
public SafeModuleHandle ModuleHandle
{
get { return _moduleHandle; }
}
/// <summary>
/// Gets a list of icons resource names RT_GROUP_ICON;
/// </summary>
public ReadOnlyCollection<ResourceName> IconNames
{
get { return _iconNames; }
}
public Icon GetIconByIndex(int index)
{
if (index < 0 || index >= IconNames.Count)
{
if (IconNames.Count > 0)
throw new ArgumentOutOfRangeException("index", index, "Index should be in the range (0-" + IconNames.Count.ToString() + ").");
else
throw new ArgumentOutOfRangeException("index", index, "No icons in the list.");
}
return GetIconFromLib(index);
}
public static IconExtractor Open(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
if (fileName.Length == 0)
throw new ArgumentException(null, "fileName");
fileName = Path.GetFullPath(fileName);
fileName = Environment.ExpandEnvironmentVariables(fileName);
SafeModuleHandle moduleHandle = DllImports.LoadLibraryEx(fileName, IntPtr.Zero, LoadLibraryExFlags.LOAD_LIBRARY_AS_DATAFILE);
if (moduleHandle.IsInvalid)
throw Win32Marshal.GetExceptionForLastWin32Error(fileName);
var iconNames = new List<ResourceName>();
DllImports.EnumResourceNames(moduleHandle, ResourceTypes.RT_GROUP_ICON, (hModule, lpszType, lpszName, lParam) =>
{
if (lpszType == ResourceTypes.RT_GROUP_ICON)
iconNames.Add(new ResourceName(lpszName));
return true;
},
IntPtr.Zero);
return new IconExtractor(moduleHandle, iconNames);
}
public static Icon ExtractIconByIndex(string fileName, int index)
{
using (var extractor = IconExtractor.Open(fileName))
{
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (index >= extractor.IconNames.Count)
return null;
return extractor.GetIconByIndex(index);
}
}
public static Icon ExtractIconById(string fileName, int id)
{
using (var extractor = IconExtractor.Open(fileName))
{
if (id < 0)
throw new ArgumentOutOfRangeException("index");
int count = extractor.IconNames.Count;
for (int i = 0; i < count; i++)
{
ResourceName name = extractor.IconNames[i];
if (name.Id != null && name.Id == id)
{
return extractor.GetIconByIndex(i);
}
}
}
return null;
}
/// <summary>
/// Gets a System.Drawing.Icon that represents RT_GROUP_ICON at the givin index from the executable module.
/// </summary>
/// <param name="index">The index of the RT_GROUP_ICON in the executable module.</param>
/// <returns>Returns System.Drawing.Icon.</returns>
private Icon GetIconFromLib(int index)
{
byte[] resourceData = GetResourceData(ModuleHandle, IconNames[index], ResourceTypes.RT_GROUP_ICON);
//Convert the resouce into an .ico file image.
using (var inputStream = new MemoryStream(resourceData))
using (var destStream = new MemoryStream())
{
//Read the GroupIconDir header.
GroupIconDir grpDir = inputStream.Read<GroupIconDir>();
int numEntries = grpDir.Count;
int iconImageOffset = IconInfo.SizeOfIconDir + numEntries * IconInfo.SizeOfIconDirEntry;
destStream.Write<IconDir>(grpDir.ToIconDir());
for (int i = 0; i < numEntries; i++)
{
//Read the GroupIconDirEntry.
GroupIconDirEntry grpEntry = inputStream.Read<GroupIconDirEntry>();
//Write the IconDirEntry.
destStream.Seek(IconInfo.SizeOfIconDir + i * IconInfo.SizeOfIconDirEntry, SeekOrigin.Begin);
destStream.Write<IconDirEntry>(grpEntry.ToIconDirEntry(iconImageOffset));
//Get the icon image raw data and write it to the stream.
byte[] imgBuf = GetResourceData(ModuleHandle, grpEntry.ID, ResourceTypes.RT_ICON);
destStream.Seek(iconImageOffset, SeekOrigin.Begin);
destStream.Write(imgBuf, 0, imgBuf.Length);
//Append the iconImageOffset.
iconImageOffset += imgBuf.Length;
}
destStream.Seek(0, SeekOrigin.Begin);
return new Icon(destStream);
}
}
/// <summary>
/// Extracts the raw data of the resource from the module.
/// </summary>
/// <param name="hModule">The module handle.</param>
/// <param name="resourceName">The name of the resource.</param>
/// <param name="resourceType">The type of the resource.</param>
/// <returns>The resource raw data.</returns>
private static byte[] GetResourceData(SafeModuleHandle hModule, ResourceName resourceName, ResourceTypes resourceType)
{
//Find the resource in the module.
IntPtr hResInfo = IntPtr.Zero;
try { hResInfo = DllImports.FindResource(hModule, resourceName.Value, resourceType); }
finally { resourceName.Dispose(); }
if (hResInfo == IntPtr.Zero)
{
throw new Win32Exception();
}
//Load the resource.
IntPtr hResData = DllImports.LoadResource(hModule, hResInfo);
if (hResData == IntPtr.Zero)
{
throw new Win32Exception();
}
//Lock the resource to read data.
IntPtr hGlobal = DllImports.LockResource(hResData);
if (hGlobal == IntPtr.Zero)
{
throw new Win32Exception();
}
//Get the resource size.
int resSize = DllImports.SizeofResource(hModule, hResInfo);
if (resSize == 0)
{
throw new Win32Exception();
}
//Allocate the requested size.
byte[] buf = new byte[resSize];
//Copy the resource data into our buffer.
Marshal.Copy(hGlobal, buf, 0, buf.Length);
return buf;
}
/// <summary>
/// Extracts the raw data of the resource from the module.
/// </summary>
/// <param name="hModule">The module handle.</param>
/// <param name="resourceId">The identifier of the resource.</param>
/// <param name="resourceType">The type of the resource.</param>
/// <returns>The resource raw data.</returns>
private static byte[] GetResourceData(SafeModuleHandle hModule, int resourceId, ResourceTypes resourceType)
{
//Find the resource in the module.
IntPtr hResInfo = DllImports.FindResource(hModule, (IntPtr) resourceId, resourceType);
if (hResInfo == IntPtr.Zero)
{
throw new Win32Exception();
}
//Load the resource.
IntPtr hResData = DllImports.LoadResource(hModule, hResInfo);
if (hResData == IntPtr.Zero)
{
throw new Win32Exception();
}
//Lock the resource to read data.
IntPtr hGlobal = DllImports.LockResource(hResData);
if (hGlobal == IntPtr.Zero)
{
throw new Win32Exception();
}
//Get the resource size.
int resSize = DllImports.SizeofResource(hModule, hResInfo);
if (resSize == 0)
{
throw new Win32Exception();
}
//Allocate the requested size.
byte[] buf = new byte[resSize];
//Copy the resource data into our buffer.
Marshal.Copy(hGlobal, buf, 0, buf.Length);
return buf;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_moduleHandle.Dispose();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
namespace Xamarin.Forms.Pages
{
internal class DataSourceList : IList<IDataItem>, IReadOnlyList<IDataItem>, INotifyCollectionChanged
{
readonly List<int> _maskedIndexes = new List<int>(); // Indices
readonly HashSet<string> _maskedKeys = new HashSet<string>();
IList<IDataItem> _mainList;
public IList<IDataItem> MainList
{
get { return _mainList; }
set
{
var observable = _mainList as INotifyCollectionChanged;
if (observable != null)
observable.CollectionChanged -= OnMainCollectionChanged;
_mainList = value;
observable = _mainList as INotifyCollectionChanged;
if (observable != null)
observable.CollectionChanged += OnMainCollectionChanged;
_maskedIndexes.Clear();
for (var i = 0; i < _mainList.Count; i++)
{
IDataItem data = _mainList[i];
if (_maskedKeys.Contains(data.Name))
_maskedIndexes.Add(i);
}
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
public IEnumerable<string> MaskedKeys => _maskedKeys;
public void Add(IDataItem item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(IDataItem item)
{
return MainList != null && !_maskedKeys.Contains(item.Name) && MainList.Contains(item);
}
public void CopyTo(IDataItem[] array, int arrayIndex)
{
throw new NotSupportedException();
}
public int Count
{
get
{
if (MainList == null)
return 0;
var result = 0;
result += MainList.Count;
result -= _maskedIndexes.Count;
return result;
}
}
public bool IsReadOnly => true;
public bool Remove(IDataItem item)
{
throw new NotSupportedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<IDataItem> GetEnumerator()
{
var index = 0;
if (MainList == null)
yield break;
foreach (IDataItem item in MainList)
{
if (!_maskedIndexes.Contains(index))
yield return item;
index++;
}
}
public int IndexOf(IDataItem item)
{
if (_maskedKeys.Contains(item.Name))
return -1;
if (MainList != null)
{
int result = MainList.IndexOf(item);
if (result >= 0)
return PublicIndexFromMainIndex(result);
}
return -1;
}
public void Insert(int index, IDataItem item)
{
throw new NotSupportedException();
}
public IDataItem this[int index]
{
get
{
foreach (int i in _maskedIndexes)
{
if (i <= index)
index++;
}
if (_mainList == null)
throw new IndexOutOfRangeException();
return _mainList[index];
}
set { throw new NotSupportedException(); }
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public void MaskKey(string key)
{
if (_maskedKeys.Contains(key) || _mainList == null)
return;
_maskedKeys.Add(key);
var index = 0;
foreach (IDataItem item in _mainList)
{
if (item.Name == key)
{
// We need to keep our indexes list sorted, so we insert everything pre-sorted
var added = false;
for (var i = 0; i < _maskedIndexes.Count; i++)
{
if (_maskedIndexes[i] > index)
{
_maskedIndexes.Insert(i, index);
added = true;
break;
}
}
if (!added)
_maskedIndexes.Add(index);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, PublicIndexFromMainIndex(index)));
break;
}
index++;
}
}
public void UnmaskKey(string key)
{
_maskedKeys.Remove(key);
if (_mainList == null)
return;
var index = 0;
foreach (IDataItem item in _mainList)
{
if (item.Name == key)
{
bool removed = _maskedIndexes.Remove(index);
if (removed)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, PublicIndexFromMainIndex(index)));
}
break;
}
index++;
}
}
protected void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
{
CollectionChanged?.Invoke(this, args);
}
void OnMainCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
// much complexity to be had here
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, args.NewItems, PublicIndexFromMainIndex(args.NewStartingIndex)));
break;
case NotifyCollectionChangedAction.Move:
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Move, args.OldItems, PublicIndexFromMainIndex(args.NewStartingIndex),
PublicIndexFromMainIndex(args.OldStartingIndex)));
break;
case NotifyCollectionChangedAction.Remove:
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, args.OldItems, PublicIndexFromMainIndex(args.OldStartingIndex)));
break;
case NotifyCollectionChangedAction.Replace:
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, args.NewItems, args.OldItems, PublicIndexFromMainIndex(args.OldStartingIndex)));
break;
case NotifyCollectionChangedAction.Reset:
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
int PublicIndexFromMainIndex(int index)
{
var count = 0;
for (var x = 0; x < _maskedIndexes.Count; x++)
{
int i = _maskedIndexes[x];
if (i < index)
count++;
}
return index - count;
}
}
}
| |
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
using System;
namespace SevenZip.Compression.RangeCoder
{
class Encoder
{
public const uint kTopValue = (1 << 24);
System.IO.Stream Stream;
public UInt64 Low;
public uint Range;
uint _cacheSize;
byte _cache;
long StartPosition;
public void SetStream(System.IO.Stream stream)
{
Stream = stream;
}
public void ReleaseStream()
{
Stream = null;
}
public void Init()
{
StartPosition = Stream.Position;
Low = 0;
Range = 0xFFFFFFFF;
_cacheSize = 1;
_cache = 0;
}
public void FlushData()
{
for (int i = 0; i < 5; i++)
ShiftLow();
}
public void FlushStream()
{
Stream.Flush();
}
public void CloseStream()
{
Stream.Close();
}
public void Encode(uint start, uint size, uint total)
{
Low += start * (Range /= total);
Range *= size;
while (Range < kTopValue)
{
Range <<= 8;
ShiftLow();
}
}
public void ShiftLow()
{
if ((uint)Low < (uint)0xFF000000 || (uint)(Low >> 32) == 1)
{
byte temp = _cache;
do
{
Stream.WriteByte((byte)(temp + (Low >> 32)));
temp = 0xFF;
}
while (--_cacheSize != 0);
_cache = (byte)(((uint)Low) >> 24);
}
_cacheSize++;
Low = ((uint)Low) << 8;
}
public void EncodeDirectBits(uint v, int numTotalBits)
{
for (int i = numTotalBits - 1; i >= 0; i--)
{
Range >>= 1;
if (((v >> i) & 1) == 1)
Low += Range;
if (Range < kTopValue)
{
Range <<= 8;
ShiftLow();
}
}
}
public void EncodeBit(uint size0, int numTotalBits, uint symbol)
{
uint newBound = (Range >> numTotalBits) * size0;
if (symbol == 0)
Range = newBound;
else
{
Low += newBound;
Range -= newBound;
}
while (Range < kTopValue)
{
Range <<= 8;
ShiftLow();
}
}
public long GetProcessedSizeAdd()
{
return _cacheSize +
Stream.Position - StartPosition + 4;
// (long)Stream.GetProcessedSize();
}
}
class Decoder
{
public const uint kTopValue = (1 << 24);
public uint Range;
public uint Code;
// public Buffer.InBuffer Stream = new Buffer.InBuffer(1 << 16);
public System.IO.Stream Stream;
public void Init(System.IO.Stream stream)
{
// Stream.Init(stream);
Stream = stream;
Code = 0;
Range = 0xFFFFFFFF;
for (int i = 0; i < 5; i++)
Code = (Code << 8) | (byte)Stream.ReadByte();
}
public void ReleaseStream()
{
// Stream.ReleaseStream();
Stream = null;
}
public void CloseStream()
{
Stream.Close();
}
public void Normalize()
{
while (Range < kTopValue)
{
Code = (Code << 8) | (byte)Stream.ReadByte();
Range <<= 8;
}
}
public void Normalize2()
{
if (Range < kTopValue)
{
Code = (Code << 8) | (byte)Stream.ReadByte();
Range <<= 8;
}
}
public uint GetThreshold(uint total)
{
return Code / (Range /= total);
}
public void Decode(uint start, uint size, uint total)
{
Code -= start * Range;
Range *= size;
Normalize();
}
public uint DecodeDirectBits(int numTotalBits)
{
uint range = Range;
uint code = Code;
uint result = 0;
for (int i = numTotalBits; i > 0; i--)
{
range >>= 1;
/*
result <<= 1;
if (code >= range)
{
code -= range;
result |= 1;
}
*/
uint t = (code - range) >> 31;
code -= range & (t - 1);
result = (result << 1) | (1 - t);
if (range < kTopValue)
{
code = (code << 8) | (byte)Stream.ReadByte();
range <<= 8;
}
}
Range = range;
Code = code;
return result;
}
public uint DecodeBit(uint size0, int numTotalBits)
{
uint newBound = (Range >> numTotalBits) * size0;
uint symbol;
if (Code < newBound)
{
symbol = 0;
Range = newBound;
}
else
{
symbol = 1;
Code -= newBound;
Range -= newBound;
}
Normalize();
return symbol;
}
// ulong GetProcessedSize() {return Stream.GetProcessedSize(); }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using VRageMath;
using Sandbox.ModAPI;
using VRage.ModAPI;
using VRage.Utils;
using VRage.Game;
using VRage.Game.ModAPI;
using Sandbox.Game.Entities;
//using VRage.Game.ModAPI;
using NaniteConstructionSystem.Entities.Beacons;
namespace NaniteConstructionSystem.Particles
{
/// <summary>
/// A particle's path has a start and end, but the start and end may change during it's journey, so path positions need to change as those
/// positions relative to one another change. The deviation must always remain the same, but the actual path position may change slightly as things
/// move around.
/// </summary>
public class ParticleRelativePath
{
private int m_count;
private float m_deviationSize;
private Vector3D m_currentStart;
private Vector3D m_currentEnd;
private List<Vector3D> m_pathPoints;
private List<Vector3D> m_deviations;
private List<Vector3D> m_staticPathList;
private bool m_shrinkDeviation;
private object m_start;
private object m_end;
public ParticleRelativePath(object start, object end, int count, float deviationSize, bool shrinkDeviation = false, List<Vector3D> staticPathList = null)
{
m_start = start;
m_end = end;
m_count = count;
m_deviationSize = deviationSize;
m_currentStart = GetPosition(start);
m_currentEnd = GetPosition(end);
m_pathPoints = new List<Vector3D>();
m_deviations = new List<Vector3D>();
m_staticPathList = staticPathList;
m_shrinkDeviation = shrinkDeviation;
GenerateInitialPoints();
}
private void GenerateInitialPoints()
{
Vector3D start = GetPosition(m_start);
Vector3D end = GetPosition(m_end);
Vector3D normal = Vector3D.Zero;
m_currentStart = start;
m_currentEnd = end;
if (end != start)
normal = Vector3.Normalize(end - start);
m_pathPoints.Add(start);
m_deviations.Add(Vector3D.Zero);
BoundingSphereD sphere = new BoundingSphereD(Vector3D.Zero, m_deviationSize * 2);
if (m_staticPathList != null)
{
foreach (var item in m_staticPathList)
{
m_pathPoints.Add(item);
m_deviations.Add(Vector3D.Zero);
//m_deviations.Add(MyUtils.GetRandomBorderPosition(ref sphere));
if (m_start is Vector3D)
m_start = item;
}
m_deviations[m_deviations.Count - 1] = Vector3D.Zero;
}
double length = (end - start).Length() / (m_count - 1);
for (int r = 0; r < m_count - 1; r++)
{
Vector3D point = new Vector3D(start + (normal * length) * r);
m_pathPoints.Add(point);
if (!m_shrinkDeviation)
sphere = new BoundingSphereD(Vector3D.Zero, m_deviationSize);
else
sphere = new BoundingSphereD(Vector3D.Zero, (m_deviationSize / m_count) * ((float)(m_count + 1) - r));
m_deviations.Add(MyUtils.GetRandomBorderPosition(ref sphere));
}
//m_pathPoints[m_pathPoints.Count - 1] = end;
//m_deviations[m_deviations.Count - 1] = Vector3D.Zero;
m_pathPoints.Add(end);
m_deviations.Add(Vector3D.Zero);
}
public void Update()
{
int pos = 0;
try
{
if (GetPosition(m_start) == m_currentStart && GetPosition(m_end) == m_currentEnd)
return;
if (GetPosition(m_start) == Vector3D.Zero || GetPosition(m_end) == Vector3D.Zero)
return;
var start = GetPosition(m_start);
var end = GetPosition(m_end);
if (m_staticPathList != null)
{
pos += m_staticPathList.Count;
}
else
{
m_pathPoints[pos] = start;
pos += 1;
}
Vector3D normal = Vector3D.Zero;
if (end != start)
normal = Vector3.Normalize(end - start);
double length = (end - start).Length() / (m_count - 1);
for (int r = 0; r < m_pathPoints.Count - pos; r++)
{
if (m_shrinkDeviation && m_deviations[r + pos] == Vector3D.Zero)
continue;
m_pathPoints[r + pos] = new Vector3D(start + (normal * length) * r);
}
}
catch(Exception ex)
{
Logging.Instance.WriteLine(string.Format("Update Error - {0} {1}: {2}", m_pathPoints.Count, pos, ex.ToString()));
}
}
public int GetPointCount()
{
return m_pathPoints.Count();
}
public Vector3D GetPoint(int index)
{
var pos = index;
if (index >= GetPointCount())
pos = GetPointCount() - 1;
if (index < 0)
pos = 0;
return m_pathPoints[pos] + m_deviations[pos];
}
private Vector3D GetPosition(object item)
{
if (item is IMyEntity)
{
IMyEntity entity = (IMyEntity)item;
if(item is MyCubeBlock)
{
MyCubeBlock block = (MyCubeBlock)item;
if(block.BlockDefinition.Id.SubtypeName == "LargeNaniteFactory")
{
return Vector3D.Transform(new Vector3D(0f, 1.5f, 0f), entity.WorldMatrix);
}
else if(block.BlockDefinition.Id.SubtypeName == "NaniteUltrasonicHammer")
{
return Vector3D.Transform(new Vector3D(0f, 3.5f, -0.5f), entity.WorldMatrix);
}
}
return entity.GetPosition();
}
else if (item is IMySlimBlock)
{
IMySlimBlock slimBlock = (IMySlimBlock)item;
if (slimBlock.FatBlock != null)
return slimBlock.FatBlock.GetPosition();
var size = slimBlock.CubeGrid.GridSizeEnum == MyCubeSize.Small ? 0.5f : 2.5f;
var destinationPosition = new Vector3D(slimBlock.Position * size);
return Vector3D.Transform(destinationPosition, slimBlock.CubeGrid.WorldMatrix);
}
else if(item is NaniteMiningItem)
{
return (item as NaniteMiningItem).Position;
}
else if (item is Vector3D)
{
return (Vector3D)item;
}
else if (item is IMyPlayer)
{
var destinationPosition = new Vector3D(0f, 2f, 0f);
var targetPosition = Vector3D.Transform(destinationPosition, (item as IMyPlayer).Controller.ControlledEntity.Entity.WorldMatrix);
return targetPosition;
//return (item as IMyPlayer).GetPosition();
}
return Vector3D.Zero;
}
}
}
| |
using BitmapFont = FlatRedBall.Graphics.BitmapFont;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
// Generated Usings
using FrbDemoDuckHunt.Screens;
using FlatRedBall.Graphics;
using FlatRedBall.Math;
using FrbDemoDuckHunt.Entities;
using FlatRedBall;
using FlatRedBall.Screens;
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Graphics.Animation;
#if XNA4 || WINDOWS_8
using Color = Microsoft.Xna.Framework.Color;
#elif FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
#endif
#if FRB_XNA && !MONODROID
using Model = Microsoft.Xna.Framework.Graphics.Model;
#endif
namespace FrbDemoDuckHunt.Entities
{
public partial class Dog : PositionedObject, IDestroyable
{
// This is made global so that static lazy-loaded content can access it.
public static string ContentManagerName
{
get;
set;
}
// Generated Fields
#if DEBUG
static bool HasBeenLoadedWithGlobalContentManager = false;
#endif
public enum VariableState
{
Uninitialized = 0, //This exists so that the first set call actually does something
Unknown = 1, //This exists so that if the entity is actually a child entity and has set a child state, you will get this
Sniffing = 2,
Walking = 3,
Happy = 4,
Jumping = 5,
OneDuck = 6,
TwoDucks = 7,
Laughing = 8
}
protected int mCurrentState = 0;
public VariableState CurrentState
{
get
{
if (Enum.IsDefined(typeof(VariableState), mCurrentState))
{
return (VariableState)mCurrentState;
}
else
{
return VariableState.Unknown;
}
}
set
{
mCurrentState = (int)value;
switch(CurrentState)
{
case VariableState.Uninitialized:
break;
case VariableState.Unknown:
break;
case VariableState.Sniffing:
CurrentChain = "Sniffing";
break;
case VariableState.Walking:
CurrentChain = "Walking";
break;
case VariableState.Happy:
CurrentChain = "Happy";
break;
case VariableState.Jumping:
CurrentChain = "Jumping";
break;
case VariableState.OneDuck:
CurrentChain = "OneDuck";
break;
case VariableState.TwoDucks:
CurrentChain = "TwoDucks";
break;
case VariableState.Laughing:
CurrentChain = "Laugh";
break;
}
}
}
static object mLockObject = new object();
static List<string> mRegisteredUnloads = new List<string>();
static List<string> LoadedContentManagers = new List<string>();
protected static FlatRedBall.Graphics.Animation.AnimationChainList AnimationChainListFile;
private FlatRedBall.Sprite VisibleInstance;
public string CurrentChain
{
get
{
return VisibleInstance.CurrentChainName;
}
set
{
VisibleInstance.CurrentChainName = value;
}
}
public float WalkingSpeed = 20f;
public float JumpingXSpeed = 15f;
public float JumpingYSpeed = 75f;
public float JumpingYDeceleration = -350f;
public float DogDuckMoveSpeed = 86f;
public float WalkingStartY = -44f;
public float WalkingStartX = -95f;
public float DuckStartY = -60f;
public float DuckMaxStartX = 40f;
public float DuckMinStartX = -50f;
public float ShortWalkingLeft = -30f;
protected Layer LayerProvidedByContainer = null;
public Dog(string contentManagerName) :
this(contentManagerName, true)
{
}
public Dog(string contentManagerName, bool addToManagers) :
base()
{
// Don't delete this:
ContentManagerName = contentManagerName;
InitializeEntity(addToManagers);
}
protected virtual void InitializeEntity(bool addToManagers)
{
// Generated Initialize
LoadStaticContent(ContentManagerName);
VisibleInstance = new FlatRedBall.Sprite();
PostInitialize();
if (addToManagers)
{
AddToManagers(null);
}
}
// Generated AddToManagers
public virtual void AddToManagers (Layer layerToAddTo)
{
LayerProvidedByContainer = layerToAddTo;
SpriteManager.AddPositionedObject(this);
AddToManagersBottomUp(layerToAddTo);
CustomInitialize();
}
public virtual void Activity()
{
// Generated Activity
CustomActivity();
// After Custom Activity
}
public virtual void Destroy()
{
// Generated Destroy
SpriteManager.RemovePositionedObject(this);
if (VisibleInstance != null)
{
VisibleInstance.Detach(); SpriteManager.RemoveSprite(VisibleInstance);
}
CustomDestroy();
}
// Generated Methods
public virtual void PostInitialize ()
{
bool oldShapeManagerSuppressAdd = FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = true;
if (VisibleInstance.Parent == null)
{
VisibleInstance.CopyAbsoluteToRelative();
VisibleInstance.AttachTo(this, false);
}
VisibleInstance.PixelSize = 0.5f;
VisibleInstance.AnimationChains = AnimationChainListFile;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = oldShapeManagerSuppressAdd;
}
public virtual void AddToManagersBottomUp (Layer layerToAddTo)
{
// We move this back to the origin and unrotate it so that anything attached to it can just use its absolute position
float oldRotationX = RotationX;
float oldRotationY = RotationY;
float oldRotationZ = RotationZ;
float oldX = X;
float oldY = Y;
float oldZ = Z;
X = 0;
Y = 0;
Z = 0;
RotationX = 0;
RotationY = 0;
RotationZ = 0;
SpriteManager.AddToLayer(VisibleInstance, layerToAddTo);
VisibleInstance.PixelSize = 0.5f;
VisibleInstance.AnimationChains = AnimationChainListFile;
X = oldX;
Y = oldY;
Z = oldZ;
RotationX = oldRotationX;
RotationY = oldRotationY;
RotationZ = oldRotationZ;
CurrentChain = "Walking";
if (Parent == null)
{
X = 0f;
}
else
{
RelativeX = 0f;
}
if (Parent == null)
{
Y = 0f;
}
else
{
RelativeY = 0f;
}
if (Parent == null)
{
Z = 0f;
}
else if (Parent is Camera)
{
RelativeZ = 0f - 40.0f;
}
else
{
RelativeZ = 0f;
}
WalkingSpeed = 20f;
JumpingXSpeed = 15f;
JumpingYSpeed = 75f;
JumpingYDeceleration = -350f;
DogDuckMoveSpeed = 86f;
WalkingStartY = -44f;
WalkingStartX = -95f;
DuckStartY = -60f;
DuckMaxStartX = 40f;
DuckMinStartX = -50f;
ShortWalkingLeft = -30f;
}
public virtual void ConvertToManuallyUpdated ()
{
this.ForceUpdateDependenciesDeep();
SpriteManager.ConvertToManuallyUpdated(this);
SpriteManager.ConvertToManuallyUpdated(VisibleInstance);
}
public static void LoadStaticContent (string contentManagerName)
{
if (string.IsNullOrEmpty(contentManagerName))
{
throw new ArgumentException("contentManagerName cannot be empty or null");
}
ContentManagerName = contentManagerName;
#if DEBUG
if (contentManagerName == FlatRedBallServices.GlobalContentManager)
{
HasBeenLoadedWithGlobalContentManager = true;
}
else if (HasBeenLoadedWithGlobalContentManager)
{
throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global. This can lead to a lot of bugs");
}
#endif
bool registerUnload = false;
if (LoadedContentManagers.Contains(contentManagerName) == false)
{
LoadedContentManagers.Add(contentManagerName);
lock (mLockObject)
{
if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("DogStaticUnload", UnloadStaticContent);
mRegisteredUnloads.Add(ContentManagerName);
}
}
if (!FlatRedBallServices.IsLoaded<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/dog/animationchainlistfile.achx", ContentManagerName))
{
registerUnload = true;
}
AnimationChainListFile = FlatRedBallServices.Load<FlatRedBall.Graphics.Animation.AnimationChainList>(@"content/entities/dog/animationchainlistfile.achx", ContentManagerName);
}
if (registerUnload && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
lock (mLockObject)
{
if (!mRegisteredUnloads.Contains(ContentManagerName) && ContentManagerName != FlatRedBallServices.GlobalContentManager)
{
FlatRedBallServices.GetContentManagerByName(ContentManagerName).AddUnloadMethod("DogStaticUnload", UnloadStaticContent);
mRegisteredUnloads.Add(ContentManagerName);
}
}
}
CustomLoadStaticContent(contentManagerName);
}
public static void UnloadStaticContent ()
{
if (LoadedContentManagers.Count != 0)
{
LoadedContentManagers.RemoveAt(0);
mRegisteredUnloads.RemoveAt(0);
}
if (LoadedContentManagers.Count == 0)
{
if (AnimationChainListFile != null)
{
AnimationChainListFile= null;
}
}
}
static VariableState mLoadingState = VariableState.Uninitialized;
public static VariableState LoadingState
{
get
{
return mLoadingState;
}
set
{
mLoadingState = value;
}
}
public FlatRedBall.Instructions.Instruction InterpolateToState (VariableState stateToInterpolateTo, double secondsToTake)
{
switch(stateToInterpolateTo)
{
case VariableState.Sniffing:
break;
case VariableState.Walking:
break;
case VariableState.Happy:
break;
case VariableState.Jumping:
break;
case VariableState.OneDuck:
break;
case VariableState.TwoDucks:
break;
case VariableState.Laughing:
break;
}
var instruction = new FlatRedBall.Instructions.DelegateInstruction<VariableState>(StopStateInterpolation, stateToInterpolateTo);
instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + secondsToTake;
this.Instructions.Add(instruction);
return instruction;
}
public void StopStateInterpolation (VariableState stateToStop)
{
switch(stateToStop)
{
case VariableState.Sniffing:
break;
case VariableState.Walking:
break;
case VariableState.Happy:
break;
case VariableState.Jumping:
break;
case VariableState.OneDuck:
break;
case VariableState.TwoDucks:
break;
case VariableState.Laughing:
break;
}
CurrentState = stateToStop;
}
public void InterpolateBetween (VariableState firstState, VariableState secondState, float interpolationValue)
{
#if DEBUG
if (float.IsNaN(interpolationValue))
{
throw new Exception("interpolationValue cannot be NaN");
}
#endif
switch(firstState)
{
case VariableState.Sniffing:
if (interpolationValue < 1)
{
this.CurrentChain = "Sniffing";
}
break;
case VariableState.Walking:
if (interpolationValue < 1)
{
this.CurrentChain = "Walking";
}
break;
case VariableState.Happy:
if (interpolationValue < 1)
{
this.CurrentChain = "Happy";
}
break;
case VariableState.Jumping:
if (interpolationValue < 1)
{
this.CurrentChain = "Jumping";
}
break;
case VariableState.OneDuck:
if (interpolationValue < 1)
{
this.CurrentChain = "OneDuck";
}
break;
case VariableState.TwoDucks:
if (interpolationValue < 1)
{
this.CurrentChain = "TwoDucks";
}
break;
case VariableState.Laughing:
if (interpolationValue < 1)
{
this.CurrentChain = "Laugh";
}
break;
}
switch(secondState)
{
case VariableState.Sniffing:
if (interpolationValue >= 1)
{
this.CurrentChain = "Sniffing";
}
break;
case VariableState.Walking:
if (interpolationValue >= 1)
{
this.CurrentChain = "Walking";
}
break;
case VariableState.Happy:
if (interpolationValue >= 1)
{
this.CurrentChain = "Happy";
}
break;
case VariableState.Jumping:
if (interpolationValue >= 1)
{
this.CurrentChain = "Jumping";
}
break;
case VariableState.OneDuck:
if (interpolationValue >= 1)
{
this.CurrentChain = "OneDuck";
}
break;
case VariableState.TwoDucks:
if (interpolationValue >= 1)
{
this.CurrentChain = "TwoDucks";
}
break;
case VariableState.Laughing:
if (interpolationValue >= 1)
{
this.CurrentChain = "Laugh";
}
break;
}
if (interpolationValue < 1)
{
mCurrentState = (int)firstState;
}
else
{
mCurrentState = (int)secondState;
}
}
public static void PreloadStateContent (VariableState state, string contentManagerName)
{
ContentManagerName = contentManagerName;
switch(state)
{
case VariableState.Sniffing:
{
object throwaway = "Sniffing";
}
break;
case VariableState.Walking:
{
object throwaway = "Walking";
}
break;
case VariableState.Happy:
{
object throwaway = "Happy";
}
break;
case VariableState.Jumping:
{
object throwaway = "Jumping";
}
break;
case VariableState.OneDuck:
{
object throwaway = "OneDuck";
}
break;
case VariableState.TwoDucks:
{
object throwaway = "TwoDucks";
}
break;
case VariableState.Laughing:
{
object throwaway = "Laugh";
}
break;
}
}
[System.Obsolete("Use GetFile instead")]
public static object GetStaticMember (string memberName)
{
switch(memberName)
{
case "AnimationChainListFile":
return AnimationChainListFile;
}
return null;
}
public static object GetFile (string memberName)
{
switch(memberName)
{
case "AnimationChainListFile":
return AnimationChainListFile;
}
return null;
}
object GetMember (string memberName)
{
switch(memberName)
{
case "AnimationChainListFile":
return AnimationChainListFile;
}
return null;
}
protected bool mIsPaused;
public override void Pause (FlatRedBall.Instructions.InstructionList instructions)
{
base.Pause(instructions);
mIsPaused = true;
}
public virtual void SetToIgnorePausing ()
{
FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(this);
FlatRedBall.Instructions.InstructionManager.IgnorePausingFor(VisibleInstance);
}
public virtual void MoveToLayer (Layer layerToMoveTo)
{
if (LayerProvidedByContainer != null)
{
LayerProvidedByContainer.Remove(VisibleInstance);
}
SpriteManager.AddToLayer(VisibleInstance, layerToMoveTo);
LayerProvidedByContainer = layerToMoveTo;
}
}
// Extra classes
public static class DogExtensionMethods
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.