context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// 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.Buffers.Tests
{
public class BasicUnitTests
{
[Fact]
public void ByteSpanEmptyCreateArrayTest()
{
var empty = Span<byte>.Empty;
var array = empty.ToArray();
Assert.Equal(0, array.Length);
}
[Fact]
public void ByteReadOnlySpanEmptyCreateArrayTest()
{
var empty = ReadOnlySpan<byte>.Empty;
var array = empty.ToArray();
Assert.Equal(0, array.Length);
}
[Fact]
public unsafe void ByteSpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
Span<byte> b1 = new Span<byte>(buffer1pinned, bufferLength);
Span<byte> b2 = new Span<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Fact]
public unsafe void ByteReadOnlySpanEqualsTestsTwoDifferentInstancesOfBuffersWithOneValueDifferent()
{
const int bufferLength = 128;
byte[] buffer1 = new byte[bufferLength];
byte[] buffer2 = new byte[bufferLength];
for (int i = 0; i < bufferLength; i++)
{
buffer1[i] = (byte)(bufferLength + 1 - i);
buffer2[i] = (byte)(bufferLength + 1 - i);
}
fixed (byte* buffer1pinned = buffer1)
fixed (byte* buffer2pinned = buffer2)
{
ReadOnlySpan<byte> b1 = new ReadOnlySpan<byte>(buffer1pinned, bufferLength);
ReadOnlySpan<byte> b2 = new ReadOnlySpan<byte>(buffer2pinned, bufferLength);
for (int i = 0; i < bufferLength; i++)
{
for (int diffPosition = i; diffPosition < bufferLength; diffPosition++)
{
buffer1[diffPosition] = unchecked((byte)(buffer1[diffPosition] + 1));
Assert.False(b1.Slice(i).SequenceEqual(b2.Slice(i)));
}
}
}
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteReadOnlySpanCtorWithRangeValidCases(byte[] bytes, int start, int length)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length);
}
[Fact]
public void ByteSpanCtorWithRangeThrowsArgumentExceptionOnNull()
{
try
{
Span<byte> span = new Span<byte>(null, 0, 0);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentNullException);
}
}
[Fact]
public void ByteReadOnlySpanCtorWithRangeThrowsArgumentExceptionOnNull()
{
try
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(null, 0, 0);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentNullException);
}
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
try
{
Span<byte> span = new Span<byte>(bytes, start, length);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
[Theory]
[InlineData(new byte[0], 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 0)]
[InlineData(new byte[1] { 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 0, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 1)]
[InlineData(new byte[2] { 0, 0 }, 1, 1)]
[InlineData(new byte[2] { 0, 0 }, 2, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 0, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 1)]
public void ByteSpanSliceWithRangeValidCases(byte[] bytes, int start, int length)
{
Span<byte> span = new Span<byte>(bytes, start, length);
}
[Theory]
[InlineData(new byte[0], 1, 0)]
[InlineData(new byte[0], 1, -1)]
[InlineData(new byte[0], 0, 1)]
[InlineData(new byte[0], -1, 0)]
[InlineData(new byte[0], 5, 5)]
[InlineData(new byte[1] { 0 }, 0, 2)]
[InlineData(new byte[1] { 0 }, 1, 1)]
[InlineData(new byte[1] { 0 }, -1, 2)]
[InlineData(new byte[2] { 0, 0 }, 0, 3)]
[InlineData(new byte[2] { 0, 0 }, 1, 2)]
[InlineData(new byte[2] { 0, 0 }, 2, 1)]
[InlineData(new byte[2] { 0, 0 }, 3, 0)]
[InlineData(new byte[2] { 0, 0 }, 1, -1)]
[InlineData(new byte[2] { 0, 0 }, 2, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue, int.MaxValue)]
[InlineData(new byte[3] { 0, 0, 0 }, 1, 3)]
[InlineData(new byte[3] { 0, 0, 0 }, 2, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 15, 0)]
public void ByteSpanSliceWithRangeThrowsArgumentOutOfRangeException1(byte[] bytes, int start, int length)
{
var span = new Span<byte>(bytes);
try
{
Span<byte> slice = span.Slice(start, length);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
[Theory]
[InlineData(new byte[0], 0)]
[InlineData(new byte[1] { 0 }, 0)]
[InlineData(new byte[1] { 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 0)]
[InlineData(new byte[2] { 0, 0 }, 1)]
[InlineData(new byte[2] { 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 0)]
[InlineData(new byte[3] { 0, 0, 0 }, 1)]
[InlineData(new byte[3] { 0, 0, 0 }, 2)]
[InlineData(new byte[3] { 0, 0, 0 }, 3)]
public void ByteSpanSliceWithStartRangeValidCases(byte[] bytes, int start)
{
Span<byte> span = new Span<byte>(bytes).Slice(start);
}
[Theory]
[InlineData(new byte[0], int.MinValue)]
[InlineData(new byte[0], -1)]
[InlineData(new byte[0], 1)]
[InlineData(new byte[0], int.MaxValue)]
[InlineData(new byte[1] { 0 }, int.MinValue)]
[InlineData(new byte[1] { 0 }, -1)]
[InlineData(new byte[1] { 0 }, 2)]
[InlineData(new byte[1] { 0 }, int.MaxValue)]
[InlineData(new byte[2] { 0, 0 }, int.MinValue)]
[InlineData(new byte[2] { 0, 0 }, -1)]
[InlineData(new byte[2] { 0, 0 }, 3)]
[InlineData(new byte[2] { 0, 0 }, int.MaxValue)]
public void ByteSpanSliceWithStartRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start)
{
var span = new Span<byte>(bytes);
try
{
Span<byte> slice = span.Slice(start);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
public void ByteReadOnlySpanCtorWithRangeThrowsArgumentOutOfRangeException(byte[] bytes, int start, int length)
{
try
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(bytes, start, length);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArgumentOutOfRangeException);
}
}
[Fact]
public void SetSpan()
{
var destination = new Span<byte>(new byte[100]);
var source = new Span<byte>(new byte[] { 1, 2, 3 });
source.CopyTo(destination);
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void SetArray()
{
var destination = new Span<byte>(new byte[100]);
var source = new byte[] { 1, 2, 3 };
source.CopyTo(destination);
for (int i = 0; i < source.Length; i++)
{
Assert.Equal(source[i], destination[i]);
}
}
[Fact]
public void CovariantSlicesNotSupported1()
{
object[] array = new string[10];
try
{
var slice = new Span<object>(array);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArrayTypeMismatchException);
}
}
[Fact]
public void CovariantSlicesNotSupported2()
{
object[] array = new string[10];
try
{
var slice = array.AsSpan().Slice(0);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArrayTypeMismatchException);
}
}
[Fact]
public void CovariantSlicesNotSupported3()
{
object[] array = new string[10];
try
{
var slice = new Span<object>(array, 0, 10);
Assert.True(false);
}
catch (Exception ex)
{
Assert.True(ex is ArrayTypeMismatchException);
}
}
[Fact]
public void OwnedBufferDisposedAfterFinalizerGCKeepAliveTest()
{
OwnedMemory<byte> owned = new CustomMemoryForTest<byte>(new byte[1024]);
var buffer = owned.Memory;
var slice = buffer.Slice(1);
var span = buffer.Span;
var sliceSpan = slice.Span;
span[5] = 42;
sliceSpan[10] = 24;
GC.Collect(2);
GC.WaitForPendingFinalizers();
try
{
span = buffer.Span;
sliceSpan = slice.Span;
}
catch (ObjectDisposedException ex)
{
Assert.True(false, "There shouldn't be any Object Disposed Exception here. " + ex.Message);
}
Assert.Equal(42, span[5]);
Assert.Equal(24, sliceSpan[10]);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Billing.Budgets.V1Beta1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedBudgetServiceClientSnippets
{
/// <summary>Snippet for CreateBudget</summary>
public void CreateBudgetRequestObject()
{
// Snippet: CreateBudget(CreateBudgetRequest, CallSettings)
// Create client
BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create();
// Initialize request argument(s)
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
// Make the request
Budget response = budgetServiceClient.CreateBudget(request);
// End snippet
}
/// <summary>Snippet for CreateBudgetAsync</summary>
public async Task CreateBudgetRequestObjectAsync()
{
// Snippet: CreateBudgetAsync(CreateBudgetRequest, CallSettings)
// Additional: CreateBudgetAsync(CreateBudgetRequest, CancellationToken)
// Create client
BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync();
// Initialize request argument(s)
CreateBudgetRequest request = new CreateBudgetRequest
{
ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
Budget = new Budget(),
};
// Make the request
Budget response = await budgetServiceClient.CreateBudgetAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateBudget</summary>
public void UpdateBudgetRequestObject()
{
// Snippet: UpdateBudget(UpdateBudgetRequest, CallSettings)
// Create client
BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create();
// Initialize request argument(s)
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new FieldMask(),
};
// Make the request
Budget response = budgetServiceClient.UpdateBudget(request);
// End snippet
}
/// <summary>Snippet for UpdateBudgetAsync</summary>
public async Task UpdateBudgetRequestObjectAsync()
{
// Snippet: UpdateBudgetAsync(UpdateBudgetRequest, CallSettings)
// Additional: UpdateBudgetAsync(UpdateBudgetRequest, CancellationToken)
// Create client
BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateBudgetRequest request = new UpdateBudgetRequest
{
Budget = new Budget(),
UpdateMask = new FieldMask(),
};
// Make the request
Budget response = await budgetServiceClient.UpdateBudgetAsync(request);
// End snippet
}
/// <summary>Snippet for GetBudget</summary>
public void GetBudgetRequestObject()
{
// Snippet: GetBudget(GetBudgetRequest, CallSettings)
// Create client
BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create();
// Initialize request argument(s)
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
// Make the request
Budget response = budgetServiceClient.GetBudget(request);
// End snippet
}
/// <summary>Snippet for GetBudgetAsync</summary>
public async Task GetBudgetRequestObjectAsync()
{
// Snippet: GetBudgetAsync(GetBudgetRequest, CallSettings)
// Additional: GetBudgetAsync(GetBudgetRequest, CancellationToken)
// Create client
BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync();
// Initialize request argument(s)
GetBudgetRequest request = new GetBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
// Make the request
Budget response = await budgetServiceClient.GetBudgetAsync(request);
// End snippet
}
/// <summary>Snippet for ListBudgets</summary>
public void ListBudgetsRequestObject()
{
// Snippet: ListBudgets(ListBudgetsRequest, CallSettings)
// Create client
BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create();
// Initialize request argument(s)
ListBudgetsRequest request = new ListBudgetsRequest
{
ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
};
// Make the request
PagedEnumerable<ListBudgetsResponse, Budget> response = budgetServiceClient.ListBudgets(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Budget item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListBudgetsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Budget item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Budget> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Budget item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListBudgetsAsync</summary>
public async Task ListBudgetsRequestObjectAsync()
{
// Snippet: ListBudgetsAsync(ListBudgetsRequest, CallSettings)
// Create client
BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync();
// Initialize request argument(s)
ListBudgetsRequest request = new ListBudgetsRequest
{
ParentAsBillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"),
};
// Make the request
PagedAsyncEnumerable<ListBudgetsResponse, Budget> response = budgetServiceClient.ListBudgetsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Budget item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListBudgetsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Budget item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Budget> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Budget item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeleteBudget</summary>
public void DeleteBudgetRequestObject()
{
// Snippet: DeleteBudget(DeleteBudgetRequest, CallSettings)
// Create client
BudgetServiceClient budgetServiceClient = BudgetServiceClient.Create();
// Initialize request argument(s)
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
// Make the request
budgetServiceClient.DeleteBudget(request);
// End snippet
}
/// <summary>Snippet for DeleteBudgetAsync</summary>
public async Task DeleteBudgetRequestObjectAsync()
{
// Snippet: DeleteBudgetAsync(DeleteBudgetRequest, CallSettings)
// Additional: DeleteBudgetAsync(DeleteBudgetRequest, CancellationToken)
// Create client
BudgetServiceClient budgetServiceClient = await BudgetServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteBudgetRequest request = new DeleteBudgetRequest
{
BudgetName = BudgetName.FromBillingAccountBudget("[BILLING_ACCOUNT]", "[BUDGET]"),
};
// Make the request
await budgetServiceClient.DeleteBudgetAsync(request);
// End snippet
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B09_Region_Child (editable child object).<br/>
/// This is a generated base class of <see cref="B09_Region_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class B09_Region_Child : BusinessBase<B09_Region_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int region_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Region Child Name");
/// <summary>
/// Gets or sets the Region Child Name.
/// </summary>
/// <value>The Region Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B09_Region_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B09_Region_Child"/> object.</returns>
internal static B09_Region_Child NewB09_Region_Child()
{
return DataPortal.CreateChild<B09_Region_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="B09_Region_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B09_Region_Child"/> object.</returns>
internal static B09_Region_Child GetB09_Region_Child(SafeDataReader dr)
{
B09_Region_Child obj = new B09_Region_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B09_Region_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B09_Region_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B09_Region_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B09_Region_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name"));
// parent properties
region_ID1 = dr.GetInt32("Region_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B09_Region_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B08_Region parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IB09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Region_ID,
Region_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B09_Region_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B08_Region parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IB09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Region_ID,
Region_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="B09_Region_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B08_Region parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IB09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(SplineNode))]
public class SplineNodeInspector : InstantInspector
{
private SerializedProperty customValueProp;
private SerializedProperty tensionProp;
private SerializedProperty normalProp;
private GUIStyle buttonGUIStyle;
private SplineNode targetNode;
private static Spline selectedSpline = null;
private static LengthMode lMode = LengthMode.GameUnits;
private readonly string notUsedWarning =
"This SplineNode isn't used by any spline in the scene. Attach this node to a spline by dragging it onto a spline's Inspector window!";
public void OnEnable( )
{
customValueProp = serializedObject.FindProperty( "customValue" );
tensionProp = serializedObject.FindProperty( "tension" );
normalProp = serializedObject.FindProperty( "normal" );
}
public override void OnInspectorGUIInner( )
{
targetNode = target as SplineNode;
List<Spline> splinesToRemove = new List<Spline>( );
foreach( var key in targetNode.Parameters.Keys )
{
if( !key )
splinesToRemove.Add( key );
else if( !key.splineNodesArray.Contains( targetNode ) )
splinesToRemove.Add( key );
}
foreach( var key in splinesToRemove )
targetNode.Parameters.Remove( key );
DrawInspectorOptions( );
DrawSplineSettings( );
DrawCustomSettings( );
DrawButtons( );
}
private void DrawInspectorOptions( )
{
EditorGUILayout.PrefixLabel( "Inspector Options", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
lMode = (LengthMode) EditorGUILayout.EnumPopup( "Length Mode", lMode );
SmallSpace( );
--EditorGUI.indentLevel;
}
private void DrawSplineSettings( )
{
EditorGUILayout.PrefixLabel( "Spline Data", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
if( targetNode.Parameters.Count <= 0 )
{
EditorGUILayout.HelpBox( notUsedWarning, MessageType.Info );
}
else
{
List<Spline> splineKeys = new List<Spline>( targetNode.Parameters.Keys );
List<string> splineNames = new List<string>( );
foreach( Spline spline in splineKeys )
{
if( !splineNames.Contains( spline.name ) )
splineNames.Add( spline.name );
else
{
string newName = spline.name;
while( splineNames.Contains( newName ) )
newName += "*";
splineNames.Add( newName );
}
}
int index = splineKeys.IndexOf( selectedSpline );
if( index < 0 )
index = 0;
index = EditorGUILayout.Popup( "Spline", index, splineNames.ToArray( ) );
selectedSpline = splineKeys[index];
float lengthFactor = (lMode != LengthMode.GameUnits) ? 1 : selectedSpline.Length;
float position = (float)targetNode.Parameters[selectedSpline].position * lengthFactor;
float length = (float)targetNode.Parameters[selectedSpline].length * lengthFactor;
SmallSpace( );
int nodeIndex = Array.IndexOf( selectedSpline.SplineNodes, targetNode );
EditorGUILayout.TextField( "Index in Spline", nodeIndex.ToString( ) );
SmallSpace( );
EditorGUILayout.TextField( "Spline Parameter", position.ToString( ) );
GUILayout.Space(-5);
EditorGUIUtility.LookLikeControls( 200 );
EditorGUILayout.PrefixLabel( new GUIContent( "(Distance From Start Node)" ), EditorStyles.miniLabel, EditorStyles.miniLabel );
EditorGUIUtility.LookLikeControls( );
EditorGUILayout.TextField( "Length Parameter", length.ToString( ) );
GUILayout.Space(-5);
EditorGUIUtility.LookLikeControls( 200 );
EditorGUILayout.PrefixLabel( new GUIContent( "(Distance To Next Node)" ), EditorStyles.miniLabel, EditorStyles.miniLabel );
EditorGUIUtility.LookLikeControls( );
}
--EditorGUI.indentLevel;
}
private void DrawCustomSettings( )
{
EditorGUILayout.PrefixLabel( "Custom Settings", EditorStyles.label, EditorStyles.boldLabel );
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField( tensionProp, new GUIContent( "Curve Tension" ) );
EditorGUILayout.PropertyField( normalProp, new GUIContent( "Curve Normal" ) );
EditorGUILayout.Space( );
EditorGUILayout.PropertyField( customValueProp, new GUIContent( "Custom Data" ) );
SmallSpace( );
--EditorGUI.indentLevel;
}
private void DrawButtons( )
{
if( targetNode.Parameters.Count <= 0 )
return;
SplineNode[] splineNodes = selectedSpline.SplineNodes;
int nodeIndex = Array.IndexOf( selectedSpline.SplineNodes, targetNode );
EditorGUI.BeginDisabledGroup( selectedSpline == null );
EditorGUILayout.BeginHorizontal( );
GUILayout.Space( 15 );
if( GUILayout.Button( "Previous Node", GetButtonGUIStyleLeft( ), GUILayout.Height( 21f ) ) )
Selection.activeGameObject = splineNodes[ (nodeIndex!=0 ? nodeIndex : splineNodes.Length) - 1].gameObject;
if( GUILayout.Button( " Next Node ", GetButtonGUIStyleRight( ), GUILayout.Height( 21f ) ) )
Selection.activeGameObject = splineNodes[(nodeIndex+1)%splineNodes.Length].gameObject;
EditorGUILayout.EndHorizontal( );
EditorGUI.EndDisabledGroup( );
}
public void OnSceneGUI( )
{
if( targetNode == null )
return;
Handles.color = new Color( .3f, 1f, .20f, 1 );
Handles.ArrowCap( 0, targetNode.Position, Quaternion.LookRotation( targetNode.TransformedNormal ), HandleUtility.GetHandleSize( targetNode.Position ) * 0.5f );
Handles.color = new Color( .2f, 0.4f, 1f, 1 );
Handles.ArrowCap( 0, targetNode.Position, Quaternion.LookRotation( targetNode.transform.forward ), HandleUtility.GetHandleSize( targetNode.Position ) * 0.5f );
Handles.color = new Color( 1f, 0.5f, 0f, .75f );
Handles.SphereCap( 0, targetNode.Position, targetNode.Rotation, HandleUtility.GetHandleSize( targetNode.Position ) * 0.175f );
}
private GUIStyle GetButtonGUIStyleLeft( )
{
GUIStyle buttonGUIStyle = new GUIStyle( EditorStyles.miniButtonLeft );
buttonGUIStyle.alignment = TextAnchor.MiddleCenter;
buttonGUIStyle.wordWrap = true;
buttonGUIStyle.border = new RectOffset( 3, 3, 3, 3 );
buttonGUIStyle.contentOffset = - Vector2.up * 2f;
buttonGUIStyle.fontSize = 12;
return buttonGUIStyle;
}
private GUIStyle GetButtonGUIStyleRight( )
{
GUIStyle buttonGUIStyle = new GUIStyle( EditorStyles.miniButtonRight );
buttonGUIStyle.alignment = TextAnchor.MiddleCenter;
buttonGUIStyle.wordWrap = true;
buttonGUIStyle.border = new RectOffset( 3, 3, 3, 3 );
buttonGUIStyle.contentOffset = - Vector2.up * 2f;
buttonGUIStyle.fontSize = 12;
return buttonGUIStyle;
}
private enum LengthMode
{
Normalized,
GameUnits
}
}
| |
using OneBoxDeployment.Utilities;
using OneBoxDeployment.Api;
using OneBoxDeployment.IntegrationTests.HttpClients;
using OneBoxDeployment.OrleansUtilities;
using Dapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Orleans.Configuration;
using Orleans.Hosting;
using Polly;
using Polly.Extensions.Http;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using Program = OneBoxDeployment.Api.Program;
using System.Net.Mime;
namespace OneBoxDeployment.IntegrationTests
{
/// <summary>
/// Running silo and its configuration information.
/// </summary>
public sealed class RunningSilo
{
/// <summary>
/// The running silo.
/// </summary>
public ISiloHost Silo { get; }
/// <summary>
/// The configuration used to start the silo.
/// </summary>
public ClusterConfig ClusterConfig { get; }
/// <summary>
/// A default constructor.
/// </summary>
/// <param name="silo">The running silo.</param>
/// <param name="clusterConfig">The cluster configuration used to start the silo.</param>
public RunningSilo(ISiloHost silo, ClusterConfig clusterConfig)
{
Silo = silo ?? throw new ArgumentNullException(nameof(silo));
ClusterConfig = clusterConfig ?? throw new ArgumentNullException(nameof(clusterConfig));
}
}
/// <summary>
/// A fixture to create <see cref="IWebHost"/> from <see cref="Startup"/> for testing purposes.
/// </summary>
public class IntegrationTestFixture: IAsyncLifetime
{
/// <summary>
/// The OneBoxDeployment Web API server.
/// </summary>
private IWebHost ApiHost { get; set; }
/// <summary>
/// The OneBoxDeployment identity server.
/// </summary>
private IWebHost IdentityHost { get; set; }
/// <summary>
/// The currently running Orleans siloes.
/// </summary>
private static List<RunningSilo> Siloes { get; } = new List<RunningSilo>();
/// <summary>
/// The database name.
/// </summary>
private static string DatabaseName { get; } = "OneBoxDeployment.Database";
/// <summary>
/// The database connection string.
/// </summary>
private static string DatabaseConnectionString { get; set; }
/// <summary>
/// The database snapshot name.
/// </summary>
private static string DatabaseSnapshotName { get; set; }
private static IManagementQueries DatabaseManagementQueries { get; } = new SqlServerManagementQueries();
/// <summary>
/// All siloes and clients in the cluster find each other using this shared value
/// in the membership table.
/// </summary>
/// <remarks>The database snapshotting makes sure the cluster identifiers never overlap
/// since originally they are not there and snapshot restore further removes them.</remarks>
public string ClusterId { get; } = "TestCluster-" + DateTime.UtcNow.ToString("O");
/// <summary>
/// This should remain stable between deployments. Reminders and storage use this as the key
/// so they can find the data even across cluster deployments.
/// </summary>
/// <remarks>The database snapshotting makes sure the service identifiers never overlap
/// since originally they are not there and snapshot restore further removes them.</remarks>
public string ServiceId { get; } = "TestService-" + DateTime.UtcNow.ToString("O");
/// <summary>
/// A service collection for various constructed IoC services.
/// </summary>
public IServiceProvider ServicesProvider { get; }
/// <summary>
/// The default Data API root URL, including the port.
/// </summary>
public string DefaultApiRootUrl { get; set; }
/// <summary>
/// The default Identity API root URL, including the port.
/// </summary>
public string DefaultIdentityRootUrl { get; set; }
/// <summary>
/// This route can be used to test pipeline exception handling during tests.
/// </summary>
public const string FaultyRouteUrlFragment = "/internalservererror";
/// <summary>
/// These are testing only default extra parameters that should not be present in a running application.
/// </summary>
/// <remarks>These settings are used, amongst others, to control fault injection in tests.</remarks>
public Dictionary<string, string> DefaultExtraParameters { get; } = new Dictionary<string, string>
{
//This setting creates a route that will always throw an exception. It's injected with a
//a setting to not to create the route in production. This is built like this also so that
//there would not be a path to accidentally inject faulty code to production.
{ ConfigurationKeys.AlwaysFaultyRoute, FaultyRouteUrlFragment }
};
/// <summary>
/// The test message sink.
/// </summary>
public IMessageSink MessageSink { get; }
/// <summary>
/// The in-memory storage of logs in the whole system.
/// </summary>
public InMemoryLoggerProvider InMemoryLoggerProvider { get; } = new InMemoryLoggerProvider();
/// <summary>
/// A default constructor.
/// </summary>
/// <param name="messageSink">The test message sink.</param>
public IntegrationTestFixture(IMessageSink messageSink)
{
MessageSink = messageSink;
//Sets this to testing environment if not in "Production".
const string AspNetCoreEnvironment = "ASPNETCORE_ENVIRONMENT";
if(Environment.GetEnvironmentVariable(AspNetCoreEnvironment) == null)
{
Environment.SetEnvironmentVariable(AspNetCoreEnvironment, "Development");
}
var environmentName = Environment.GetEnvironmentVariable(AspNetCoreEnvironment);
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
//Collect the database names.
DatabaseConnectionString = configuration.GetValue<string>($"ConnectionStrings:{DatabaseName}");
DatabaseSnapshotName = $"{DatabaseName}_Snapshot_{DateTime.UtcNow.ToString("O")}";
//The API test server is started in a random free port in order to avoid collisions with the already running APIs,
//identity or other services. Also connects to the identity server in the right ports.
int freeEphemeralApiPort = PlatformUtilities.GetFreePortFromEphemeralRange();
DefaultApiRootUrl = $"http://localhost:{freeEphemeralApiPort}/";
int freeEphemeralIdentityPort = PlatformUtilities.GetFreePortFromEphemeralRange();
DefaultIdentityRootUrl = $"http://localhost:{freeEphemeralIdentityPort}/";
void onBreak(DelegateResult<HttpResponseMessage> handledFault, TimeSpan duration) => Console.WriteLine("temp"); /* Logger.LogError($"Circuit breaking for {duration} due to {handledFault.Exception?.Message ?? handledFault.Result.StatusCode.ToString()}"); */
void onReset() { /* etc */ }
var circuitBreaker = HttpPolicyExtensions
.HandleTransientHttpError()
.AdvancedCircuitBreakerAsync(
failureThreshold: 0.5,
samplingDuration: TimeSpan.FromSeconds(10),
minimumThroughput: 2,
durationOfBreak: TimeSpan.FromMilliseconds(300),
onBreak: onBreak,
onReset: onReset);
var services = new ServiceCollection();
services.AddTypedHttpClient<FaultyRouteClient>(httpClient =>
{
httpClient.BaseAddress = new Uri(new Uri(DefaultApiRootUrl), FaultyRouteUrlFragment);
httpClient.DefaultRequestHeaders.Add("Accept", MediaTypeNames.Application.Json);
httpClient.DefaultRequestHeaders.Add("x-correlation-id", "test123");
})
.AddHttpMessageHandler(_ => new SecurityHeaderTestMessageHandler());
services.AddTypedHttpClient<CspClient>(httpClient =>
{
httpClient.BaseAddress = new Uri(DefaultApiRootUrl);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("x-correlation-id", "test123");
})
.AddHttpMessageHandler(_ => new SecurityHeaderTestMessageHandler());
services.AddTypedHttpClient<TestStateClient>(httpClient =>
{
httpClient.BaseAddress = new Uri(DefaultApiRootUrl);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("x-correlation-id", "test123");
})
.AddHttpMessageHandler(_ => new SecurityHeaderTestMessageHandler());
DefaultExtraParameters["AuthorityUrl"] = DefaultIdentityRootUrl;
ServicesProvider = services.BuildServiceProvider(validateScopes: true);
}
/// <summary>
/// <see cref="IAsyncLifetime.InitializeAsync"/>
/// </summary>
public async Task InitializeAsync()
{
//Preconditions checks without which the tests cannot be started.
if(!await ExistsDatabase(DatabaseName).ConfigureAwait(false))
{
throw new InvalidOperationException($"Database \"{DatabaseName}\" does not exist.");
}
//First a database snapshot that can be restored after the tests. This carries
//also the developer made changes since it may the purpose of the tests to test them.
//The database can be reset before running tests.
await CreateDatabaseSnapshot(DatabaseName, DatabaseSnapshotName).ConfigureAwait(false);
//By default two local siloes are started. One configuration object is saved to be given
//to the client. The siloes are started first so that the cluster clients won't hang
//while waiting for the clusters to start (they're in the same process). See
//ClusterClientStartupTask for improvements on asynchronous tasks in ASP.NET Core.
var siloConfig = CreateClusterConfig(ClusterId, ServiceId);
var silo1 = BuildSilo(siloConfig);
var silo2 = BuildSilo(CreateClusterConfig(ClusterId, ServiceId));
await Task.WhenAll(silo1.StartAsync(), silo2.StartAsync()).ConfigureAwait(false);
DefaultExtraParameters.Add(nameof(ClusterConfig), JsonConvert.SerializeObject(siloConfig, Formatting.Indented, new IPAddressConverter()));
ApiHost = Program.InternalBuildWebHost(new[] { "--server.urls", DefaultApiRootUrl }, DefaultExtraParameters, new[] { InMemoryLoggerProvider });
var apiServerTask = ApiHost.StartAsync();
//This also adds well known user names to the the system. The password is "Foobar".
//var wellKnownTestUsers = JsonConvert.SerializeObject(GetWellKnownTestUsers(), Formatting.Indented);
//IdentityHost = Identity.Program.InternalBuildWebHost(new[] { "--server.urls", DefaultIdentityRootUrl }, new Dictionary<string, string> { { "WellKnownTestUsers", wellKnownTestUsers }, { "integrationtest", "yes" } });
//var identityServerTask = IdentityHost.StartAsync();
await Task.WhenAll(apiServerTask/*, identityServerTask*/).ConfigureAwait(false);
}
/// <summary>
/// Creates a Orleans cluster configuration.
/// </summary>
/// <param name="clusterId">The cluster identifier.</param>
/// <param name="serviceId">The service identifier.</param>
/// <returns>A new cluster configuration.</returns>
public static ClusterConfig CreateClusterConfig(string clusterId, string serviceId)
{
const string AdoNetInvariant = "System.Data.SqlClient";
int GatewayPort = PlatformUtilities.GetFreePortFromEphemeralRange();
int SiloPort = PlatformUtilities.GetFreePortFromEphemeralRange();
return new ClusterConfig
{
ClusterOptions = new ClusterOptions
{
ClusterId = clusterId,
ServiceId = serviceId,
},
EndPointOptions = new EndpointOptions
{
AdvertisedIPAddress = IPAddress.Loopback,
GatewayPort = GatewayPort,
SiloPort = SiloPort
},
ConnectionConfig = new ConnectionConfig
{
Name = "TestCluster",
AdoNetConstant = AdoNetInvariant,
ConnectionString = DatabaseConnectionString
},
StorageConfigs = new List<ConnectionConfig>(new[]
{
new ConnectionConfig
{
Name = "TestStorage",
AdoNetConstant = AdoNetInvariant,
ConnectionString = DatabaseConnectionString
}
}),
ReminderConfigs = new List<ConnectionConfig>(new[]
{
new ConnectionConfig
{
Name = "TestReminders",
AdoNetConstant = AdoNetInvariant,
ConnectionString = DatabaseConnectionString
}
})
};
}
/// <summary>
/// Builds a new Orleans silo.
/// </summary>
/// <returns></returns>
public static ISiloHost BuildSilo(ClusterConfig clusterConfig)
{
var silo = OneBoxDeployment.OrleansHost.Program.BuildOrleansHost(null, clusterConfig);
Siloes.Add(new RunningSilo(silo, clusterConfig));
return silo;
}
/// <summary>
/// <see cref="IAsyncLifetime.DisposeAsync"/>
/// </summary>
public async Task DisposeAsync()
{
try
{
await Task.WhenAll(
Task.Run(() => Siloes.ForEach(rs => rs.Silo.Dispose())),
Task.Run(() => ApiHost?.Dispose()),
Task.Run(() => IdentityHost?.Dispose())).ConfigureAwait(false);
}
finally
{
await RestoreAndDropDatabaseSnapshot(DatabaseName, DatabaseSnapshotName).ConfigureAwait(false);
}
}
/// <summary>
/// Checks existence of <paramref name="databaseName"/>.
/// </summary>
/// <param name="databaseName">The name of the database.</param>
private static async Task<bool> ExistsDatabase(string databaseName)
{
using(var connection = new SqlConnection(DatabaseConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
var existsDatabaseQuery = DatabaseManagementQueries.ExistsDatabase(databaseName);
return (await connection.QueryAsync<bool>(existsDatabaseQuery).ConfigureAwait(false)).Single();
}
}
/// <summary>
/// Creates a database snapshot.
/// </summary>
/// <param name="databaseName">The name of the database the snapshot is taken from.</param>
/// <param name="databaseSnapshotName">The name of the snapshot database.</param>
private async static Task CreateDatabaseSnapshot(string databaseName, string databaseSnapshotName)
{
using(var connection = new SqlConnection(DatabaseConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
var createDatabaseSnapshotQuery = DatabaseManagementQueries.CreateDatabaseSnapshot(databaseName, databaseSnapshotName);
await connection.QueryAsync<int>(createDatabaseSnapshotQuery).ConfigureAwait(false);
}
}
/// <summary>
/// Restores database from a snapshot.
/// </summary>
/// <param name="databaseName">The name of the database which to restore.</param>
/// <param name="databaseSnapshotName">The name of the snapshot database from which to restore.</param>
private async static Task RestoreAndDropDatabaseSnapshot(string databaseName, string databaseSnapshotName)
{
using(var connection = new SqlConnection(DatabaseConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
var restoreDatabaseSnapshotQuery = DatabaseManagementQueries.RestoreDatabaseFromSnapshot(databaseName, databaseSnapshotName);
var dropDatabaseSnapshotQuery = DatabaseManagementQueries.DropDatabaseSnapshot(databaseSnapshotName);
await connection.QueryAsync<int>(restoreDatabaseSnapshotQuery).ConfigureAwait(false);
await connection.QueryAsync<int>(dropDatabaseSnapshotQuery).ConfigureAwait(false);
}
}
}
}
| |
//
// IntervalHeap.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2006-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
namespace Hyena.Collections
{
public class IntervalHeap<T> : ICollection<T>, ICollection
{
private const int MIN_CAPACITY = 16;
private int count;
private int generation;
private Interval [] heap;
public IntervalHeap ()
{
Clear ();
}
public virtual T Pop ()
{
if (count == 0) {
throw new InvalidOperationException ();
}
T item = heap[0].Item;
MoveDown (0, heap[--count]);
generation++;
return item;
}
public virtual T Peek ()
{
if (count == 0) {
throw new InvalidOperationException ();
}
return heap[0].Item;
}
public virtual void Push (T item, int priority)
{
if (item == null) {
throw new ArgumentNullException ("item");
}
if (count == heap.Length) {
OptimalArrayResize (ref heap, 1);
}
MoveUp (++count - 1, new Interval (item, priority));
generation++;
}
public virtual void Clear ()
{
generation = 0;
count = 0;
heap = new Interval[MIN_CAPACITY];
}
void ICollection.CopyTo (Array array, int index)
{
if (array == null) {
throw new ArgumentNullException ("array");
}
if (index < 0) {
throw new ArgumentOutOfRangeException ("index");
}
Array.Copy (heap, 0, array, index, count);
}
public virtual void CopyTo (T [] array, int index)
{
if (array == null) {
throw new ArgumentNullException ("array");
}
if (index < 0) {
throw new ArgumentOutOfRangeException ("index");
}
Array.Copy (heap, 0, array, index, count);
}
public virtual bool Contains (T item)
{
if (item == null) {
throw new ArgumentNullException ("item");
}
return FindItemHeapIndex (item) >= 0;
}
public virtual void Add (T item)
{
if (item == null) {
throw new ArgumentNullException ("item");
}
Push (item, 0);
}
public virtual bool Remove (T item)
{
if (item == null) {
throw new ArgumentNullException ("item");
}
int index = FindItemHeapIndex (item);
if (index < 0) {
return false;
}
MoveDown (index, heap[--count]);
generation++;
return true;
}
public virtual void TrimExcess ()
{
if (count < heap.Length * 0.9) {
Array.Resize (ref heap, count);
}
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public virtual IEnumerator<T> GetEnumerator ()
{
return new IntervalHeapEnumerator (this);
}
public static IntervalHeap<T> Synchronized (IntervalHeap<T> heap)
{
if (heap == null) {
throw new ArgumentNullException ("heap");
}
return new SyncIntervalHeap (heap);
}
private int FindItemHeapIndex (T item)
{
for (int i = 0; i < count; i++) {
if (item.Equals (heap[i].Item)) {
return i;
}
}
return -1;
}
private int GetLeftChildIndex (int index)
{
return index * 2 + 1;
}
private int GetParentIndex (int index)
{
return (index - 1) / 2;
}
private static void OptimalArrayResize (ref Interval [] array, int grow)
{
int new_capacity = array.Length == 0 ? 1 : array.Length;
int min_capacity = array.Length == 0 ? MIN_CAPACITY : array.Length + grow;
while (new_capacity < min_capacity) {
new_capacity <<= 1;
}
Array.Resize (ref array, new_capacity);
}
private void MoveUp (int index, Interval node)
{
int parent_index = GetParentIndex (index);
while (index > 0 && heap[parent_index].Priority < node.Priority) {
heap[index] = heap[parent_index];
index = parent_index;
parent_index = GetParentIndex (index);
}
heap[index] = node;
}
private void MoveDown (int index, Interval node)
{
int child_index = GetLeftChildIndex (index);
while (child_index < count) {
if (child_index + 1 < count
&& heap[child_index].Priority < heap[child_index + 1].Priority) {
child_index++;
}
heap[index] = heap[child_index];
index = child_index;
child_index = GetLeftChildIndex (index);
}
MoveUp (index, node);
}
public virtual int Count {
get { return count; }
}
public bool IsReadOnly {
get { return false; }
}
public virtual object SyncRoot {
get { return this; }
}
public virtual bool IsSynchronized {
get { return false; }
}
private struct Interval
{
private T item;
private int priority;
public Interval (T item, int priority)
{
this.item = item;
this.priority = priority;
}
public T Item {
get { return item; }
}
public int Priority {
get { return priority; }
}
}
private class SyncIntervalHeap : IntervalHeap<T>
{
private new IntervalHeap<T> heap;
internal SyncIntervalHeap (IntervalHeap<T> heap)
{
this.heap = heap;
}
public override int Count {
get { lock (heap) { return heap.Count; } }
}
public override bool IsSynchronized {
get { return true; }
}
public override object SyncRoot {
get { return heap.SyncRoot; }
}
public override void Clear ()
{
lock (heap) { heap.Clear (); }
}
public override bool Contains(T item)
{
lock (heap) { return heap.Contains (item); }
}
public override T Pop()
{
lock (heap) { return heap.Pop (); }
}
public override T Peek ()
{
lock (heap) { return heap.Peek (); }
}
public override void Push (T item, int priority)
{
lock (heap) { heap.Push (item, priority); }
}
public override void Add (T item)
{
lock (heap) { heap.Add (item); }
}
public override bool Remove (T item)
{
lock (heap) { return heap.Remove (item); }
}
public override void TrimExcess ()
{
lock (heap) { heap.TrimExcess (); }
}
public override void CopyTo (T [] array, int index)
{
lock (heap) { heap.CopyTo (array, index); }
}
public override IEnumerator<T> GetEnumerator ()
{
lock (heap) { return new IntervalHeapEnumerator (this); }
}
}
private class IntervalHeapEnumerator : IEnumerator<T>, IEnumerator
{
private IntervalHeap<T> heap;
private int index;
private int generation;
public IntervalHeapEnumerator (IntervalHeap<T> heap)
{
this.heap = heap;
Reset ();
}
public void Reset ()
{
generation = heap.generation;
index = -1;
}
public void Dispose ()
{
heap = null;
}
public bool MoveNext ()
{
if (generation != heap.generation) {
throw new InvalidOperationException ();
}
if (index + 1 == heap.count) {
return false;
}
index++;
return true;
}
object IEnumerator.Current {
get { return Current; }
}
public T Current {
get {
if (generation != heap.generation) {
throw new InvalidOperationException ();
}
return heap.heap[index].Item;
}
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.Generic;
namespace Vulkan
{
public static partial class DeviceExtensions
{
public const string VK_KHR_swapchain = "VK_KHR_swapchain";
};
public static partial class VK
{
#region handles
[StructLayout(LayoutKind.Sequential)] public struct SwapchainKHR { public UInt64 native; }
#endregion
//no enums
#region flags
[Flags]
public enum SwapchainCreateFlagsKHR : int
{
SplitInstanceBindRegionsBitKhr = 1 << 0,
ProtectedBitKhr = 1 << 1,
MutableFormatBitKhr = 1 << 2,
};
[Flags]
public enum DeviceGroupPresentModeFlagsKHR : int
{
LocalBitKhr = 1 << 0,
RemoteBitKhr = 1 << 1,
SumBitKhr = 1 << 2,
LocalMultiDeviceBitKhr = 1 << 3,
};
#endregion
#region structs
public struct SwapchainCreateInfoKHR
{
public StructureType type;
public IntPtr next;
public SwapchainCreateFlagsKHR flags;
public SurfaceKHR surface;
public UInt32 minImageCount;
public Format imageFormat;
public ColorSpaceKHR imageColorSpace;
public Extent2D imageExtent;
public UInt32 imageArrayLayers;
public ImageUsageFlags imageUsage;
public SharingMode imageSharingMode;
public List<UInt32> queueFamilyIndices;
public SurfaceTransformFlagsKHR preTransform;
public CompositeAlphaFlagsKHR compositeAlpha;
public PresentModeKHR presentMode;
public Bool32 clipped;
public SwapchainKHR oldSwapchain;
}
public struct PresentInfoKHR
{
public StructureType type;
public IntPtr next;
public List<Semaphore> waitSemaphores;
public List<SwapchainKHR> swapchains;
public List<UInt32> indices;
public List<Result> results;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct ImageSwapchainCreateInfoKHR
{
public StructureType type;
public IntPtr next;
public SwapchainKHR swapchain;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct BindImageMemorySwapchainInfoKHR
{
public StructureType type;
public IntPtr next;
public SwapchainKHR swapchain;
public UInt32 imageIndex;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct AcquireNextImageInfoKHR
{
public StructureType type;
public IntPtr next;
public SwapchainKHR swapchain;
public UInt64 timeout;
public Semaphore semaphore;
public Fence fence;
public UInt32 deviceMask;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public unsafe struct DeviceGroupPresentCapabilitiesKHR
{
public StructureType type;
public IntPtr next;
public fixed UInt32 presentMask[(int)VK.MAX_DEVICE_GROUP_SIZE];
public DeviceGroupPresentModeFlagsKHR modes;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public unsafe struct DeviceGroupPresentInfoKHR
{
public StructureType type;
public IntPtr next;
public UInt32 swapchainCount;
public UInt32* pDeviceMasks;
public DeviceGroupPresentModeFlagsKHR mode;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DeviceGroupSwapchainCreateInfoKHR
{
public StructureType type;
public IntPtr next;
public DeviceGroupPresentModeFlagsKHR modes;
};
#endregion
#region functions
//external functions we need to get from the device
//VkResult vkCreateSwapchainKHR(VkDevice device, VkSwapchainCreateInfoKHR* pCreateInfo, VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain);
//void vkDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, VkAllocationCallbacks* pAllocator);
//VkResult vkGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages);
//VkResult vkAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex);
//VkResult vkQueuePresentKHR(VkQueue queue, VkPresentInfoKHR* pPresentInfo);
//VkResult vkGetDeviceGroupPresentCapabilitiesKHR(VkDevice device, VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities);
//VkResult vkGetDeviceGroupSurfacePresentModesKHR(VkDevice device, VkSurfaceKHR surface, VkDeviceGroupPresentModeFlagsKHR* pModes);
//VkResult vkGetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pRectCount, VkRect2D* pRects);
//VkResult vkAcquireNextImage2KHR(VkDevice device, VkAcquireNextImageInfoKHR* pAcquireInfo, uint32_t* pImageIndex);
//delegate definitions
delegate Result CreateSwapchainKHRDelegate(Device device, ref _SwapchainCreateInfoKHR pCreateInfo, AllocationCallbacks pAllocator, out SwapchainKHR pSwapchain);
public delegate void DestroySwapchainKHRDelegate(Device device, SwapchainKHR swapchain, AllocationCallbacks pAllocator = null);
delegate Result GetSwapchainImagesKHRDelegate(Device device, SwapchainKHR swapchain, ref UInt32 pSwapchainImageCount, IntPtr pSwapchainImages);
public delegate Result AcquireNextImageKHRDelegate(Device device, SwapchainKHR swapchain, UInt64 timeout, Semaphore semaphore, Fence fence, ref UInt32 pImageIndex);
delegate Result QueuePresentKHRDelegate(Queue queue, ref _PresentInfoKHR pPresentInfo);
public delegate Result GetDeviceGroupPresentCapabilitiesKHRDelegate(Device device, ref DeviceGroupPresentCapabilitiesKHR pDeviceGroupPresentCapabilities);
public delegate Result GetDeviceGroupSurfacePresentModesKHRDelegate(Device device, SurfaceKHR surface, ref DeviceGroupPresentModeFlagsKHR pModes);
public delegate Result GetPhysicalDevicePresentRectanglesKHRDelegate(PhysicalDevice physicalDevice, SurfaceKHR surface, ref UInt32 pRectCount, ref Rect2D pRects);
public delegate Result AcquireNextImage2KHRDelegate(Device device, ref AcquireNextImageInfoKHR pAcquireInfo, ref UInt32 pImageIndex);
//delegate instances
static CreateSwapchainKHRDelegate _CreateSwapchainKHR;
public static DestroySwapchainKHRDelegate DestroySwapchainKHR;
static GetSwapchainImagesKHRDelegate _GetSwapchainImagesKHR;
public static AcquireNextImageKHRDelegate AcquireNextImageKHR;
static QueuePresentKHRDelegate _QueuePresentKHR;
public static GetDeviceGroupPresentCapabilitiesKHRDelegate GetDeviceGroupPresentCapabilitiesKHR;
public static GetDeviceGroupSurfacePresentModesKHRDelegate GetDeviceGroupSurfacePresentModesKHR;
public static GetPhysicalDevicePresentRectanglesKHRDelegate GetPhysicalDevicePresentRectanglesKHR;
public static AcquireNextImage2KHRDelegate AcquireNextImage2KHR;
#endregion
#region interop
public static Result CreateSwapchainKHR(Device device, ref SwapchainCreateInfoKHR pCreateInfo, ref SwapchainKHR pSwapchain, AllocationCallbacks pAllocator = null)
{
_SwapchainCreateInfoKHR info = new _SwapchainCreateInfoKHR(pCreateInfo);
Result res = _CreateSwapchainKHR(device, ref info, pAllocator, out pSwapchain);
info.destroy();
return res;
}
public unsafe static Result GetSwapchainImagesKHR(Device device, SwapchainKHR swapchain, ref UInt32 pSwapchainImageCount, Image[] pSwapchainImages)
{
fixed (Image* ptr = pSwapchainImages)
{
return _GetSwapchainImagesKHR(device, swapchain, ref pSwapchainImageCount, (IntPtr)ptr);
}
}
public unsafe static Result QueuePresentKHR(Queue queue, ref PresentInfoKHR pPresentInfo)
{
_PresentInfoKHR p = new _PresentInfoKHR(pPresentInfo);
int resultsCount = (pPresentInfo.results == null || pPresentInfo.results.Count == 0) ? 0 : pPresentInfo.results.Count;
Result res = _QueuePresentKHR(queue, ref p);
if(resultsCount > 0)
{
pPresentInfo.results = p.getResults(resultsCount);
}
p.destroy();
return res;
}
public static class KHR_swapchain
{
public static void init(VK.Device device)
{
VK._CreateSwapchainKHR = ExternalFunction.getDeviceFunction<VK.CreateSwapchainKHRDelegate>(device, "vkCreateSwapchainKHR");
VK.DestroySwapchainKHR = ExternalFunction.getDeviceFunction<VK.DestroySwapchainKHRDelegate>(device, "vkDestroySwapchainKHR");
VK._GetSwapchainImagesKHR = ExternalFunction.getDeviceFunction<VK.GetSwapchainImagesKHRDelegate>(device, "vkGetSwapchainImagesKHR");
VK.AcquireNextImageKHR = ExternalFunction.getDeviceFunction<VK.AcquireNextImageKHRDelegate>(device, "vkAcquireNextImageKHR");
VK._QueuePresentKHR = ExternalFunction.getDeviceFunction<VK.QueuePresentKHRDelegate>(device, "vkQueuePresentKHR");
VK.GetDeviceGroupPresentCapabilitiesKHR = ExternalFunction.getDeviceFunction<VK.GetDeviceGroupPresentCapabilitiesKHRDelegate>(device, "vkGetDeviceGroupPresentCapabilitiesKHR");
VK.GetDeviceGroupSurfacePresentModesKHR = ExternalFunction.getDeviceFunction<VK.GetDeviceGroupSurfacePresentModesKHRDelegate>(device, "vkGetDeviceGroupSurfacePresentModesKHR");
VK.GetPhysicalDevicePresentRectanglesKHR = ExternalFunction.getDeviceFunction<VK.GetPhysicalDevicePresentRectanglesKHRDelegate>(device, "vkGetPhysicalDevicePresentRectanglesKHR");
VK.AcquireNextImage2KHR = ExternalFunction.getDeviceFunction<VK.AcquireNextImage2KHRDelegate>(device, "vkAcquireNextImage2KHR");
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct _SwapchainCreateInfoKHR
{
public StructureType SType;
public IntPtr Next;
public SwapchainCreateFlagsKHR Flags;
public SurfaceKHR Surface;
public UInt32 MinImageCount;
public Format ImageFormat;
public ColorSpaceKHR ImageColorSpace;
public Extent2D ImageExtent;
public UInt32 ImageArrayLayers;
public ImageUsageFlags ImageUsage;
public SharingMode ImageSharingMode;
public UInt32 QueueFamilyIndexCount;
public IntPtr QueueFamilyIndices;
public SurfaceTransformFlagsKHR PreTransform;
public CompositeAlphaFlagsKHR CompositeAlpha;
public PresentModeKHR PresentMode;
public Bool32 Clipped;
public SwapchainKHR OldSwapchain;
public _SwapchainCreateInfoKHR(SwapchainCreateInfoKHR info)
{
SType = info.type;
Next = info.next;
Flags = info.flags;
Surface = info.surface;
MinImageCount = info.minImageCount;
ImageFormat = info.imageFormat;
ImageColorSpace = info.imageColorSpace;
ImageExtent = info.imageExtent;
ImageArrayLayers = info.imageArrayLayers;
ImageUsage = info.imageUsage;
ImageSharingMode = info.imageSharingMode;
QueueFamilyIndexCount = (UInt32)(info.queueFamilyIndices?.Count ?? 0);
QueueFamilyIndices = info.queueFamilyIndices != null ? Alloc.alloc(info.queueFamilyIndices) : IntPtr.Zero;
PreTransform = info.preTransform;
CompositeAlpha = info.compositeAlpha;
PresentMode = info.presentMode;
Clipped = info.clipped;
OldSwapchain = info.oldSwapchain;
}
public void destroy()
{
Alloc.free(QueueFamilyIndices);
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct _PresentInfoKHR
{
public StructureType SType;
public IntPtr Next;
public UInt32 WaitSemaphoreCount;
public IntPtr WaitSemaphores;
public UInt32 SwapchainCount;
public IntPtr Swapchains;
public IntPtr ImageIndices;
public IntPtr Results;
public _PresentInfoKHR(PresentInfoKHR info)
{
SType = info.type;
Next = info.next;
WaitSemaphoreCount = (UInt32)info.waitSemaphores.Count;
SwapchainCount = (UInt32)info.swapchains.Count;
WaitSemaphores = Alloc.alloc(info.waitSemaphores);
Swapchains = Alloc.alloc(info.swapchains);
ImageIndices = Alloc.alloc(info.indices);
List<UInt32> res;
if(info.results == null || info.results.Count == 0)
{
Results = IntPtr.Zero;
}
else
{
res = new List<UInt32>(info.results.Count);
Results = Alloc.alloc(res);
}
}
public List<Result> getResults(int count)
{
int[] vals = new int[count];
Marshal.Copy(Results, vals, 0, count);
List<Result> ret = new List<Result>(count);
foreach(int v in vals)
{
ret.Add((Result)v);
}
return ret;
}
public void destroy()
{
Alloc.free(WaitSemaphores);
Alloc.free(Swapchains);
Alloc.free(ImageIndices);
Alloc.free(Results);
}
}
#endregion
}
}
| |
#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.IO;
using System.Runtime.Serialization;
using System.Text;
#if !(NET20 || NET35 || SILVERLIGHT)
using System.Threading.Tasks;
#endif
using System.Xml;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Tests.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests
{
[TestFixture]
public class JsonConvertTest : TestFixtureBase
{
[Test]
public void DeserializeObject_EmptyString()
{
object result = JsonConvert.DeserializeObject(string.Empty);
Assert.IsNull(result);
}
[Test]
public void DeserializeObject_Integer()
{
object result = JsonConvert.DeserializeObject("1");
Assert.AreEqual(1L, result);
}
[Test]
public void DeserializeObject_Integer_EmptyString()
{
int? value = JsonConvert.DeserializeObject<int?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_Decimal_EmptyString()
{
decimal? value = JsonConvert.DeserializeObject<decimal?>("");
Assert.IsNull(value);
}
[Test]
public void DeserializeObject_DateTime_EmptyString()
{
DateTime? value = JsonConvert.DeserializeObject<DateTime?>("");
Assert.IsNull(value);
}
[Test]
public void EscapeJavaScriptString()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("How now brown cow?", '"', true);
Assert.AreEqual(@"""How now brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now 'brown' cow?", '"', true);
Assert.AreEqual(@"""How now 'brown' cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("How now <brown> cow?", '"', true);
Assert.AreEqual(@"""How now <brown> cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString(@"How
now brown cow?", '"', true);
Assert.AreEqual(@"""How \r\nnow brown cow?""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007", '"', true);
Assert.AreEqual(@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString("\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013", '"', true);
Assert.AreEqual(@"""\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013""", result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f ", '"', true);
Assert.AreEqual(@"""\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f """, result);
result =
JavaScriptUtils.ToEscapedJavaScriptString(
"!\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]", '"', true);
Assert.AreEqual(@"""!\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("^_`abcdefghijklmnopqrstuvwxyz{|}~", '"', true);
Assert.AreEqual(@"""^_`abcdefghijklmnopqrstuvwxyz{|}~""", result);
string data =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
string expected =
@"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
result = JavaScriptUtils.ToEscapedJavaScriptString(data, '"', true);
Assert.AreEqual(expected, result);
result = JavaScriptUtils.ToEscapedJavaScriptString("Fred's cat.", '\'', true);
Assert.AreEqual(result, @"'Fred\'s cat.'");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are you gentlemen?"" said Cats.", '"', true);
Assert.AreEqual(result, @"""\""How are you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"""How are' you gentlemen?"" said Cats.", '"', true);
Assert.AreEqual(result, @"""\""How are' you gentlemen?\"" said Cats.""");
result = JavaScriptUtils.ToEscapedJavaScriptString(@"Fred's ""cat"".", '\'', true);
Assert.AreEqual(result, @"'Fred\'s ""cat"".'");
result = JavaScriptUtils.ToEscapedJavaScriptString("\u001farray\u003caddress");
Assert.AreEqual(result, @"""\u001farray<address""");
}
[Test]
public void EscapeJavaScriptString_UnicodeLinefeeds()
{
string result;
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u0085' + "after", '"', true);
Assert.AreEqual(@"""before\u0085after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2028' + "after", '"', true);
Assert.AreEqual(@"""before\u2028after""", result);
result = JavaScriptUtils.ToEscapedJavaScriptString("before" + '\u2029' + "after", '"', true);
Assert.AreEqual(@"""before\u2029after""", result);
}
[Test]
public void ToStringInvalid()
{
ExceptionAssert.Throws<ArgumentException>("Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.",
() =>
{
JsonConvert.ToString(new Version(1, 0));
});
}
[Test]
public void GuidToString()
{
Guid guid = new Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D");
string json = JsonConvert.ToString(guid);
Assert.AreEqual(@"""bed7f4ea-1a96-11d2-8f08-00a0c9a6186d""", json);
}
[Test]
public void EnumToString()
{
string json = JsonConvert.ToString(StringComparison.CurrentCultureIgnoreCase);
Assert.AreEqual("1", json);
}
[Test]
public void ObjectToString()
{
object value;
value = 1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = 1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = 1.1m;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (float)1.1;
Assert.AreEqual("1.1", JsonConvert.ToString(value));
value = (short)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (long)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (byte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (uint)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ushort)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (sbyte)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = (ulong)1;
Assert.AreEqual("1", JsonConvert.ToString(value));
value = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""1970-01-01T00:00:00Z""", JsonConvert.ToString(value));
value = new DateTime(JsonConvert.InitialJavaScriptDateTicks, DateTimeKind.Utc);
Assert.AreEqual(@"""\/Date(0)\/""", JsonConvert.ToString((DateTime)value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind));
#if !PocketPC && !NET20
value = new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""1970-01-01T00:00:00+00:00""", JsonConvert.ToString(value));
value = new DateTimeOffset(JsonConvert.InitialJavaScriptDateTicks, TimeSpan.Zero);
Assert.AreEqual(@"""\/Date(0+0000)\/""", JsonConvert.ToString((DateTimeOffset)value, DateFormatHandling.MicrosoftDateFormat));
#endif
value = null;
Assert.AreEqual("null", JsonConvert.ToString(value));
#if !(NETFX_CORE || PORTABLE)
value = DBNull.Value;
Assert.AreEqual("null", JsonConvert.ToString(value));
#endif
value = "I am a string";
Assert.AreEqual(@"""I am a string""", JsonConvert.ToString(value));
value = true;
Assert.AreEqual("true", JsonConvert.ToString(value));
value = 'c';
Assert.AreEqual(@"""c""", JsonConvert.ToString(value));
}
[Test]
public void TestInvalidStrings()
{
ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.",
() =>
{
string orig = @"this is a string ""that has quotes"" ";
string serialized = JsonConvert.SerializeObject(orig);
// *** Make string invalid by stripping \" \"
serialized = serialized.Replace(@"\""", "\"");
JsonConvert.DeserializeObject<string>(serialized);
});
}
[Test]
public void DeserializeValueObjects()
{
int i = JsonConvert.DeserializeObject<int>("1");
Assert.AreEqual(1, i);
#if !PocketPC && !NET20
DateTimeOffset d = JsonConvert.DeserializeObject<DateTimeOffset>(@"""\/Date(-59011455539000+0000)\/""");
Assert.AreEqual(new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)), d);
#endif
bool b = JsonConvert.DeserializeObject<bool>("true");
Assert.AreEqual(true, b);
object n = JsonConvert.DeserializeObject<object>("null");
Assert.AreEqual(null, n);
object u = JsonConvert.DeserializeObject<object>("undefined");
Assert.AreEqual(null, u);
}
[Test]
public void FloatToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0));
Assert.AreEqual("1.0", JsonConvert.ToString(1d));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1d));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001));
Assert.AreEqual(JsonConvert.PositiveInfinity, JsonConvert.ToString(Double.PositiveInfinity));
Assert.AreEqual(JsonConvert.NegativeInfinity, JsonConvert.ToString(Double.NegativeInfinity));
Assert.AreEqual(JsonConvert.NaN, JsonConvert.ToString(Double.NaN));
}
[Test]
public void DecimalToString()
{
Assert.AreEqual("1.1", JsonConvert.ToString(1.1m));
Assert.AreEqual("1.11", JsonConvert.ToString(1.11m));
Assert.AreEqual("1.111", JsonConvert.ToString(1.111m));
Assert.AreEqual("1.1111", JsonConvert.ToString(1.1111m));
Assert.AreEqual("1.11111", JsonConvert.ToString(1.11111m));
Assert.AreEqual("1.111111", JsonConvert.ToString(1.111111m));
Assert.AreEqual("1.0", JsonConvert.ToString(1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1.0m));
Assert.AreEqual("-1.0", JsonConvert.ToString(-1m));
Assert.AreEqual("1.0", JsonConvert.ToString(1m));
Assert.AreEqual("1.01", JsonConvert.ToString(1.01m));
Assert.AreEqual("1.001", JsonConvert.ToString(1.001m));
Assert.AreEqual("79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MaxValue));
Assert.AreEqual("-79228162514264337593543950335.0", JsonConvert.ToString(Decimal.MinValue));
}
[Test]
public void StringEscaping()
{
string v = @"It's a good day
""sunshine""";
string json = JsonConvert.ToString(v);
Assert.AreEqual(@"""It's a good day\r\n\""sunshine\""""", json);
}
[Test]
public void WriteDateTime()
{
DateTimeResult result = null;
result = TestDateTime("DateTime Max", DateTime.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateRoundtrip);
Assert.AreEqual("9999-12-31T23:59:59.9999999" + GetOffset(DateTime.MaxValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("9999-12-31T23:59:59.9999999", result.IsoDateUnspecified);
Assert.AreEqual("9999-12-31T23:59:59.9999999Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999" + GetOffset(DateTime.MaxValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(253402300799999)\/", result.MsDateUtc);
DateTime year2000local = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Local);
string localToUtcDate = year2000local.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local", year2000local);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000local, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + GetOffset(year2000local, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000local) + @")\/", result.MsDateUtc);
DateTime millisecondsLocal = new DateTime(2000, 1, 1, 1, 1, 1, 999, DateTimeKind.Local);
localToUtcDate = millisecondsLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with milliseconds", millisecondsLocal);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01.999" + GetOffset(millisecondsLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01.999", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + GetOffset(millisecondsLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(millisecondsLocal) + @")\/", result.MsDateUtc);
DateTime ticksLocal = new DateTime(634663873826822481, DateTimeKind.Local);
localToUtcDate = ticksLocal.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK");
result = TestDateTime("DateTime Local with ticks", ticksLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateRoundtrip);
Assert.AreEqual("2012-03-03T16:03:02.6822481" + GetOffset(ticksLocal, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2012-03-03T16:03:02.6822481", result.IsoDateUnspecified);
Assert.AreEqual(localToUtcDate, result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + GetOffset(ticksLocal, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(ticksLocal) + @")\/", result.MsDateUtc);
DateTime year2000Unspecified = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified);
result = TestDateTime("DateTime Unspecified", year2000Unspecified);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateRoundtrip);
Assert.AreEqual("2000-01-01T01:01:01" + GetOffset(year2000Unspecified, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified) + GetOffset(year2000Unspecified, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(year2000Unspecified.ToLocalTime()) + @")\/", result.MsDateUtc);
DateTime year2000Utc = new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string utcTolocalDate = year2000Utc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Utc", year2000Utc);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(year2000Utc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("2000-01-01T01:01:01", result.IsoDateUnspecified);
Assert.AreEqual("2000-01-01T01:01:01Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000" + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(year2000Utc, DateTimeKind.Unspecified)) + GetOffset(year2000Utc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(946688461000)\/", result.MsDateUtc);
DateTime unixEpoc = new DateTime(621355968000000000, DateTimeKind.Utc);
utcTolocalDate = unixEpoc.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss");
result = TestDateTime("DateTime Unix Epoc", unixEpoc);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateRoundtrip);
Assert.AreEqual(utcTolocalDate + GetOffset(unixEpoc, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("1970-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("1970-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(0" + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(" + JsonConvert.ConvertDateTimeToJavaScriptTicks(DateTime.SpecifyKind(unixEpoc, DateTimeKind.Unspecified)) + GetOffset(unixEpoc, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(0)\/", result.MsDateUtc);
result = TestDateTime("DateTime Min", DateTime.MinValue);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(DateTime.MinValue, DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(DateTime.MinValue, DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
result = TestDateTime("DateTime Default", default(DateTime));
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateRoundtrip);
Assert.AreEqual("0001-01-01T00:00:00" + GetOffset(default(DateTime), DateFormatHandling.IsoDateFormat), result.IsoDateLocal);
Assert.AreEqual("0001-01-01T00:00:00", result.IsoDateUnspecified);
Assert.AreEqual("0001-01-01T00:00:00Z", result.IsoDateUtc);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000" + GetOffset(default(DateTime), DateFormatHandling.MicrosoftDateFormat) + @")\/", result.MsDateLocal);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUnspecified);
Assert.AreEqual(@"\/Date(-62135596800000)\/", result.MsDateUtc);
#if !NET20
result = TestDateTime("DateTimeOffset TimeSpan Zero", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero));
Assert.AreEqual("2000-01-01T01:01:01+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946688461000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1)));
Assert.AreEqual("2000-01-01T01:01:01+01:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946684861000+0100)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 1.5 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(1.5)));
Assert.AreEqual("2000-01-01T01:01:01+01:30", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946683061000+0130)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan 13 hour", new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)));
Assert.AreEqual("2000-01-01T01:01:01+13:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(946641661000+1300)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset TimeSpan with ticks", new DateTimeOffset(634663873826822481, TimeSpan.Zero));
Assert.AreEqual("2012-03-03T16:03:02.6822481+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(1330790582682+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Min", DateTimeOffset.MinValue);
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Max", DateTimeOffset.MaxValue);
Assert.AreEqual("9999-12-31T23:59:59.9999999+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(253402300799999+0000)\/", result.MsDateRoundtrip);
result = TestDateTime("DateTimeOffset Default", default(DateTimeOffset));
Assert.AreEqual("0001-01-01T00:00:00+00:00", result.IsoDateRoundtrip);
Assert.AreEqual(@"\/Date(-62135596800000+0000)\/", result.MsDateRoundtrip);
#endif
}
public class DateTimeResult
{
public string IsoDateRoundtrip { get; set; }
public string IsoDateLocal { get; set; }
public string IsoDateUnspecified { get; set; }
public string IsoDateUtc { get; set; }
public string MsDateRoundtrip { get; set; }
public string MsDateLocal { get; set; }
public string MsDateUnspecified { get; set; }
public string MsDateUtc { get; set; }
}
private DateTimeResult TestDateTime<T>(string name, T value)
{
Console.WriteLine(name);
DateTimeResult result = new DateTimeResult();
result.IsoDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.IsoDateLocal = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Local);
result.IsoDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Unspecified);
result.IsoDateUtc = TestDateTimeFormat(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.Utc);
}
result.MsDateRoundtrip = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.RoundtripKind);
if (value is DateTime)
{
result.MsDateLocal = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Local);
result.MsDateUnspecified = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Unspecified);
result.MsDateUtc = TestDateTimeFormat(value, DateFormatHandling.MicrosoftDateFormat, DateTimeZoneHandling.Utc);
}
TestDateTimeFormat(value, new IsoDateTimeConverter());
#if !NETFX_CORE
if (value is DateTime)
{
Console.WriteLine(XmlConvert.ToString((DateTime)(object)value, XmlDateTimeSerializationMode.RoundtripKind));
}
else
{
Console.WriteLine(XmlConvert.ToString((DateTimeOffset)(object)value));
}
#endif
#if !NET20
MemoryStream ms = new MemoryStream();
DataContractSerializer s = new DataContractSerializer(typeof(T));
s.WriteObject(ms, value);
string json = Encoding.UTF8.GetString(ms.ToArray(), 0, Convert.ToInt32(ms.Length));
Console.WriteLine(json);
#endif
Console.WriteLine();
return result;
}
private static string TestDateTimeFormat<T>(T value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
string date = null;
if (value is DateTime)
{
date = JsonConvert.ToString((DateTime)(object)value, format, timeZoneHandling);
}
else
{
#if !NET20
date = JsonConvert.ToString((DateTimeOffset)(object)value, format);
#endif
}
Console.WriteLine(format.ToString("g") + "-" + timeZoneHandling.ToString("g") + ": " + date);
if (timeZoneHandling == DateTimeZoneHandling.RoundtripKind)
{
T parsed = JsonConvert.DeserializeObject<T>(date);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception ex)
{
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks/10000)*10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
return date.Trim('"');
}
private static void TestDateTimeFormat<T>(T value, JsonConverter converter)
{
string date = Write(value, converter);
Console.WriteLine(converter.GetType().Name + ": " + date);
T parsed = Read<T>(date, converter);
try
{
Assert.AreEqual(value, parsed);
}
catch (Exception ex)
{
// JavaScript ticks aren't as precise, recheck after rounding
long valueTicks = GetTicks(value);
long parsedTicks = GetTicks(parsed);
valueTicks = (valueTicks / 10000) * 10000;
Assert.AreEqual(valueTicks, parsedTicks);
}
}
public static long GetTicks(object value)
{
return (value is DateTime) ? ((DateTime)value).Ticks : ((DateTimeOffset)value).Ticks;
}
public static string Write(object value, JsonConverter converter)
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
converter.WriteJson(writer, value, null);
writer.Flush();
return sw.ToString();
}
public static T Read<T>(string text, JsonConverter converter)
{
JsonTextReader reader = new JsonTextReader(new StringReader(text));
reader.ReadAsString();
return (T)converter.ReadJson(reader, typeof(T), null, null);
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
[Test]
public void Async()
{
Task<string> task = null;
task = JsonConvert.SerializeObjectAsync(42);
task.Wait();
Assert.AreEqual("42", task.Result);
task = JsonConvert.SerializeObjectAsync(new[] {1, 2, 3, 4, 5}, Formatting.Indented);
task.Wait();
Assert.AreEqual(@"[
1,
2,
3,
4,
5
]", task.Result);
task = JsonConvert.SerializeObjectAsync(DateTime.MaxValue, Formatting.None, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
task.Wait();
Assert.AreEqual(@"""\/Date(253402300799999)\/""", task.Result);
var taskObject = JsonConvert.DeserializeObjectAsync("[]");
taskObject.Wait();
CollectionAssert.AreEquivalent(new JArray(), (JArray)taskObject.Result);
Task<object> taskVersionArray = JsonConvert.DeserializeObjectAsync("['2.0']", typeof(Version[]), new JsonSerializerSettings
{
Converters = {new VersionConverter()}
});
taskVersionArray.Wait();
Version[] versionArray = (Version[])taskVersionArray.Result;
Assert.AreEqual(1, versionArray.Length);
Assert.AreEqual(2, versionArray[0].Major);
Task<int> taskInt = JsonConvert.DeserializeObjectAsync<int>("5");
taskInt.Wait();
Assert.AreEqual(5, taskInt.Result);
var taskVersion = JsonConvert.DeserializeObjectAsync<Version>("'2.0'", new JsonSerializerSettings
{
Converters = {new VersionConverter()}
});
taskVersion.Wait();
Assert.AreEqual(2, taskVersion.Result.Major);
Movie p = new Movie();
p.Name = "Existing,";
Task taskVoid = JsonConvert.PopulateObjectAsync("{'Name':'Appended'}", p, new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new JsonSerializerTest.StringAppenderConverter() }
});
taskVoid.Wait();
Assert.AreEqual("Existing,Appended", p.Name);
}
#endif
[Test]
public void SerializeObjectDateTimeZoneHandling()
{
string json = JsonConvert.SerializeObject(
new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Unspecified),
new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc
});
Assert.AreEqual(@"""2000-01-01T01:01:01Z""", json);
}
//[Test]
public void StackOverflowTest()
{
StringBuilder sb = new StringBuilder();
int depth = 900;
for (int i = 0; i < depth; i++)
{
sb.Append("{'A':");
}
// invalid json
sb.Append("{***}");
for (int i = 0; i < depth; i++)
{
sb.Append("}");
}
string json = sb.ToString();
JsonSerializer serializer = new JsonSerializer() { };
serializer.Deserialize<Nest>(new JsonTextReader(new StringReader(json)));
}
public class Nest
{
public Nest A { get; set; }
}
}
}
| |
// Message factory type.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// 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.
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/5/1
* Time: 11:17
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using GSF.Net.Snmp.Security;
namespace GSF.Net.Snmp.Messaging
{
/// <summary>
/// Factory that creates <see cref="ISnmpMessage"/> instances from byte format.
/// </summary>
public static class MessageFactory
{
/// <summary>
/// Creates <see cref="ISnmpMessage"/> instances from a string.
/// </summary>
/// <param name="bytes">Byte string.</param>
/// <param name="registry">The registry.</param>
/// <returns></returns>
public static IList<ISnmpMessage> ParseMessages(IEnumerable<char> bytes, UserRegistry registry)
{
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
return ParseMessages(ByteTool.Convert(bytes), registry);
}
/// <summary>
/// Creates <see cref="ISnmpMessage"/> instances from buffer.
/// </summary>
/// <param name="buffer">Buffer.</param>
/// <param name="registry">The registry.</param>
/// <returns></returns>
public static IList<ISnmpMessage> ParseMessages(byte[] buffer, UserRegistry registry)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
return ParseMessages(buffer, 0, buffer.Length, registry);
}
/// <summary>
/// Creates <see cref="ISnmpMessage"/> instances from buffer.
/// </summary>
/// <param name="buffer">Buffer.</param>
/// <param name="index">The index.</param>
/// <param name="length">The length.</param>
/// <param name="registry">The registry.</param>
/// <returns></returns>
public static IList<ISnmpMessage> ParseMessages(byte[] buffer, int index, int length, UserRegistry registry)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (registry == null)
{
throw new ArgumentNullException(nameof(registry));
}
IList<ISnmpMessage> result = new List<ISnmpMessage>();
using (Stream stream = new MemoryStream(buffer, index, length, true))
{
int first;
while ((first = stream.ReadByte()) != -1)
{
ISnmpMessage message = ParseMessage(first, stream, registry);
if (message == null)
{
continue;
}
result.Add(message);
}
}
return result;
}
private static ISnmpMessage ParseMessage(int first, Stream stream, UserRegistry registry)
{
ISnmpData array = DataFactory.CreateSnmpData(first, stream);
if (array == null)
{
return null;
}
if (array.TypeCode != SnmpType.Sequence)
{
throw new SnmpException("not an SNMP message");
}
Sequence body = (Sequence)array;
if (body.Length != 3 && body.Length != 4)
{
throw new SnmpException("not an SNMP message");
}
VersionCode version = (VersionCode)((Integer32)body[0]).ToInt32();
Header header;
SecurityParameters parameters;
IPrivacyProvider privacy;
Scope scope;
if (body.Length == 3)
{
header = Header.Empty;
parameters = SecurityParameters.Create((OctetString)body[1]);
privacy = DefaultPrivacyProvider.DefaultPair;
scope = new Scope((ISnmpPdu)body[2]);
}
else
{
header = new Header(body[1]);
parameters = new SecurityParameters((OctetString)body[2]);
privacy = registry.Find(parameters.UserName);
if (privacy == null)
{
// handle decryption exception.
return new MalformedMessage(header.MessageId, parameters.UserName, body[3]);
}
SnmpType code = body[3].TypeCode;
if (code == SnmpType.Sequence)
{
// v3 not encrypted
scope = new Scope((Sequence)body[3]);
}
else if (code == SnmpType.OctetString)
{
// v3 encrypted
try
{
scope = new Scope((Sequence)privacy.Decrypt(body[3], parameters));
}
catch (DecryptionException)
{
// handle decryption exception.
return new MalformedMessage(header.MessageId, parameters.UserName, body[3]);
}
}
else
{
throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "invalid v3 packets scoped data: {0}", code));
}
if (!privacy.VerifyHash(version, header, parameters, body[3], body.GetLengthBytes()))
{
parameters.IsInvalid = true;
}
}
SnmpType scopeCode = scope.Pdu.TypeCode;
try
{
switch (scopeCode)
{
case SnmpType.TrapV1Pdu:
return new TrapV1Message(body);
case SnmpType.TrapV2Pdu:
return new TrapV2Message(version, header, parameters, scope, privacy, body.GetLengthBytes());
case SnmpType.GetRequestPdu:
return new GetRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes());
case SnmpType.ResponsePdu:
return new ResponseMessage(version, header, parameters, scope, privacy, false, body.GetLengthBytes());
case SnmpType.SetRequestPdu:
return new SetRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes());
case SnmpType.GetNextRequestPdu:
return new GetNextRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes());
case SnmpType.GetBulkRequestPdu:
return new GetBulkRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes());
case SnmpType.ReportPdu:
return new ReportMessage(version, header, parameters, scope, privacy, body.GetLengthBytes());
case SnmpType.InformRequestPdu:
return new InformRequestMessage(version, header, parameters, scope, privacy, body.GetLengthBytes());
default:
throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "unsupported pdu: {0}", scopeCode));
}
}
catch (Exception ex)
{
if (ex is SnmpException)
{
throw;
}
throw new SnmpException("message construction exception", ex);
}
}
}
}
| |
/*Copyright (c) 2013-2015 Derrick Creamer
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 PosArrays;
//This file contains utility classes and extension methods. Some are meant to be used with 2D grids, while others are more general. (v8)
namespace Utilities{
public class Dict<TKey,TValue>{ //a Dictionary that returns the default value for keys that haven't been added
public Dictionary<TKey,TValue> d;
public TValue this[TKey key]{
get{
return d.ContainsKey(key)? d[key] : default(TValue);
}
set{
d[key] = value;
}
}
public Dict(){ d = new Dictionary<TKey,TValue>(); }
public Dict(Dict<TKey,TValue> d2){ d = new Dictionary<TKey, TValue>(d2.d); }
}
public struct cell{ //a position that holds an integer value, useful with priority queues
public pos p;
public int row{
get{
return p.row;
}
set{
p.row = value;
}
}
public int col{
get{
return p.col;
}
set{
p.col = value;
}
}
public int value;
public cell(int row_,int col_,int value_){
p = new pos(row_,col_);
value = value_;
}
}
public delegate int SortValue<T>(T t);
public class PriorityQueue<T>{
public LinkedList<T> list;
public SortValue<T> priority;
public PriorityQueue(SortValue<T> sort_value){
list = new LinkedList<T>();
priority = sort_value;
}
public void Add(T t){
if(list.First == null){
list.AddFirst(t);
}
else{
LinkedListNode<T> current = list.First;
while(true){
if(priority(t) < priority(current.Value)){
current = current.Next;
if(current == null){
list.AddLast(t);
break;
}
}
else{
list.AddBefore(current,t);
break;
}
}
}
}
public T Pop(){
T result = list.First.Value;
list.Remove(result);
return result;
}
}
public enum DistanceMetric{Manhattan,Chebyshev};
public static class U{ //for Utility, of course
public static DistanceMetric DefaultMetric = DistanceMetric.Chebyshev;
public static bool BoundsCheck<T>(this pos p,PosArray<T> array,bool allow_map_edges = true){
int h = array.objs.GetLength(0);
int w = array.objs.GetLength(1);
if(p.row < 0 || p.row > h-1 || p.col < 0 || p.col > w-1){
return false;
}
if(!allow_map_edges){
if(p.row == 0 || p.row == h-1 || p.col == 0 || p.col == w-1){
return false;
}
}
return true;
}
public static bool BoundsCheck<T>(this PosArray<T> array,pos p,bool allow_map_edges = true){
return p.BoundsCheck(array,allow_map_edges);
}
public static bool BoundsCheck<T>(this PosArray<T> array,int r,int c,bool allow_map_edges = true){
return new pos(r,c).BoundsCheck(array,allow_map_edges);
}
public static bool IsOnBorder<T>(this pos p,PosArray<T> array){
if(p.row == 0 || p.row == array.objs.GetLength(0)-1){
if(p.col == 0 || p.col == array.objs.GetLength(1)-1){
return true;
}
}
return false;
}
public static bool BoundsCheck<T>(this T[,] array,int r,int c){
int h = array.GetLength(0);
int w = array.GetLength(1);
if(r < 0 || r > h-1 || c < 0 || c > w-1){
return false;
}
return true;
}
public static int[] EightDirections = {8,9,6,3,2,1,4,7}; //these all start at 8 (up) and go clockwise.
public static int[] FourDirections = {8,6,2,4}; //the directions correspond to the numbers on a keyboard's numpad.
public static int[] DiagonalDirections = {9,3,1,7};
public static int[] NineDirections = {5,8,9,6,3,2,1,4,7}; //eight, plus the direction that corresponds to "here".
public static int RotateDir(this int dir,bool clockwise,int times = 1){
if(DefaultMetric == DistanceMetric.Chebyshev){
return dir.RotateEightWayDir(clockwise,times);
}
return dir.RotateFourWayDir(clockwise,times);
}
public static int RotateEightWayDir(this int dir,bool clockwise,int times = 1){
if(dir == 5){
return 5;
}
if(times < 0){
times = -times;
clockwise = !clockwise;
}
for(int i=0;i<times;++i){
switch(dir){
case 7:
dir = clockwise?8:4;
break;
case 8:
dir = clockwise?9:7;
break;
case 9:
dir = clockwise?6:8;
break;
case 4:
dir = clockwise?7:1;
break;
case 6:
dir = clockwise?3:9;
break;
case 1:
dir = clockwise?4:2;
break;
case 2:
dir = clockwise?1:3;
break;
case 3:
dir = clockwise?2:6;
break;
default:
return 0;
}
}
return dir;
}
public static int RotateFourWayDir(this int dir,bool clockwise,int times = 1){
if(dir == 5){
return 5;
}
if(times < 0){
times = -times;
clockwise = !clockwise;
}
for(int i=0;i<times;++i){
switch(dir){
case 8:
dir = clockwise?6:4;
break;
case 4:
dir = clockwise?8:2;
break;
case 6:
dir = clockwise?2:8;
break;
case 2:
dir = clockwise?4:6;
break;
default:
throw new ArgumentException("Rotate4WayDir accepts only 4-way directions: 2(down), 4(left), 5(neutral), 6(right), and 8(up).");
}
}
return dir;
}
public static List<int> GetArc(this int i,int distance,bool clockwise = true){ //returns a list of directions: the original direction plus some number of other adjacent directions. 'distance' is how far you want to go out on each side.
List<int> result = new List<int>();
for(int num = -distance;num <= distance;++num){
result.Add(i.RotateDir(clockwise,num));
}
return result;
}
public static int DirectionOf(this pos p,pos obj){
if(DefaultMetric == DistanceMetric.Chebyshev){
return p.EightWayDirectionOf(obj);
}
return p.FourWayDirectionOf(obj);
}
public static int EightWayDirectionOf(this pos p,pos obj){ //determines which of the 8 directions is closest to the actual direction. Ties go to the cardinal directions.
int row = p.row;
int col = p.col;
int dy = Math.Abs(obj.row - row);
int dx = Math.Abs(obj.col - col);
if(dy == 0){
if(col < obj.col){
return 6;
}
if(col > obj.col){
return 4;
}
else{
if(dx == 0){
return 5;
}
}
}
if(dx == 0){
if(row > obj.row){
return 8;
}
else{
if(row < obj.row){
return 2;
}
}
}
if(row+col == obj.row+obj.col){ //slope is -1
if(row > obj.row){
return 9;
}
else{
if(row < obj.row){
return 1;
}
}
}
if(row-col == obj.row-obj.col){ //slope is 1
if(row > obj.row){
return 7;
}
else{
if(row < obj.row){
return 3;
}
}
}
// calculate all other dirs here
int primary; //orthogonal
int secondary; //diagonal
int dprimary = Math.Min(dy,dx);
int dsecondary = Math.Max(dy,dx);
if(row < obj.row){ //down
if(col < obj.col){ //right
secondary = 3;
if(dx > dy){ //slope less than 1
primary = 6;
}
else{ //slope greater than 1
primary = 2;
}
}
else{ //left
secondary = 1;
if(dx > dy){ //slope less than 1
primary = 4;
}
else{ //slope greater than 1
primary = 2;
}
}
}
else{ //up
if(col < obj.col){ //right
secondary = 9;
if(dx > dy){ //slope less than 1
primary = 6;
}
else{ //slope greater than 1
primary = 8;
}
}
else{ //left
secondary = 7;
if(dx > dy){ //slope less than 1
primary = 4;
}
else{ //slope greater than 1
primary = 8;
}
}
}
int tiebreaker = primary;
float ratio = (float)dprimary / (float)dsecondary;
if(ratio < 0.5f){
return primary;
}
else{
if(ratio > 0.5f){
return secondary;
}
else{
return tiebreaker;
}
}
}
public static int FourWayDirectionOf(this pos p,pos obj){ //determines which of the 4 directions is closest to the actual direction. Ties go to the vertical directions.
int row = p.row;
int col = p.col;
int dy = Math.Abs(obj.row - row);
int dx = Math.Abs(obj.col - col);
if(dx == 0 && dy == 0){
return 5;
}
if(dx > dy){
if(obj.col > col){
return 6;
}
return 4;
}
if(obj.row > row){ //dx <= dy
return 2;
}
return 8;
}
public static int Get1DIndex(int r,int c,int num_cols){
return r * num_cols + c;
}
public static int DistanceFrom(this pos p,pos dest){ return p.DistanceFrom(dest.row,dest.col); }
public static int DistanceFrom(int r1,int c1,int r2,int c2){ return new pos(r1,c1).DistanceFrom(r2,c2); }
public static int DistanceFrom(this pos p,int r,int c){
if(DefaultMetric == DistanceMetric.Chebyshev){
return p.ChebyshevDistanceFrom(r,c);
}
return p.ManhattanDistanceFrom(r,c);
}
public static int ChebyshevDistanceFrom(this pos p,pos dest){ return p.ChebyshevDistanceFrom(dest.row,dest.col); }
public static int ChebyshevDistanceFrom(int r1,int c1,int r2,int c2){ return new pos(r1,c1).ChebyshevDistanceFrom(r2,c2); }
public static int ChebyshevDistanceFrom(this pos p,int r,int c){
int dy = Math.Abs(r-p.row);
int dx = Math.Abs(c-p.col);
if(dx > dy){
return dx;
}
else{
return dy;
}
}
public static int ManhattanDistanceFrom(this pos p,pos dest){ return p.ManhattanDistanceFrom(dest.row,dest.col); }
public static int ManhattanDistanceFrom(int r1,int c1,int r2,int c2){ return new pos(r1,c1).ManhattanDistanceFrom(r2,c2); }
public static int ManhattanDistanceFrom(this pos p,int r,int c){
int dy = Math.Abs(r-p.row);
int dx = Math.Abs(c-p.col);
return dx + dy;
}
public static int ChebyshevDistanceFromX10(this pos p,pos dest){ return p.ChebyshevDistanceFromX10(dest.row,dest.col); } //this is the same as DistanceFrom x 10
public static int ChebyshevDistanceFromX10(this pos p,int dest_r,int dest_c){ //note that distances are multiplied by 10 so that integer euclidean distances work properly
int dy = Math.Abs(p.row-dest_r) * 10;
int dx = Math.Abs(p.col-dest_c) * 10;
if(dx > dy){
return dx;
}
else{
return dy;
}
}
public static int ManhattanDistanceFromX10(this pos p,pos dest){ return p.ManhattanDistanceFromX10(dest.row,dest.col); }
public static int ManhattanDistanceFromX10(this pos p,int dest_r,int dest_c){
int dy = Math.Abs(p.row-dest_r) * 10; //these are x10 so they can be compared to the estimated euclidean one below.
int dx = Math.Abs(p.col-dest_c) * 10;
return dy + dx;
}
public static int ApproximateEuclideanDistanceFromX10(this pos p,pos dest){ return p.ApproximateEuclideanDistanceFromX10(dest.row,dest.col); }
public static int ApproximateEuclideanDistanceFromX10(this pos p,int dest_r,int dest_c){ //no trig here. a position 1 step away diagonally has a distance of 15, not 14 or 1.41.
int dy = Math.Abs(p.row-dest_r) * 10;
int dx = Math.Abs(p.col-dest_c) * 10;
if(dx > dy){
return dx + (dy/2);
}
else{
return dy + (dx/2);
}
}
public static List<pos> PositionsWithinDistance(this pos p,int dist,bool exclude_origin = false){
return p.PositionsWithinDistance<int>(dist,null,exclude_origin);
}
public static List<pos> PositionsWithinDistance<T>(this pos p,int dist,PosArray<T> array,bool exclude_origin = false){
if(DefaultMetric == DistanceMetric.Chebyshev){
return p.PositionsWithinChebyshevDistance(dist,array,exclude_origin);
}
return p.PositionsWithinManhattanDistance(dist,array,exclude_origin);
}
public static List<pos> PositionsWithinChebyshevDistance(this pos p,int dist,bool exclude_origin = false){
return p.PositionsWithinChebyshevDistance<int>(dist,null,exclude_origin);
}
public static List<pos> PositionsWithinChebyshevDistance<T>(this pos p,int dist,PosArray<T> array,bool exclude_origin = false){
List<pos> result = new List<pos>();
for(int i=p.row-dist;i<=p.row+dist;++i){
for(int j=p.col-dist;j<=p.col+dist;++j){
if(!exclude_origin || i != p.row || j != p.col){
if(array == null || array.BoundsCheck(i,j)){
result.Add(new pos(i,j));
}
}
}
}
return result;
}
public static List<pos> PositionsWithinManhattanDistance(this pos p,int dist,bool exclude_origin = false){
return p.PositionsWithinManhattanDistance<int>(dist,null,exclude_origin);
}
public static List<pos> PositionsWithinManhattanDistance<T>(this pos p,int dist,PosArray<T> array,bool exclude_origin = false){
List<pos> result = new List<pos>();
for(int i=p.row-dist;i<=p.row+dist;++i){
for(int j=p.col-dist;j<=p.col+dist;++j){
if(!exclude_origin || i != p.row || j != p.col){
if(array == null || array.BoundsCheck(i,j)){
if(p.ManhattanDistanceFrom(i,j) <= dist){ //room for improvement here.
result.Add(new pos(i,j));
}
}
}
}
}
return result;
}
public static List<pos> PositionsAtDistance(this pos p,int dist){
return p.PositionsAtDistance<int>(dist,null);
}
public static List<pos> PositionsAtDistance<T>(this pos p,int dist,PosArray<T> array){
if(DefaultMetric == DistanceMetric.Chebyshev){
return p.PositionsAtChebyshevDistance(dist,array);
}
return p.PositionsAtManhattanDistance(dist,array);
}
public static List<pos> PositionsAtChebyshevDistance(this pos p,int dist){
return p.PositionsAtChebyshevDistance<int>(dist,null);
}
public static List<pos> PositionsAtChebyshevDistance<T>(this pos p,int dist,PosArray<T> array){
List<pos> result = new List<pos>();
for(int i=p.row-dist;i<=p.row+dist;++i){
for(int j=p.col-dist;j<=p.col+dist;++j){
if(p.ChebyshevDistanceFrom(i,j) == dist){
if(array == null || array.BoundsCheck(i,j)){
result.Add(new pos(i,j));
}
}
else{
j = p.col+dist-1;
}
}
}
return result;
}
public static List<pos> PositionsAtManhattanDistance(this pos p,int dist){
return p.PositionsAtManhattanDistance<int>(dist,null);
}
public static List<pos> PositionsAtManhattanDistance<T>(this pos p,int dist,PosArray<T> array){
List<pos> result = new List<pos>();
for(int i=p.row-dist;i<=p.row+dist;++i){ //room for improvement
for(int j=p.col-dist;j<=p.col+dist;++j){
if(p.ManhattanDistanceFrom(i,j) == dist){
if(array == null || array.BoundsCheck(i,j)){
result.Add(new pos(i,j));
}
}
}
}
return result;
}
public static pos PosInDir(this pos p,int dir){
switch(dir){
case 7:
return new pos(p.row-1,p.col-1);
case 8:
return new pos(p.row-1,p.col);
case 9:
return new pos(p.row-1,p.col+1);
case 4:
return new pos(p.row,p.col-1);
case 5:
return p;
case 6:
return new pos(p.row,p.col+1);
case 1:
return new pos(p.row+1,p.col-1);
case 2:
return new pos(p.row+1,p.col);
case 3:
return new pos(p.row+1,p.col+1);
default:
return new pos(-1,-1);
}
}
public static T Random<T>(this List<T> l){ //now, some utility extension methods for lists.
if(l.Count == 0){
throw new IndexOutOfRangeException("This list is empty! It has no last value.");
}
return l[R.Roll(l.Count)-1];
}
public static T RandomOrDefault<T>(this List<T> l){ //now, some utility extension methods for lists.
if(l.Count == 0){
return default(T);
}
return l[R.Roll(l.Count)-1];
}
public static T RemoveRandom<T>(this List<T> l){
if(l.Count == 0){
throw new IndexOutOfRangeException("This list is empty! It has no last value.");
}
int idx = R.Roll(l.Count)-1;
T result = l[idx];
l.RemoveAt(idx);
return result;
}
public static T Last<T>(this List<T> l){
if(l.Count == 0){
throw new IndexOutOfRangeException("This list is empty! It has no last value.");
}
return l[l.Count-1];
}
public static T LastOrDefault<T>(this List<T> l){
if(l.Count == 0){
return default(T);
}
return l[l.Count-1];
}
public static T RemoveLast<T>(this List<T> l){
if(l.Count == 0){
throw new IndexOutOfRangeException("This list is empty! It has no last value.");
}
int idx = l.Count-1;
T result = l[idx];
l.RemoveAt(idx);
return result;
}
public static void AddUnique<T>(this List<T> l,T obj){
if(!l.Contains(obj)){
l.Add(obj);
}
}
public static List<T> Randomize<T>(this List<T> l){ //this one operates on the given list, rather than returning a new one
List<T> temp = new List<T>(l);
l.Clear();
while(temp.Count > 0){
l.Add(temp.RemoveRandom());
}
return l;
}
public delegate bool BooleanDelegate<T>(T t);
public static List<T> Where<T>(this List<T> l,BooleanDelegate<T> condition){
List<T> result = new List<T>();
foreach(T t in l){
if(condition(t)){
result.Add(t);
}
}
return result;
}
public static bool Any<T>(this List<T> l,BooleanDelegate<T> condition){
foreach(T t in l){
if(condition(t)){
return true;
}
}
return false;
}
public static bool All<T>(this List<T> l,BooleanDelegate<T> condition){
foreach(T t in l){
if(!condition(t)){
return false;
}
}
return true;
}
public delegate int IntegerDelegate<T>(T t);
public static List<T> WhereGreatest<T>(this List<T> l,IntegerDelegate<T> value){
List<T> result = new List<T>();
int highest = 0;
bool first = true;
foreach(T t in l){
int i = value(t);
if(first){
first = false;
highest = i;
result.Add(t);
}
else{
if(i > highest){
highest = i;
result.Clear();
result.Add(t);
}
else{
if(i == highest){
result.Add(t);
}
}
}
}
return result;
}
public static int Greatest<T>(this List<T> l,IntegerDelegate<T> value){ //if list is empty, returns int.MinValue
int highest = int.MinValue;
foreach(T t in l){
int i = value(t);
if(i > highest){
highest = i;
}
}
return highest;
}
public static List<T> WhereLeast<T>(this List<T> l,IntegerDelegate<T> value){
List<T> result = new List<T>();
int lowest = 0;
bool first = true;
foreach(T t in l){
int i = value(t);
if(first){
first = false;
lowest = i;
result.Add(t);
}
else{
if(i < lowest){
lowest = i;
result.Clear();
result.Add(t);
}
else{
if(i == lowest){
result.Add(t);
}
}
}
}
return result;
}
public static int Least<T>(this List<T> l,IntegerDelegate<T> value){ //if list is empty, returns int.MaxValue
int lowest = int.MaxValue;
foreach(T t in l){
int i = value(t);
if(i < lowest){
lowest = i;
}
}
return lowest;
}
public static void RemoveWhere<T>(this List<T> l,BooleanDelegate<T> condition){
List<T> removed = new List<T>();
foreach(T t in l){
if(condition(t)){
removed.Add(t);
}
}
foreach(T t in removed){
l.Remove(t);
}
}
public static int Modulo(this int i,int mod){ //true modulo, for wrapping in a specific range
int r = i % mod;
if(r < 0){
return r + mod;
}
else{
return r;
}
}
public static int IntDivide(this int i,int divisor){ //rounds down instead of toward zero, so -2 / 5 evaluates to -1, not zero.
return (i < 0 && divisor > 0)? (i - divisor + 1) / divisor : (i > 0 && divisor < 0)? (i - divisor - 1) / divisor : i / divisor;
}
public static int Cap(this int i,int max){ //todo: keep these or not?
if(i > max){
return max;
}
return i;
}
public static int Floor(this int i,int min){
if(i < min){
return min;
}
return i;
}
public static string PadOuter(this string s,int totalWidth){ //here's the missing counterpart to PadRight and PadLeft.
return s.PadOuter(totalWidth,' ');
}
public static string PadOuter(this string s,int totalWidth,char paddingChar){
if(s.Length >= totalWidth){
return s;
}
int added = totalWidth - s.Length;
string left = "";
for(int i=0;i<(added+1)/2;++i){ //todo: This seems to look better if it puts the extra space on the RIGHT, not the left. Consider changing.
left = left + paddingChar;
}
string right = "";
for(int i=0;i<added/2;++i){
right = right + paddingChar;
}
return left + s + right;
}
public static string Capitalize(this string s){
if(s.Length == 0){
return s;
}
char[] c = s.ToCharArray();
c[0] = Char.ToUpper(c[0]);
return new string(c);
}
public static List<pos> AllPositions<T>(this PosArray<T> array){
List<pos> result = new List<pos>();
int rows = array.objs.GetLength(0);
int cols = array.objs.GetLength(1);
for(int i=0;i<rows;++i){
for(int j=0;j<cols;++j){
result.Add(new pos(i,j));
}
}
return result;
}
public static List<pos> AllPositions<T>(this T[,] array){
List<pos> result = new List<pos>();
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for(int i=0;i<rows;++i){
for(int j=0;j<cols;++j){
result.Add(new pos(i,j));
}
}
return result;
}
public static pos RandomPosition<T>(this PosArray<T> array,bool allow_borders){
if(allow_borders){
return new pos(R.Between(0,array.objs.GetLength(0)-1),R.Between(0,array.objs.GetLength(1)-1));
}
else{
return new pos(R.Between(1,array.objs.GetLength(0)-2),R.Between(1,array.objs.GetLength(1)-2));
}
}
public static List<pos> PositionsWhere<T>(this PosArray<T> array,BooleanPositionDelegate condition){
return array.objs.PositionsWhere(condition);
}
public static List<pos> PositionsWhere<T>(this T[,] array,BooleanPositionDelegate condition){
List<pos> result = new List<pos>();
int rows = array.GetLength(0);
int cols = array.GetLength(1);
for(int i=0;i<rows;++i){
for(int j=0;j<cols;++j){
pos p = new pos(i,j);
if(condition(p)){
result.Add(p);
}
}
}
return result;
}
public static List<pos> PositionsWhereGreatest<T>(this PosArray<T> array,IntegerPositionDelegate value){ //are these useful with no Dijkstra specialization? I'm not sure.
return array.objs.PositionsWhereGreatest(value);
}
public static List<pos> PositionsWhereGreatest<T>(this T[,] array,IntegerPositionDelegate value){
List<pos> result = new List<pos>();
int rows = array.GetLength(0);
int cols = array.GetLength(1);
int highest = 0;
bool first = true;
for(int i=0;i<rows;++i){
for(int j=0;j<cols;++j){
pos p = new pos(i,j);
int val = value(p);
if(first){
first = false;
highest = val;
result.Add(p);
}
else{
if(val > highest){
highest = val;
result.Clear();
result.Add(p);
}
else{
if(val == highest){
result.Add(p);
}
}
}
}
}
return result;
}
public static List<pos> PositionsWhereLeast<T>(this PosArray<T> array,IntegerPositionDelegate value){
return array.objs.PositionsWhereLeast(value);
}
public static List<pos> PositionsWhereLeast<T>(this T[,] array,IntegerPositionDelegate value){
List<pos> result = new List<pos>();
int rows = array.GetLength(0);
int cols = array.GetLength(1);
int lowest = 0;
bool first = true;
for(int i=0;i<rows;++i){
for(int j=0;j<cols;++j){
pos p = new pos(i,j);
int val = value(p);
if(first){
first = false;
lowest = val;
result.Add(p);
}
else{
if(val < lowest){
lowest = val;
result.Clear();
result.Add(p);
}
else{
if(val == lowest){
result.Add(p);
}
}
}
}
}
return result;
}
public static List<pos> PositionsNearBorder<T>(this PosArray<T> array,int dist){
List<pos> result = new List<pos>();
if(dist <= 0){
return result;
}
int rows = array.objs.GetLength(0);
int cols = array.objs.GetLength(1);
if(dist * 2 >= rows && dist * 2 >= cols){
return array.AllPositions();
}
for(int i=0;i<rows;++i){
for(int j=0;j<cols;++j){
if(j == dist && i >= dist && i < rows-dist){
j = cols-dist;
}
result.Add(new pos(i,j));
}
}
return result;
}
public delegate bool BooleanPositionDelegate(pos p);
public static List<pos> GetFloodFillPositions<T>(this PosArray<T> array,pos origin,bool exclude_origin,BooleanPositionDelegate condition){
return array.GetFloodFillPositions(new List<pos>{origin},exclude_origin,condition);
}
public static List<pos> GetFloodFillPositions<T>(this PosArray<T> array,List<pos> origins,bool exclude_origins,BooleanPositionDelegate condition){
List<pos> result = new List<pos>(origins);
PosArray<bool> result_map = new PosArray<bool>(array.objs.GetLength(0),array.objs.GetLength(1));
foreach(pos origin in origins){
result_map[origin] = true;
}
List<pos> frontier = new List<pos>(origins);
while(frontier.Count > 0){
pos p = frontier.RemoveLast();
foreach(pos neighbor in p.PositionsAtDistance(1)){
if(neighbor.BoundsCheck(array) && !result_map[neighbor] && condition(neighbor)){
result_map[neighbor] = true;
frontier.Add(neighbor);
result.Add(neighbor);
}
}
}
if(exclude_origins){
foreach(pos origin in origins){
result.Remove(origin);
}
}
return result;
}
public static PosArray<bool> GetFloodFillArray<T>(this PosArray<T> array,pos origin,bool exclude_origin,BooleanPositionDelegate condition){
return array.GetFloodFillArray(new List<pos>{origin},exclude_origin,condition);
}
public static PosArray<bool> GetFloodFillArray<T>(this PosArray<T> array,List<pos> origins,bool exclude_origins,BooleanPositionDelegate condition){
PosArray<bool> result_map = new PosArray<bool>(array.objs.GetLength(0),array.objs.GetLength(1));
foreach(pos origin in origins){
result_map[origin] = true;
}
List<pos> frontier = new List<pos>(origins);
while(frontier.Count > 0){
pos p = frontier.RemoveLast();
foreach(pos neighbor in p.PositionsAtDistance(1)){
if(neighbor.BoundsCheck(array) && !result_map[neighbor] && condition(neighbor)){
result_map[neighbor] = true;
frontier.Add(neighbor);
}
}
}
if(exclude_origins){
foreach(pos origin in origins){
result_map[origin] = false;
}
}
return result_map;
}
public static List<pos> GetRandomizedFloodFillPositions<T>(this PosArray<T> array, pos origin,int desired_count,bool exclude_origin_from_count,bool exclude_origin_from_result,BooleanPositionDelegate condition){
return array.GetRandomizedFloodFillPositions(new List<pos>{origin},desired_count,exclude_origin_from_count,exclude_origin_from_result,condition);
}
public static List<pos> GetRandomizedFloodFillPositions<T>(this PosArray<T> array, List<pos> origins,int desired_count,bool exclude_origins_from_count,bool exclude_origins_from_result,BooleanPositionDelegate condition){
List<pos> result = new List<pos>();
PosArray<bool> result_map = new PosArray<bool>(array.objs.GetLength(0),array.objs.GetLength(1));
List<pos> frontier = new List<pos>();
int count = 0;
foreach(pos origin in origins){
result_map[origin] = true;
if(condition(origin)){
if(!exclude_origins_from_count){
++count;
}
if(!exclude_origins_from_result){
result.Add(origin);
}
}
foreach(pos neighbor in origin.PositionsAtDistance(1)){
if(neighbor.BoundsCheck(array) && !result_map[neighbor]){
result_map[neighbor] = true;
frontier.Add(neighbor);
}
}
}
while(frontier.Count > 0 && count < desired_count){
pos p = frontier.RemoveRandom();
if(condition(p)){
result.Add(p);
++count;
foreach(pos neighbor in p.PositionsAtDistance(1)){
if(neighbor.BoundsCheck(array) && !result_map[neighbor]){
result_map[neighbor] = true;
frontier.Add(neighbor);
}
}
}
}
return result;
}
public static int DijkstraMax = int.MaxValue;
public static int DijkstraMin = int.MinValue;
public static bool IsValidDijkstraValue(this int i){
if(i == DijkstraMin || i == DijkstraMax){
return false;
}
return true;
}
public delegate int IntegerPositionDelegate(pos p);
public delegate int EdgeCostDelegate(pos start,pos end);
public delegate bool EdgeBlockedDelegate(pos start,pos end);
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,List<pos> sources,BooleanPositionDelegate is_blocked){
return array.GetDijkstraMap(sources,x=>0,(p1,p2)=>is_blocked(p2),(p1,p2)=>1);
}
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,BooleanPositionDelegate is_source,BooleanPositionDelegate is_blocked){
return array.GetDijkstraMap(is_source,x=>0,(p1,p2)=>is_blocked(p2),(p1,p2)=>1);
}
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,List<pos> sources,BooleanPositionDelegate is_blocked,IntegerPositionDelegate get_cost){
return array.GetDijkstraMap(sources,x=>0,(p1,p2)=>is_blocked(p2),(p1,p2)=>get_cost(p2));
}
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,BooleanPositionDelegate is_source,BooleanPositionDelegate is_blocked,IntegerPositionDelegate get_cost){
return array.GetDijkstraMap(is_source,x=>0,(p1,p2)=>is_blocked(p2),(p1,p2)=>get_cost(p2));
}
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,List<pos> sources,IntegerPositionDelegate source_value,BooleanPositionDelegate is_blocked,IntegerPositionDelegate get_cost){
return array.GetDijkstraMap(sources,source_value,(p1,p2)=>is_blocked(p2),(p1,p2)=>get_cost(p2));
}
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,BooleanPositionDelegate is_source,IntegerPositionDelegate source_value,BooleanPositionDelegate is_blocked,IntegerPositionDelegate get_cost){
return array.GetDijkstraMap(is_source,source_value,(p1,p2)=>is_blocked(p2),(p1,p2)=>get_cost(p2));
}
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,List<pos> sources,IntegerPositionDelegate source_value,EdgeBlockedDelegate is_blocked,EdgeCostDelegate get_cost){
int height = array.objs.GetLength(0);
int width = array.objs.GetLength(1);
PosArray<int> map = new PosArray<int>(height,width);
PriorityQueue<pos> frontier = new PriorityQueue<pos>(x => -map[x]);
for(int i=0;i<height;++i){
for(int j=0;j<width;++j){
map[i,j] = DijkstraMax;
}
}
foreach(pos p in sources){
map[p] = source_value(p);
frontier.Add(p);
}
DijkstraScan(map,frontier,is_blocked,get_cost);
return map;
}
public static PosArray<int> GetDijkstraMap<T>(this PosArray<T> array,BooleanPositionDelegate is_source,IntegerPositionDelegate source_value,EdgeBlockedDelegate is_blocked,EdgeCostDelegate get_cost){
int height = array.objs.GetLength(0);
int width = array.objs.GetLength(1);
PosArray<int> map = new PosArray<int>(height,width);
PriorityQueue<pos> frontier = new PriorityQueue<pos>(x => -map[x]);
for(int i=0;i<height;++i){
for(int j=0;j<width;++j){
pos p = new pos(i,j);
if(is_source(p)){
map[p] = source_value(p);
frontier.Add(p);
}
else{
map[p] = DijkstraMax;
}
}
}
DijkstraScan(map,frontier,is_blocked,get_cost);
return map;
}
private static void DijkstraScan(PosArray<int> map,PriorityQueue<pos> frontier,EdgeBlockedDelegate is_blocked,EdgeCostDelegate get_cost){
while(frontier.list.Count > 0){
pos p = frontier.Pop();
foreach(pos neighbor in p.PositionsAtDistance(1)){
if(neighbor.BoundsCheck(map) && !is_blocked(p,neighbor)){
int cost = get_cost(p,neighbor);
if(map[neighbor] > map[p]+cost){
map[neighbor] = map[p]+cost;
frontier.Add(neighbor);
}
}
}
}
}
public static List<pos> GetAStarPath<T>(this PosArray<T> array,pos start,pos goal,BooleanPositionDelegate is_blocked,bool deterministic_results){
return array.GetAStarPath(start,goal,is_blocked,x=>1,1,deterministic_results);
}
public static List<pos> GetAStarPath<T>(this PosArray<T> array,pos start,pos goal,BooleanPositionDelegate is_blocked,IntegerPositionDelegate get_cost,int default_cost,bool deterministic_results){
int height = array.objs.GetLength(0);
int width = array.objs.GetLength(1);
PosArray<int> map = new PosArray<int>(height,width);
PriorityQueue<pos> frontier = new PriorityQueue<pos>(x => -(map[x] + x.DistanceFrom(goal)*default_cost));
for(int i=0;i<height;++i){
for(int j=0;j<width;++j){
if(is_blocked(new pos(i,j))){
map[i,j] = DijkstraMin;
}
else{
map[i,j] = DijkstraMax;
}
}
}
frontier.Add(start);
map[start] = 0;
while(frontier.list.Count > 0){
pos p = frontier.Pop();
if(p.Equals(goal)){
List<pos> result = new List<pos>();
pos current_position = goal;
while(true){
result.Add(current_position);
List<pos> valid = current_position.PositionsAtDistance(1,map).Where(x=>map[x].IsValidDijkstraValue() && map[x] < map[current_position]).WhereLeast(x=>map[x]).WhereLeast(x=>x.ApproximateEuclideanDistanceFromX10(current_position));
if(valid.Count > 0){
if(deterministic_results){
current_position = valid.Last();
}
else{
current_position = valid.Random();
}
if(current_position.Equals(start)){
result.Reverse();
return result;
}
}
else{
return null;
}
}
}
foreach(pos neighbor in p.PositionsAtDistance(1)){
if(neighbor.BoundsCheck(map)){
int cost = get_cost(neighbor);
if(map[neighbor] > map[p]+cost){
map[neighbor] = map[p]+cost;
frontier.Add(neighbor);
}
}
}
}
return null; //no path found
}
public static int PathingDistanceFrom<T>(this PosArray<T> array,pos start,pos goal,BooleanPositionDelegate is_blocked){
return array.PathingDistanceFrom(start,goal,is_blocked,x=>1,1);
}
public static int PathingDistanceFrom<T>(this PosArray<T> array,pos start,pos goal,BooleanPositionDelegate is_blocked,IntegerPositionDelegate get_cost,int default_cost){
int height = array.objs.GetLength(0);
int width = array.objs.GetLength(1);
PosArray<int> map = new PosArray<int>(height,width);
PriorityQueue<pos> frontier = new PriorityQueue<pos>(x => -(map[x] + x.DistanceFrom(goal)*default_cost));
for(int i=0;i<height;++i){
for(int j=0;j<width;++j){
if(is_blocked(new pos(i,j))){
map[i,j] = DijkstraMin;
}
else{
map[i,j] = DijkstraMax;
}
}
}
frontier.Add(start);
map[start] = 0;
while(frontier.list.Count > 0){
pos p = frontier.Pop();
if(p.Equals(goal)){
return map[p];
}
foreach(pos neighbor in p.PositionsAtDistance(1)){
if(neighbor.BoundsCheck(map)){
int cost = get_cost(neighbor);
if(map[neighbor] > map[p]+cost){
map[neighbor] = map[p]+cost;
frontier.Add(neighbor);
}
}
}
}
return -1; //no path found
}
public static T GetWrapped<T>(this PosArray<T> array,pos p){ //todo: do I use any of these?
return array.GetWrapped(p.row,p.col);
}
public static T GetWrapped<T>(this PosArray<T> array,int row,int col){
return array[row.Modulo(array.objs.GetLength(0)),col.Modulo(array.objs.GetLength(1))];
}
public static void SetWrapped<T>(this PosArray<T> array,pos p,T t){
array.SetWrapped(p.row,p.col,t);
}
public static void SetWrapped<T>(this PosArray<T> array,int row,int col,T t){
array[row.Modulo(array.objs.GetLength(0)),col.Modulo(array.objs.GetLength(1))] = t;
}
public static PosArray<float> GetNoise(int height,int width){
return GetNoise(Math.Max(height,width));
}
public static PosArray<float> GetNoise(int size){
int size2 = 2;
while(size2+1 < size){
size2 *= 2;
}
++size2; //power of two, plus one
PosArray<float> n = new PosArray<float>(size2,size2);
int step = 1;
while(DiamondStep(n,step)){
SquareStep(n,step);
++step;
}
return n;
}
private static bool DiamondStep(this PosArray<float> a,int step){
int divisions = 1; //divisions^2 is the number of squares
while(step > 1){
divisions *= 2;
--step;
}
int increment = a.objs.GetUpperBound(0) / divisions;
if(increment == 1){
return false; //done!
}
for(int i=0;i<divisions;++i){
for(int j=0;j<divisions;++j){
float total = 0;
total += a[i*increment,j*increment];
total += a[i*increment,(j+1)*increment];
total += a[(i+1)*increment,j*increment];
total += a[(i+1)*increment,(j+1)*increment];
total = total / 4;
double val = (R.r.NextDouble() - 0.5) * 2;
total += (float)(val / divisions);
a[i*increment + increment/2,j*increment + increment/2] = total;
}
}
return true;
}
private static void SquareStep(this PosArray<float> a,int step){
int divisions = 1;
while(step > 0){
divisions *= 2;
--step;
}
int increment = a.objs.GetUpperBound(0) / divisions;
for(int i=0;i<=divisions;++i){
for(int j=0;j<=divisions;++j){
if((i+j)%2 == 1){
float total = 0;
total += a.GetWrapped((i-1)*increment,j*increment);
total += a.GetWrapped(i*increment,(j-1)*increment);
total += a.GetWrapped(i*increment,(j+1)*increment);
total += a.GetWrapped((i+1)*increment,j*increment);
total = total / 4;
double val = (R.r.NextDouble() - 0.5) * 2;
total += (float)(val / (divisions/2));
a[i*increment,j*increment] = total;
}
}
}
}
}
public static class R{ //random methods
public static Random r = new Random();
public static void SetSeed(int seed){ r = new Random(seed); }
public static int Roll(int dice,int sides){
if(sides == 0){
return 0;
}
int total = 0;
for(int i=0;i<dice;++i){
total += r.Next(1,sides+1); //Next's maxvalue is exclusive, thus the +1
}
return total;
}
public static int Roll(int sides){
if(sides == 0){
return 0;
}
int total = 0;
total += r.Next(1,sides+1); //Next's maxvalue is exclusive, thus the +1
return total;
}
public static int Between(int a,int b){ //inclusive
int min = Math.Min(a,b);
int max = Math.Max(a,b);
return Roll((max-min)+1) + (min-1);
}
public static bool CoinFlip(){
return r.Next(1,3) == 2;
}
public static bool OneIn(int x){
return r.Next(1,x+1) == x;
}
public static bool PercentChance(int x){
return r.Next(1,101) <= x;
}
public static int Choose(params int[] choices){
int len = choices.Length;
if(len == 0){
throw new ArgumentException("The Choose method requires at least one argument.");
}
return choices[R.Between(0,len-1)];
}
}
public enum NumberType{Value,Range,Sequence,Delta};
public class Number{
public NumberType Type = NumberType.Value;
public int Value = 0;
public Number RangeMin = null;
public Number RangeMax = null;
public List<Number> Sequence = null;
public int sequence_index = 0;
public Number Delta = null; //todo: some of these should be properties, with validation on changes.
public static implicit operator int(Number n){
return n.GetValue();
}
public int GetValue(){ //also, need to enforce the requirement that every number eventually evaluates to an int.
switch(Type){
case NumberType.Range:
return R.Between(RangeMin.GetValue(),RangeMax.GetValue());
case NumberType.Sequence:
{
int result = Sequence[sequence_index].GetValue();
++sequence_index;
if(sequence_index == Sequence.Count){
sequence_index = 0;
}
return result;
}
case NumberType.Delta:
{
int result = Value;
Value += Delta.GetValue();
return result;
}
case NumberType.Value:
default:
return Value;
}
}
public static Number CreateValue(int value){
Number n = new Number();
n.Value = value;
return n;
}
public static Number CreateRange(Number min,Number max){
Number n = new Number();
n.Type = NumberType.Range;
n.RangeMin = min;
n.RangeMax = max;
return n;
}
public static Number CreateRange(int min,int max){
return CreateRange(CreateValue(min),CreateValue(max));
}
public static Number CreateRange(Number min,int max){
return CreateRange(min,CreateValue(max));
}
public static Number CreateRange(int min,Number max){
return CreateRange(CreateValue(min),max);
}
public static Number CreateSequence(){
Number n = new Number();
n.Type = NumberType.Sequence;
n.Sequence = new List<Number>();
return n;
}
public Number Add(int value){
if(Type != NumberType.Sequence){
throw new InvalidOperationException("This method can only be used with a Sequence");
}
Sequence.Add(CreateValue(value));
return this;
}
public Number Add(Number number){
if(Type != NumberType.Sequence){
throw new InvalidOperationException("This method can only be used with a Sequence");
}
Sequence.Add(number);
return this;
}
public static Number CreateDelta(int initial_value,Number delta){
Number n = new Number();
n.Type = NumberType.Delta;
n.Value = initial_value;
n.Delta = delta;
return n;
}
public static Number CreateDelta(int initial_value,int delta){
return CreateDelta(initial_value,CreateValue(delta));
}
}
public class FloatNumber{
public NumberType Type = NumberType.Value;
public float Value = 0;
public FloatNumber RangeMin = null;
public FloatNumber RangeMax = null;
public List<FloatNumber> Sequence = null;
public int sequence_index = 0;
public FloatNumber Delta = null; //todo: some of these should be properties, with validation on changes.
public static implicit operator float(FloatNumber n){
return n.GetValue();
}
public float GetValue(){ //also, need to enforce the requirement that every number eventually evaluates to a float.
switch(Type){
case NumberType.Range:
{
while(true){
float min = RangeMin.GetValue();
float max = RangeMax.GetValue();
float result = (float)(R.r.NextDouble() * (double)(max-min) + (double)min);
if(!float.IsInfinity(result) && !float.IsNaN(result)){
return result;
}
}
}
case NumberType.Sequence:
{
float result = Sequence[sequence_index].GetValue();
++sequence_index;
if(sequence_index == Sequence.Count){
sequence_index = 0;
}
return result;
}
case NumberType.Delta:
{
float result = Value;
Value += Delta.GetValue();
return result;
}
case NumberType.Value:
default:
return Value;
}
}
public static FloatNumber CreateValue(float value){
FloatNumber n = new FloatNumber();
n.Value = value;
return n;
}
public static FloatNumber CreateRange(FloatNumber min,FloatNumber max){
FloatNumber n = new FloatNumber();
n.Type = NumberType.Range;
n.RangeMin = min;
n.RangeMax = max;
return n;
}
public static FloatNumber CreateRange(float min,float max){
return CreateRange(CreateValue(min),CreateValue(max));
}
public static FloatNumber CreateRange(FloatNumber min,float max){
return CreateRange(min,CreateValue(max));
}
public static FloatNumber CreateRange(float min,FloatNumber max){
return CreateRange(CreateValue(min),max);
}
public static FloatNumber CreateSequence(){
FloatNumber n = new FloatNumber();
n.Type = NumberType.Sequence;
n.Sequence = new List<FloatNumber>();
return n;
}
public FloatNumber Add(float value){
if(Type != NumberType.Sequence){
throw new InvalidOperationException("This method can only be used with a Sequence");
}
Sequence.Add(CreateValue(value));
return this;
}
public FloatNumber Add(FloatNumber number){
if(Type != NumberType.Sequence){
throw new InvalidOperationException("This method can only be used with a Sequence");
}
Sequence.Add(number);
return this;
}
public static FloatNumber CreateDelta(float initial_value,FloatNumber delta){
FloatNumber n = new FloatNumber();
n.Type = NumberType.Delta;
n.Value = initial_value;
n.Delta = delta;
return n;
}
public static FloatNumber CreateDelta(float initial_value,float delta){
return CreateDelta(initial_value,CreateValue(delta));
}
}
}
| |
using System.Net.Mail;
using Moq;
using Shouldly;
using Xunit;
using System.IO;
using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Postal.AspNetCore;
using Microsoft.Extensions.Options;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
namespace Postal
{
public class EmailServiceTests
{
[Fact]
public async Task CreateMessage_returns_MailMessage_created_by_parser()
{
var html = @"Content-Type: text/html
To: test1@test.com
From: test2@test.com
Subject: Test Subject
<p>Hello, World!</p>";
var email = new Email("Test");
var renderer = new Mock<IEmailViewRender>();
renderer.Setup(r => r.RenderAsync(email)).Returns(Task.FromResult(html));
var parser = new Mock<IEmailParser>();
var emailOptions = new EmailServiceOptions();
emailOptions.CreateSmtpClient = () => null;
var options = new Mock<IOptions<EmailServiceOptions>>();
options.SetupGet(o => o.Value).Returns(emailOptions);
var logger = new Mock<ILogger<EmailService>>();
var service = new EmailService(renderer.Object, parser.Object, options.Object, logger.Object);
var expectedMailMessage = new MailMessage();
parser.Setup(p => p.ParseAsync(It.IsAny<string>(), email)).Returns(Task.FromResult(expectedMailMessage));
var actualMailMessage = await service.CreateMailMessageAsync(email);
actualMailMessage.ShouldBeOfType<MailMessage>();
parser.Verify();
renderer.Verify();
options.Verify();
}
[Fact]
public void SendAync_returns_a_Task_and_sends_email()
{
var html = @"Content-Type: text/html
To: test1@test.com
From: test2@test.com
Subject: Test Subject
<p>Hello, World!</p>";
var dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(dir);
try
{
using (var smtp = new SmtpClient())
{
smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
smtp.PickupDirectoryLocation = dir;
smtp.Host = "localhost"; // HACK: required by SmtpClient, but not actually used!
var email = new Email("Test");
var renderer = new Mock<IEmailViewRender>();
renderer.Setup(r => r.RenderAsync(email)).Returns(Task.FromResult(html));
var emailOptions = new EmailServiceOptions();
emailOptions.CreateSmtpClient = () => smtp;
var options = new Mock<IOptions<EmailServiceOptions>>();
options.SetupGet(o => o.Value).Returns(emailOptions);
var parser = new Mock<IEmailParser>();
var logger = new Mock<ILogger<EmailService>>();
var service = new EmailService(renderer.Object, parser.Object, options.Object, logger.Object);
parser.Setup(p => p.ParseAsync(It.IsAny<string>(), It.IsAny<Email>()))
.Returns(Task.FromResult(new MailMessage("test@test.com", "test@test.com")));
var sending = service.SendAsync(email);
sending.Wait();
Directory.GetFiles(dir).Length.ShouldBe(1);
parser.Verify();
renderer.Verify();
}
}
finally
{
Directory.Delete(dir, true);
}
}
[Fact]
public void Dependency_injection_default()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
var viewEngine = new Mock<IRazorViewEngine>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
var logger = new Mock<ILogger<EmailService>>();
var logger2 = new Mock<ILogger<TemplateService>>();
serviceCollection.AddSingleton(logger.Object);
serviceCollection.AddSingleton(logger2.Object);
serviceCollection.AddSingleton(viewEngine.Object);
serviceCollection.AddSingleton(tempDataProvider.Object);
serviceCollection.AddSingleton<IWebHostEnvironment>(hostingEnvironment.Object);
serviceCollection.AddSingleton<Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);
serviceCollection.AddPostal();
var services = serviceCollection.BuildServiceProvider();
var emailService = services.GetRequiredService<IEmailService>();
var emailOption = services.GetRequiredService<IOptions<EmailServiceOptions>>();
emailService.ShouldBeOfType<EmailService>();
var smtpClient = ((EmailService)emailService).CreateSmtpClient;
smtpClient.ShouldBe(emailOption.Value.CreateSmtpClient);
}
[Fact]
public void Dependency_injection_smtpOtions1()
{
var configBuilder = new ConfigurationBuilder();
configBuilder.AddInMemoryCollection(new Dictionary<string, string>()
{
{ "Host", "abc" },
{ "Port","12345"},
{ "FromAddress","qwerty"},
{ "UserName","zxcvbn"},
{ "Password","asdfgh"}
});
var _configuration = configBuilder.Build();
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
var viewEngine = new Mock<IRazorViewEngine>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
var logger = new Mock<ILogger<EmailService>>();
var logger2 = new Mock<ILogger<TemplateService>>();
serviceCollection.AddSingleton(logger.Object);
serviceCollection.AddSingleton(logger2.Object); serviceCollection.AddSingleton(viewEngine.Object);
serviceCollection.AddSingleton(viewEngine.Object);
serviceCollection.AddSingleton(tempDataProvider.Object);
serviceCollection.AddSingleton<IWebHostEnvironment>(hostingEnvironment.Object);
serviceCollection.AddSingleton<Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);
serviceCollection.Configure<EmailServiceOptions>(_configuration);
serviceCollection.AddPostal();
var services = serviceCollection.BuildServiceProvider();
var emailService = services.GetRequiredService<IEmailService>();
var emailOption = services.GetRequiredService<IOptions<EmailServiceOptions>>().Value;
EmailServiceOptions emailOptionField = GetInstanceField(typeof(EmailService), emailService, "options") as EmailServiceOptions;
emailOption.Host.ShouldBe("abc");
emailOption.Port.ShouldBe(12345);
emailOption.FromAddress.ShouldBe("qwerty");
emailOption.UserName.ShouldBe("zxcvbn");
emailOption.Password.ShouldBe("asdfgh");
emailOptionField.Host.ShouldBe("abc");
emailOptionField.Port.ShouldBe(12345);
emailOptionField.FromAddress.ShouldBe("qwerty");
emailOptionField.UserName.ShouldBe("zxcvbn");
emailOptionField.Password.ShouldBe("asdfgh");
}
[Fact]
public void Dependency_injection_smtpOtions2()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
var viewEngine = new Mock<IRazorViewEngine>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
var logger = new Mock<ILogger<EmailService>>();
var logger2 = new Mock<ILogger<TemplateService>>();
serviceCollection.AddSingleton(logger.Object);
serviceCollection.AddSingleton(logger2.Object);
serviceCollection.AddSingleton(viewEngine.Object);
serviceCollection.AddSingleton(tempDataProvider.Object);
serviceCollection.AddSingleton<IWebHostEnvironment>(hostingEnvironment.Object);
serviceCollection.AddSingleton<Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);
serviceCollection.Configure<EmailServiceOptions>(o =>
{
o.Host = "abc";
o.Port = 12345;
o.FromAddress = "qwerty";
o.UserName = "zxcvbn";
o.Password = "asdfgh";
o.CreateSmtpClient = () => new FactExcetpionForSmtpClient();
});
serviceCollection.AddPostal();
var services = serviceCollection.BuildServiceProvider();
var emailService = services.GetRequiredService<IEmailService>();
EmailServiceOptions emailOptionField = GetInstanceField(typeof(EmailService), emailService, "options") as EmailServiceOptions;
emailOptionField.Host.ShouldBe("abc");
emailOptionField.Port.ShouldBe(12345);
emailOptionField.FromAddress.ShouldBe("qwerty");
emailOptionField.UserName.ShouldBe("zxcvbn");
emailOptionField.Password.ShouldBe("asdfgh");
emailOptionField.CreateSmtpClient().ShouldBeOfType<FactExcetpionForSmtpClient>();
}
[Fact]
public void Dependency_injection_smtpOtions3()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
var viewEngine = new Mock<IRazorViewEngine>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
var logger = new Mock<ILogger<EmailService>>();
var logger2 = new Mock<ILogger<TemplateService>>();
serviceCollection.AddSingleton(logger.Object);
serviceCollection.AddSingleton(logger2.Object);
serviceCollection.AddSingleton(viewEngine.Object);
serviceCollection.AddSingleton(tempDataProvider.Object);
serviceCollection.AddSingleton<IWebHostEnvironment>(hostingEnvironment.Object);
serviceCollection.AddSingleton<Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);
serviceCollection.Configure<EmailServiceOptions>(o =>
{
o.CreateSmtpClient = () => throw new FactExcetpionForSmtpCreation();
});
serviceCollection.AddPostal();
var services = serviceCollection.BuildServiceProvider();
var emailService = services.GetRequiredService<IEmailService>();
Assert.ThrowsAsync<FactExcetpionForSmtpCreation>(() => emailService.SendAsync(new Email("testView")));
EmailServiceOptions emailOptionField = GetInstanceField(typeof(EmailService), emailService, "options") as EmailServiceOptions;
Assert.Throws<FactExcetpionForSmtpCreation>(() => emailOptionField.CreateSmtpClient());
}
[Fact]
public void Dependency_injection_generic_host()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
var viewEngine = new Mock<IRazorViewEngine>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<Microsoft.Extensions.Hosting.IHostEnvironment>();
var logger = new Mock<ILogger<EmailService>>();
var logger2 = new Mock<ILogger<TemplateService>>();
serviceCollection.AddSingleton(logger.Object);
serviceCollection.AddSingleton(logger2.Object);
serviceCollection.AddSingleton(viewEngine.Object);
serviceCollection.AddSingleton(tempDataProvider.Object);
serviceCollection.AddSingleton<Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);
serviceCollection.Configure<EmailServiceOptions>(o =>
{
o.CreateSmtpClient = () => throw new FactExcetpionForSmtpCreation();
});
serviceCollection.AddPostal();
var services = serviceCollection.BuildServiceProvider();
var emailService = services.GetRequiredService<IEmailService>();
Assert.ThrowsAsync<FactExcetpionForSmtpCreation>(() => emailService.SendAsync(new Email("testView")));
EmailServiceOptions emailOptionField = GetInstanceField(typeof(EmailService), emailService, "options") as EmailServiceOptions;
Assert.Throws<FactExcetpionForSmtpCreation>(() => emailOptionField.CreateSmtpClient());
}
private static object GetInstanceField(Type type, object instance, string fieldName)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Static;
FieldInfo field = type.GetField(fieldName, bindFlags);
return field.GetValue(instance);
}
class FactExcetpionForSmtpClient : SmtpClient
{
}
class FactExcetpionForSmtpCreation : Exception
{
}
}
}
| |
using System;
/// <summary>
/// Equals(System.Guid)
/// </summary>
public class GuidEquals1
{
#region Private Fields
private const int c_GUID_BYTE_ARRAY_SIZE = 16;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Equals with self instance");
try
{
Guid guid = Guid.Empty;
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.1", "Calling Equals with self instance returns false");
retVal = false;
}
// double check
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.2", "Calling Equals with self instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.3", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (!guid.Equals(guid))
{
TestLibrary.TestFramework.LogError("001.4", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Equals with equal instance");
try
{
Guid guid1 = Guid.Empty;
Guid guid2 = new Guid("00000000-0000-0000-0000-000000000000");
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.1", "Calling Equals with equal instance returns false");
retVal = false;
}
// double check
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.2", "Calling Equals with equal instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid1 = new Guid(bytes);
guid2 = new Guid(bytes);
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.3", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
// double check
if (!guid1.Equals(guid2))
{
TestLibrary.TestFramework.LogError("002.4", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Equals with not equal instance");
try
{
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000001"), false, "003.1") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000100"), false, "003.2") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000010000"), false, "003.3") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000001000000"), false, "003.4") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000100000000"), false, "003.5") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-010000000000"), false, "003.6") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0001-000000000000"), false, "003.7") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0100-000000000000"), false, "003.8") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0001-0000-000000000000"), false, "003.9") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0100-0000-000000000000"), false, "003.10") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0001-0000-0000-000000000000"), false, "003.11") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0100-0000-0000-000000000000"), false, "003.12") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000001-0000-0000-0000-000000000000"), false, "003.13") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000100-0000-0000-0000-000000000000"), false, "003.14") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00010000-0000-0000-0000-000000000000"), false, "003.15") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("01000000-0000-0000-0000-000000000000"), false, "003.16") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
GuidEquals1 test = new GuidEquals1();
TestLibrary.TestFramework.BeginTestCase("GuidEquals1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper(Guid guid1, Guid guid2, bool expected, string errorNo)
{
bool retVal = true;
bool actual = guid1.Equals(guid2);
if (actual != expected)
{
TestLibrary.TestFramework.LogError(errorNo, "Calling Equals returns wrong result");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2 + ", actual = " + actual + ", expected = " + expected);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace AutoMapper.Configuration
{
using static Expression;
using static AutoMapper.Internal.ExpressionFactory;
public class MemberConfigurationExpression<TSource, TDestination, TMember> : IMemberConfigurationExpression<TSource, TDestination, TMember>, IPropertyMapConfiguration
{
private readonly MemberInfo _destinationMember;
private LambdaExpression _sourceMember;
private readonly Type _sourceType;
protected List<Action<PropertyMap>> PropertyMapActions { get; } = new List<Action<PropertyMap>>();
public MemberConfigurationExpression(MemberInfo destinationMember, Type sourceType)
{
_destinationMember = destinationMember;
_sourceType = sourceType;
}
public MemberInfo DestinationMember => _destinationMember;
public void MapAtRuntime()
{
PropertyMapActions.Add(pm => pm.Inline = false);
}
public void NullSubstitute(object nullSubstitute)
{
PropertyMapActions.Add(pm => pm.NullSubstitute = nullSubstitute);
}
public void ResolveUsing<TValueResolver>()
where TValueResolver : IValueResolver<TSource, TDestination, TMember>
{
var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IValueResolver<TSource, TDestination, TMember>));
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing<TValueResolver, TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember)
where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>
{
var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>))
{
SourceMember = sourceMember
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing<TValueResolver, TSourceMember>(string sourceMemberName)
where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>
{
var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>))
{
SourceMemberName = sourceMemberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing(IValueResolver<TSource, TDestination, TMember> valueResolver)
{
var config = new ValueResolverConfiguration(valueResolver, typeof(IValueResolver<TSource, TDestination, TMember>));
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing<TSourceMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember> valueResolver, Expression<Func<TSource, TSourceMember>> sourceMember)
{
var config = new ValueResolverConfiguration(valueResolver, typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>))
{
SourceMember = sourceMember
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void ResolveUsing<TResult>(Func<TSource, TResult> resolver)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src);
pm.CustomResolver = expr;
});
}
public void ResolveUsing<TResult>(Func<TSource, TDestination, TResult> resolver)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src, dest);
pm.CustomResolver = expr;
});
}
public void ResolveUsing<TResult>(Func<TSource, TDestination, TMember, TResult> resolver)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src, dest, destMember);
pm.CustomResolver = expr;
});
}
public void ResolveUsing<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> resolver)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => resolver(src, dest, destMember, ctxt);
pm.CustomResolver = expr;
});
}
public void MapFrom<TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember)
{
MapFromUntyped(sourceMember);
}
internal void MapFromUntyped(LambdaExpression sourceExpression)
{
_sourceMember = sourceExpression;
PropertyMapActions.Add(pm => pm.MapFrom(sourceExpression));
}
public void MapFrom(string sourceMember)
{
_sourceType.GetFieldOrProperty(sourceMember);
PropertyMapActions.Add(pm => pm.MapFrom(sourceMember));
}
public void UseValue<TValue>(TValue value)
{
MapFrom(s => value);
}
public void Condition(Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember, destMember, ctxt);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, TDestination, TMember, TMember, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember, destMember);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, TDestination, TMember, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, TDestination, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src);
pm.Condition = expr;
});
}
public void PreCondition(Func<TSource, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, ResolutionContext, bool>> expr =
(src, ctxt) => condition(src);
pm.PreCondition = expr;
});
}
public void PreCondition(Func<ResolutionContext, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, ResolutionContext, bool>> expr =
(src, ctxt) => condition(ctxt);
pm.PreCondition = expr;
});
}
public void PreCondition(Func<TSource, ResolutionContext, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, ResolutionContext, bool>> expr =
(src, ctxt) => condition(src, ctxt);
pm.PreCondition = expr;
});
}
public void AddTransform(Expression<Func<TMember, TMember>> transformer)
{
PropertyMapActions.Add(pm =>
{
var config = new ValueTransformerConfiguration(typeof(TMember), transformer);
pm.AddValueTransformation(config);
});
}
public void ExplicitExpansion()
{
PropertyMapActions.Add(pm => pm.ExplicitExpansion = true);
}
public void Ignore() => Ignore(ignorePaths: true);
internal void Ignore(bool ignorePaths) =>
PropertyMapActions.Add(pm =>
{
pm.Ignored = true;
if(ignorePaths)
{
pm.TypeMap.IgnorePaths(DestinationMember);
}
});
public void AllowNull()
{
PropertyMapActions.Add(pm => pm.AllowNull = true);
}
public void UseDestinationValue()
{
PropertyMapActions.Add(pm => pm.UseDestinationValue = true);
}
public void SetMappingOrder(int mappingOrder)
{
PropertyMapActions.Add(pm => pm.MappingOrder = mappingOrder);
}
public void Configure(TypeMap typeMap)
{
var destMember = _destinationMember;
if(destMember.DeclaringType.IsGenericType())
{
destMember = typeMap.DestinationTypeDetails.PublicReadAccessors.Single(m => m.Name == destMember.Name);
}
var propertyMap = typeMap.FindOrCreatePropertyMapFor(destMember);
Apply(propertyMap);
}
private void Apply(PropertyMap propertyMap)
{
foreach(var action in PropertyMapActions)
{
action(propertyMap);
}
}
public IPropertyMapConfiguration Reverse()
{
var newSourceExpression = MemberAccessLambda(_destinationMember);
return PathConfigurationExpression<TDestination, TSource, object>.Create(_sourceMember, newSourceExpression);
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.MultiplayerModels;
using PlayFab.Internal;
using PlayFab.Json;
using PlayFab.Public;
namespace PlayFab
{
/// <summary>
/// API methods for managing multiplayer servers. API methods for managing parties.
/// </summary>
public static partial class PlayFabMultiplayerAPI
{
static PlayFabMultiplayerAPI() {}
/// <summary>
/// Clear the Client SessionToken which allows this Client to call API calls requiring login.
/// A new/fresh login will be required after calling this.
/// </summary>
public static void ForgetAllCredentials()
{
PlayFabHttp.ForgetAllCredentials();
}
/// <summary>
/// Creates a multiplayer server build with a custom container.
/// </summary>
public static void CreateBuildWithCustomContainer(CreateBuildWithCustomContainerRequest request, Action<CreateBuildWithCustomContainerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateBuildWithCustomContainer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Creates a multiplayer server build with a managed container.
/// </summary>
public static void CreateBuildWithManagedContainer(CreateBuildWithManagedContainerRequest request, Action<CreateBuildWithManagedContainerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateBuildWithManagedContainer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Creates a remote user to log on to a VM for a multiplayer server build.
/// </summary>
public static void CreateRemoteUser(CreateRemoteUserRequest request, Action<CreateRemoteUserResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateRemoteUser", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a multiplayer server game asset for a title.
/// </summary>
public static void DeleteAsset(DeleteAssetRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteAsset", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a multiplayer server build.
/// </summary>
public static void DeleteBuild(DeleteBuildRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteBuild", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a multiplayer server game certificate.
/// </summary>
public static void DeleteCertificate(DeleteCertificateRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteCertificate", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a remote user to log on to a VM for a multiplayer server build.
/// </summary>
public static void DeleteRemoteUser(DeleteRemoteUserRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteRemoteUser", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Enables the multiplayer server feature for a title.
/// </summary>
public static void EnableMultiplayerServersForTitle(EnableMultiplayerServersForTitleRequest request, Action<EnableMultiplayerServersForTitleResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/EnableMultiplayerServersForTitle", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets the URL to upload assets to.
/// </summary>
public static void GetAssetUploadUrl(GetAssetUploadUrlRequest request, Action<GetAssetUploadUrlResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetAssetUploadUrl", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets a multiplayer server build.
/// </summary>
public static void GetBuild(GetBuildRequest request, Action<GetBuildResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetBuild", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets the credentials to the container registry.
/// </summary>
public static void GetContainerRegistryCredentials(GetContainerRegistryCredentialsRequest request, Action<GetContainerRegistryCredentialsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetContainerRegistryCredentials", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets multiplayer server session details for a build.
/// </summary>
public static void GetMultiplayerServerDetails(GetMultiplayerServerDetailsRequest request, Action<GetMultiplayerServerDetailsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetMultiplayerServerDetails", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets a remote login endpoint to a VM that is hosting a multiplayer server build.
/// </summary>
public static void GetRemoteLoginEndpoint(GetRemoteLoginEndpointRequest request, Action<GetRemoteLoginEndpointResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetRemoteLoginEndpoint", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets the status of whether a title is enabled for the multiplayer server feature.
/// </summary>
public static void GetTitleEnabledForMultiplayerServersStatus(GetTitleEnabledForMultiplayerServersStatusRequest request, Action<GetTitleEnabledForMultiplayerServersStatusResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetTitleEnabledForMultiplayerServersStatus", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists archived multiplayer server sessions for a build.
/// </summary>
public static void ListArchivedMultiplayerServers(ListMultiplayerServersRequest request, Action<ListMultiplayerServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListArchivedMultiplayerServers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists multiplayer server game assets for a title.
/// </summary>
public static void ListAssetSummaries(ListAssetSummariesRequest request, Action<ListAssetSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListAssetSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists summarized details of all multiplayer server builds for a title.
/// </summary>
public static void ListBuildSummaries(ListBuildSummariesRequest request, Action<ListBuildSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListBuildSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists multiplayer server game certificates for a title.
/// </summary>
public static void ListCertificateSummaries(ListCertificateSummariesRequest request, Action<ListCertificateSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListCertificateSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists custom container images for a title.
/// </summary>
public static void ListContainerImages(ListContainerImagesRequest request, Action<ListContainerImagesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListContainerImages", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists the tags for a custom container image.
/// </summary>
public static void ListContainerImageTags(ListContainerImageTagsRequest request, Action<ListContainerImageTagsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListContainerImageTags", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists multiplayer server sessions for a build.
/// </summary>
public static void ListMultiplayerServers(ListMultiplayerServersRequest request, Action<ListMultiplayerServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListMultiplayerServers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists quality of service servers.
/// </summary>
public static void ListQosServers(ListQosServersRequest request, Action<ListQosServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListQosServers", request, AuthType.None, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists virtual machines for a title.
/// </summary>
public static void ListVirtualMachineSummaries(ListVirtualMachineSummariesRequest request, Action<ListVirtualMachineSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListVirtualMachineSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Request a multiplayer server session. Accepts tokens for title and if game client accesss is enabled, allows game client
/// to request a server with player entity token.
/// </summary>
public static void RequestMultiplayerServer(RequestMultiplayerServerRequest request, Action<RequestMultiplayerServerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/RequestMultiplayerServer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Rolls over the credentials to the container registry.
/// </summary>
public static void RolloverContainerRegistryCredentials(RolloverContainerRegistryCredentialsRequest request, Action<RolloverContainerRegistryCredentialsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/RolloverContainerRegistryCredentials", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Shuts down a multiplayer server session.
/// </summary>
public static void ShutdownMultiplayerServer(ShutdownMultiplayerServerRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ShutdownMultiplayerServer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Updates a multiplayer server build's regions.
/// </summary>
public static void UpdateBuildRegions(UpdateBuildRegionsRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/UpdateBuildRegions", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Uploads a multiplayer server game certificate.
/// </summary>
public static void UploadCertificate(UploadCertificateRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/UploadCertificate", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
}
}
#endif
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* 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.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Infoplus.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration
{
/// <summary>
/// Initializes a new instance of the Configuration class with different settings
/// </summary>
/// <param name="apiClient">Api client</param>
/// <param name="defaultHeader">Dictionary of default HTTP header</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="accessToken">accessToken</param>
/// <param name="apiKey">Dictionary of API key</param>
/// <param name="apiKeyPrefix">Dictionary of API key prefix</param>
/// <param name="tempFolderPath">Temp folder path</param>
/// <param name="dateTimeFormat">DateTime format string</param>
/// <param name="timeout">HTTP connection timeout (in milliseconds)</param>
/// <param name="userAgent">HTTP user agent</param>
public Configuration(ApiClient apiClient = null,
Dictionary<String, String> defaultHeader = null,
string username = null,
string password = null,
string accessToken = null,
Dictionary<String, String> apiKey = null,
Dictionary<String, String> apiKeyPrefix = null,
string tempFolderPath = null,
string dateTimeFormat = null,
int timeout = 100000,
string userAgent = "Swagger-Codegen/1.0/csharp"
)
{
setApiClientUsingDefault(apiClient);
Username = username;
Password = password;
AccessToken = accessToken;
UserAgent = userAgent;
if (defaultHeader != null)
DefaultHeader = defaultHeader;
if (apiKey != null)
ApiKey = apiKey;
if (apiKeyPrefix != null)
ApiKeyPrefix = apiKeyPrefix;
TempFolderPath = tempFolderPath;
DateTimeFormat = dateTimeFormat;
Timeout = timeout;
}
/// <summary>
/// Initializes a new instance of the Configuration class.
/// </summary>
/// <param name="apiClient">Api client.</param>
public Configuration(ApiClient apiClient)
{
setApiClientUsingDefault(apiClient);
}
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "1.0";
/// <summary>
/// Gets or sets the default Configuration.
/// </summary>
/// <value>Configuration.</value>
public static Configuration Default = new Configuration();
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
int status = (int) response.StatusCode;
if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content);
if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage);
return null;
};
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
/// <value>Timeout.</value>
public int Timeout
{
get { return ApiClient.RestClient.Timeout; }
set
{
if (ApiClient != null)
ApiClient.RestClient.Timeout = value;
}
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The API client.</value>
public ApiClient ApiClient;
/// <summary>
/// Set the ApiClient using Default or ApiClient instance.
/// </summary>
/// <param name="apiClient">An instance of ApiClient.</param>
/// <returns></returns>
public void setApiClientUsingDefault (ApiClient apiClient = null)
{
if (apiClient == null)
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = new ApiClient();
ApiClient = Default != null ? Default.ApiClient : new ApiClient();
}
else
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = apiClient;
ApiClient = apiClient;
}
}
private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the default header.
/// </summary>
public Dictionary<String, String> DefaultHeader
{
get { return _defaultHeaderMap; }
set
{
_defaultHeaderMap = value;
}
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
public void AddDefaultHeader(string key, string value)
{
_defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public String UserAgent { get; set; }
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public String Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public String Password { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
/// </summary>
/// <value>The access token.</value>
public String AccessToken { get; set; }
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public Dictionary<String, String> ApiKey = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>();
/// <summary>
/// Get the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix))
return apiKeyPrefix + " " + apiKeyValue;
else
return apiKeyValue;
}
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public String TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (String.IsNullOrEmpty(value))
{
_tempFolderPath = value;
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
Directory.CreateDirectory(value);
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
_tempFolderPath = value;
else
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
private const string ISO8601_DATETIME_FORMAT = "o";
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
/// <summary>
/// Gets or sets the the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public String DateTimeFormat
{
get
{
return _dateTimeFormat;
}
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static String ToDebugReport()
{
String report = "C# SDK (Infoplus) Debug Report:\n";
report += " OS: " + Environment.OSVersion + "\n";
report += " .NET Framework Version: " + Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(x => x.Name == "System.Core").First().Version.ToString() + "\n";
report += " Version of the API: v1.0\n";
report += " SDK Package Version: 1.0\n";
return report;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
using System;
namespace Apache.Geode.Client.UnitTests
{
[TestFixture]
[Category("group3")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientDurableCqTests : ThinClientRegionSteps
{
#region Private Members
private UnitProcess m_client1 = null;
private UnitProcess m_client2 = null;
private string[] m_client1DurableCqNames = { "client1DurableCQ1", "client1DurableCQ2", "client1DurableCQ3", "client1DurableCQ4", "client1DurableCQ5", "client1DurableCQ6", "client1DurableCQ7", "client1DurableCQ8" };
private string[] m_client2DurableCqNames = { "client2DurableCQ1", "client2DurableCQ2", "client2DurableCQ3", "client2DurableCQ4", "client2DurableCQ5", "client2DurableCQ6", "client2DurableCQ7", "client2DurableCQ8" };
private static string[] QueryRegionNames = { "ListDurableCqs" };
private static int m_NumberOfCqs = 110;
#endregion
#region Test helper methods
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2 };
}
public void InitDurableClient(string locators, int redundancyLevel,
string durableClientId, TimeSpan durableTimeout)
{
CacheHelper.InitConfigForDurable_Pool(locators, redundancyLevel, durableClientId, durableTimeout);
CacheHelper.CreateTCRegion_Pool(QueryRegionNames[0], true, true, (ICacheListener<object, object>)null, CacheHelper.Locators, "__TESTPOOL1_", true);
}
public void RegisterCqsClient1(bool isRecycle)
{
Util.Log("Registering Cqs for client1.");
CqAttributesFactory<object, object> cqAf = new CqAttributesFactory<object, object>();
CqAttributes<object, object> attributes = cqAf.Create();
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
if (!isRecycle)
{
qs.NewCq(m_client1DurableCqNames[0], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[1], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[2], "Select * From /" + QueryRegionNames[0], attributes, false).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[3], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, false).ExecuteWithInitialResults();
}
else
{
qs.NewCq(m_client1DurableCqNames[4], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[5], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[6], "Select * From /" + QueryRegionNames[0], attributes, false).ExecuteWithInitialResults();
qs.NewCq(m_client1DurableCqNames[7], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, false).ExecuteWithInitialResults();
}
}
public void RegisterCqsClient1MultipleChunks()
{
Util.Log("Registering Cqs for client1 for multiple chunks.");
CqAttributesFactory<object, object> cqAf = new CqAttributesFactory<object, object>();
CqAttributes<object, object> attributes = cqAf.Create();
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
for (int i = 0; i < m_NumberOfCqs; i++)
qs.NewCq("MyCq_" + i.ToString(), "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
}
public void RegisterCqsClient2(bool isRecycle)
{
Util.Log("Registering Cqs for client2.");
CqAttributesFactory<object, object> cqAf = new CqAttributesFactory<object, object>();
CqAttributes<object, object> attributes = cqAf.Create();
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
if (!isRecycle)
{
qs.NewCq(m_client2DurableCqNames[0], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[1], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[2], "Select * From /" + QueryRegionNames[0], attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[3], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, true).ExecuteWithInitialResults();
}
else
{
qs.NewCq(m_client2DurableCqNames[4], "Select * From /" + QueryRegionNames[0] + " where id = 1", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[5], "Select * From /" + QueryRegionNames[0] + " where id = 10", attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[6], "Select * From /" + QueryRegionNames[0], attributes, true).ExecuteWithInitialResults();
qs.NewCq(m_client2DurableCqNames[7], "Select * From /" + QueryRegionNames[0] + " where id = 3", attributes, true).ExecuteWithInitialResults();
}
}
public void VerifyDurableCqListClient1MultipleChunks()
{
Util.Log("Verifying durable Cqs for client1.");
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
Assert.AreEqual(m_NumberOfCqs, durableCqList.Count, "Durable CQ count sholuld be %d", m_NumberOfCqs);
Util.Log("Completed verifying durable Cqs for client1.");
}
public void VerifyDurableCqListClient1(bool isRecycle)
{
Util.Log("Verifying durable Cqs for client1.");
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
if (!isRecycle)
{
Assert.AreEqual(2, durableCqList.Count, "Durable CQ count sholuld be 2");
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[1]));
}
else
{
Assert.AreEqual(4, durableCqList.Count, "Durable CQ count sholuld be 4");
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[1]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[4]));
Assert.AreEqual(true, durableCqList.Contains(m_client1DurableCqNames[5]));
}
Util.Log("Completed verifying durable Cqs for client1.");
}
public void VerifyDurableCqListClient2(bool isRecycle)
{
Util.Log("Verifying durable Cqs for client2.");
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
if (!isRecycle)
{
Assert.AreEqual(4, durableCqList.Count, "Durable CQ count sholuld be 4");
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[1]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[2]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[3]));
}
else
{
Assert.AreEqual(8, durableCqList.Count, "Durable CQ count sholuld be 8");
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[0]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[1]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[2]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[3]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[4]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[5]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[6]));
Assert.AreEqual(true, durableCqList.Contains(m_client2DurableCqNames[7]));
}
}
public void VerifyEmptyDurableCqListClient1()
{
Util.Log("Verifying empty durable Cqs for client1.");
var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
System.Collections.Generic.List<string> durableCqList = qs.GetAllDurableCqsFromServer();
Assert.AreNotEqual(null, durableCqList);
Assert.AreEqual(0, durableCqList.Count, "Durable CQ list sholuld be empty");
}
private void RunTestGetDurableCqsFromServer()
{
try
{
CacheHelper.SetupJavaServers(true, "cacheserverDurableCqs.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cache server 1 started");
m_client1.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient1", TimeSpan.FromSeconds(300));
m_client2.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient2", TimeSpan.FromSeconds(300));
Util.Log("client initialization done.");
m_client1.Call(RegisterCqsClient1, false);
m_client2.Call(RegisterCqsClient2, false);
Util.Log("Registered DurableCQs.");
m_client1.Call(VerifyDurableCqListClient1, false);
m_client2.Call(VerifyDurableCqListClient2, false);
Util.Log("Verified DurableCQ List.");
}
finally
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
}
}
private void RunTestGetDurableCqsFromServerCyclicClients()
{
try
{
CacheHelper.SetupJavaServers(true, "cacheserverDurableCqs.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cache server 1 started");
m_client1.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient1", TimeSpan.FromSeconds(300));
m_client2.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient2", TimeSpan.FromSeconds(300));
Util.Log("client initialization done.");
m_client1.Call(RegisterCqsClient1, false);
m_client2.Call(RegisterCqsClient2, false);
Util.Log("Registered DurableCQs.");
m_client1.Call(VerifyDurableCqListClient1, false);
m_client1.Call(VerifyDurableCqListClient1, false);
Util.Log("Verified DurableCQ List.");
m_client1.Call(CacheHelper.CloseKeepAlive);
m_client2.Call(CacheHelper.CloseKeepAlive);
m_client1.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient1", TimeSpan.FromSeconds(300));
m_client2.Call(InitDurableClient, CacheHelper.Locators, 0, "DurableClient2", TimeSpan.FromSeconds(300));
Util.Log("client re-initialization done.");
m_client1.Call(RegisterCqsClient1, true);
m_client2.Call(RegisterCqsClient2, true);
Util.Log("Registered DurableCQs.");
m_client1.Call(VerifyDurableCqListClient1, true);
m_client1.Call(VerifyDurableCqListClient1, true);
Util.Log("Verified DurableCQ List.");
}
finally
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaLocator(1);
}
}
[TestFixtureSetUp]
public override void InitTests()
{
base.InitTests();
}
[TestFixtureTearDown]
public override void EndTests()
{
m_client1.Exit();
m_client2.Exit();
base.EndTests();
}
[SetUp]
public override void InitTest()
{
base.InitTest();
}
[TearDown]
public override void EndTest()
{
m_client1.Call(CacheHelper.Close);
m_client2.Call(CacheHelper.Close);
base.EndTest();
}
#endregion
#region Tests
[Test]
public void TestGetDurableCqsFromServerWithLocator()
{
RunTestGetDurableCqsFromServer();
}
[Test]
public void TestGetDurableCqsFromServerCyclicClientsWithLocator()
{
RunTestGetDurableCqsFromServerCyclicClients();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Tools.Compiler.Native
{
public class NativeCompileSettings
{
private const BuildConfiguration DefaultBuiltType = BuildConfiguration.debug;
private const NativeIntermediateMode DefaultNativeModel = NativeIntermediateMode.ryujit;
private const ArchitectureMode DefaultArchitectureMode = ArchitectureMode.x64;
private string _inputManagedAssemblyPath;
private string _appDepSdkPath;
private string _ilcPath;
private string _ilcSdkPath;
private string _outputDirectory;
private string _intermediateDirectory;
private string _logPath;
private string _ilcArgs;
private readonly List<string> _referencePaths;
private readonly List<string> _linkLibPaths;
private string _cppCompilerFlags;
public string LogPath
{
get { return _logPath; }
set { _logPath = Path.GetFullPath(value); }
}
public string InputManagedAssemblyPath
{
get
{
return _inputManagedAssemblyPath;
}
set
{
if(!File.Exists(value))
{
throw new Exception($"Could not find the input managed assembly: {value}");
}
_inputManagedAssemblyPath = Path.GetFullPath(value);
}
}
public string OutputDirectory
{
get
{
return _outputDirectory ?? GetDefaultOutputDirectory();
}
set
{
_outputDirectory = value;
}
}
public string IntermediateDirectory
{
get
{
return _intermediateDirectory ?? GetDefaultIntermediateDirectory();
}
set
{
_intermediateDirectory = value;
}
}
public BuildConfiguration BuildType { get; set; }
public ArchitectureMode Architecture { get; set; }
public NativeIntermediateMode NativeMode { get; set; }
public OSMode OS { get; set; }
public IEnumerable<string> ReferencePaths
{
get
{
return _referencePaths;
}
}
// Optional Customization Points (Can be null)
public string IlcArgs
{
get { return _ilcArgs; }
set { _ilcArgs = value; }
}
public IEnumerable<string> LinkLibPaths => _linkLibPaths;
// Required Customization Points (Must have default)
public string AppDepSDKPath {
get
{
return _appDepSdkPath;
}
set
{
if (!Directory.Exists(value))
{
throw new Exception($"AppDepSDK Directory does not exist: {value}.");
}
_appDepSdkPath = value;
}
}
public string IlcPath
{
get
{
return _ilcPath;
}
set
{
if (!Directory.Exists(value))
{
throw new Exception($"ILC Directory does not exist: {value}.");
}
_ilcPath = value;
}
}
public string IlcSdkPath
{
get
{
return _ilcSdkPath;
}
set
{
if (!Directory.Exists(value))
{
throw new Exception($"ILC SDK Directory does not exist: {value}.");
}
_ilcSdkPath = value;
}
}
public string CppCompilerFlags
{
get
{
return _cppCompilerFlags;
}
set
{
_cppCompilerFlags = value;
}
}
private NativeCompileSettings()
{
_linkLibPaths = new List<string>();
IlcPath = AppContext.BaseDirectory;
// By default, ILC SDK Path is assumed to be the same folder as ILC path
IlcSdkPath = IlcPath;
Architecture = DefaultArchitectureMode;
BuildType = DefaultBuiltType;
NativeMode = DefaultNativeModel;
AppDepSDKPath = Path.Combine(AppContext.BaseDirectory, "appdepsdk");
_referencePaths = new List<string>(Directory.EnumerateFiles(AppDepSDKPath, "*.dll"));
}
public static NativeCompileSettings Default
{
get
{
var defaultNativeCompileSettings = new NativeCompileSettings
{
OS = RuntimeInformationExtensions.GetCurrentOS()
};
return defaultNativeCompileSettings;
}
}
public string DetermineFinalOutputPath()
{
var outputDirectory = OutputDirectory;
var filename = Path.GetFileNameWithoutExtension(InputManagedAssemblyPath);
var outFile = Path.Combine(outputDirectory, filename + Constants.ExeSuffix);
return outFile;
}
public void AddReference(string reference)
{
_referencePaths.Add(Path.GetFullPath(reference));
}
public void AddLinkLibPath(string linkLibPath)
{
_linkLibPaths.Add(linkLibPath);
}
private string GetDefaultOutputDirectory()
{
return GetOutputDirectory(Constants.BinDirectoryName);
}
private string GetDefaultIntermediateDirectory()
{
return GetOutputDirectory(Constants.ObjDirectoryName);
}
private string GetOutputDirectory(string beginsWith)
{
var dir = Path.Combine(beginsWith, Architecture.ToString(), BuildType.ToString(), "native");
return Path.GetFullPath(dir);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
{
public static class ActualApiResponseMetadataFactory
{
/// <summary>
/// This method looks at individual return statments and attempts to parse the status code and the return type.
/// Given a <see cref="MethodDeclarationSyntax"/> for an action, this method inspects return statements in the body.
/// If the returned type is not assignable from IActionResult, it assumes that an "object" value is being returned. e.g. return new Person();
/// For return statements returning an action result, it attempts to infer the status code and return type. Helper methods in controller,
/// values set in initializer and new-ing up an IActionResult instance are supported.
/// </summary>
internal static bool TryGetActualResponseMetadata(
in ApiControllerSymbolCache symbolCache,
IMethodBodyBaseOperation methodBody,
CancellationToken cancellationToken,
out IList<ActualApiResponseMetadata> actualResponseMetadata)
{
var localActualResponseMetadata = new List<ActualApiResponseMetadata>();
var localSymbolCache = symbolCache;
var allReturnStatementsReadable = true;
void AnalyzeResponseExpression(IReturnOperation returnOperation)
{
var responseMetadata = InspectReturnOperation(
localSymbolCache,
returnOperation);
if (responseMetadata is { } value)
{
localActualResponseMetadata.Add(value);
}
else
{
allReturnStatementsReadable = false;
}
}
foreach (var operation in GetReturnStatements(methodBody))
{
AnalyzeResponseExpression(operation);
}
actualResponseMetadata = localActualResponseMetadata;
return allReturnStatementsReadable;
}
internal static ActualApiResponseMetadata? InspectReturnOperation(
in ApiControllerSymbolCache symbolCache,
IReturnOperation returnOperation)
{
var returnedValue = returnOperation.ReturnedValue;
if (returnedValue is null || returnedValue is IInvalidOperation)
{
return null;
}
// Covers conversion in the `IActionResult GetResult => NotFound()` case.
// Multiple conversions can happen for ActionResult<T>, hence a while loop.
while (returnedValue is IConversionOperation conversion)
{
returnedValue = conversion.Operand;
}
var statementReturnType = returnedValue.Type;
if (!symbolCache.IActionResult.IsAssignableFrom(statementReturnType))
{
// Return expression is not an instance of IActionResult. Must be returning the "model".
return new ActualApiResponseMetadata(returnOperation, statementReturnType);
}
var defaultStatusCodeAttribute = statementReturnType
.GetAttributes(symbolCache.DefaultStatusCodeAttribute, inherit: true)
.FirstOrDefault();
var statusCode = GetDefaultStatusCode(defaultStatusCodeAttribute);
ITypeSymbol? returnType = null;
switch (returnedValue)
{
case IInvocationOperation invocation:
{
// Covers the 'return StatusCode(200)' case.
var result = InspectMethodArguments(invocation.Arguments);
statusCode = result.statusCode ?? statusCode;
returnType = result.returnType;
break;
}
case IObjectCreationOperation creation:
{
// Read values from 'return new StatusCodeResult(200) case.
var result = InspectMethodArguments(creation.Arguments);
statusCode = result.statusCode ?? statusCode;
returnType = result.returnType;
// Read values from property assignments e.g. 'return new ObjectResult(...) { StatusCode = 200 }'.
// Property assignments override constructor assigned values and defaults.
if (creation.Initializer is not null)
{
result = InspectInitializers(symbolCache, creation.Initializer);
statusCode = result.statusCode ?? statusCode;
returnType = result.returnType ?? returnType;
}
break;
}
}
if (statusCode == null)
{
return null;
}
return new ActualApiResponseMetadata(returnOperation, statusCode.Value, returnType);
}
private static (int? statusCode, ITypeSymbol? returnType) InspectInitializers(
in ApiControllerSymbolCache symbolCache,
IObjectOrCollectionInitializerOperation initializer)
{
int? statusCode = null;
ITypeSymbol? typeSymbol = null;
foreach (var child in initializer.Children)
{
if (child is not IAssignmentOperation assignmentOperation ||
assignmentOperation.Target is not IPropertyReferenceOperation propertyReference)
{
continue;
}
var property = propertyReference.Property;
if (IsInterfaceImplementation(property, symbolCache.StatusCodeActionResultStatusProperty))
{
// Look for assignments to IStatusCodeActionResult.StatusCode
if (TryGetStatusCode(assignmentOperation.Value, out var statusCodeValue))
{
// new StatusCodeResult { StatusCode = someLocal };
statusCode = statusCodeValue;
}
}
else if (HasAttributeNamed(property, ApiSymbolNames.ActionResultObjectValueAttribute))
{
// Look for assignment to a property annotated with [ActionResultObjectValue]
typeSymbol = assignmentOperation.Type;
}
}
return (statusCode, typeSymbol);
}
private static (int? statusCode, ITypeSymbol? returnType) InspectMethodArguments(ImmutableArray<IArgumentOperation> arguments)
{
int? statusCode = null;
ITypeSymbol? typeSymbol = null;
foreach (var argument in arguments)
{
var parameter = argument.Parameter;
if (HasAttributeNamed(parameter, ApiSymbolNames.ActionResultStatusCodeAttribute))
{
if (TryGetStatusCode(argument.Value, out var statusCodeValue))
{
statusCode = statusCodeValue;
}
}
if (HasAttributeNamed(parameter, ApiSymbolNames.ActionResultObjectValueAttribute))
{
var operation = argument.Value;
if (operation is IConversionOperation conversionOperation)
{
// new BadRequest((object)MyDataType);
operation = conversionOperation.Operand;
}
typeSymbol = operation.Type;
}
}
return (statusCode, typeSymbol);
}
private static bool TryGetStatusCode(
IOperation operation,
out int statusCode)
{
if (operation is IConversionOperation conversion)
{
// Could be an implicit conversation from int -> int?
operation = conversion.Operand;
}
if (operation.ConstantValue is { HasValue: true } constant)
{
// Covers the 'return StatusCode(200)' case.
statusCode = (int)constant.Value;
return true;
}
if (operation is IMemberReferenceOperation memberReference)
{
if (memberReference.Member is IFieldSymbol field && field.HasConstantValue && field.ConstantValue is int constantStatusCode)
{
// Covers the 'return StatusCode(StatusCodes.Status200OK)' case.
// It also covers the 'return StatusCode(StatusCode)' case, where 'StatusCode' is a constant field.
statusCode = constantStatusCode;
return true;
}
}
else if (operation is ILocalReferenceOperation localReference)
{
if (localReference.ConstantValue is { HasValue: true } localConstant)
{
// Covers the 'return StatusCode(statusCode)' case, where 'statusCode' is a local constant.
statusCode = (int)localConstant.Value;
return true;
}
}
statusCode = 0;
return false;
}
internal static int? GetDefaultStatusCode(AttributeData attribute)
{
if (attribute != null &&
attribute.ConstructorArguments.Length == 1 &&
attribute.ConstructorArguments[0].Kind == TypedConstantKind.Primitive &&
attribute.ConstructorArguments[0].Value is int statusCode)
{
return statusCode;
}
return null;
}
private static bool IsInterfaceImplementation(IPropertySymbol property, IPropertySymbol statusCodeActionResultStatusProperty)
{
if (property.Name != statusCodeActionResultStatusProperty.Name)
{
return false;
}
for (var i = 0; i < property.ExplicitInterfaceImplementations.Length; i++)
{
if (SymbolEqualityComparer.Default.Equals(property.ExplicitInterfaceImplementations[i], statusCodeActionResultStatusProperty))
{
return true;
}
}
var implementedProperty = property.ContainingType.FindImplementationForInterfaceMember(statusCodeActionResultStatusProperty);
return SymbolEqualityComparer.Default.Equals(implementedProperty, property);
}
private static bool HasAttributeNamed(ISymbol symbol, string attributeName)
{
var attributes = symbol.GetAttributes();
var length = attributes.Length;
for (var i = 0; i < length; i++)
{
if (attributes[i].AttributeClass.Name == attributeName)
{
return true;
}
}
return false;
}
private static IEnumerable<IReturnOperation> GetReturnStatements(IMethodBodyBaseOperation method)
{
foreach (var returnOperation in method.Descendants().OfType<IReturnOperation>())
{
if (!AncestorIsLocalFunction(returnOperation))
{
yield return returnOperation;
}
}
bool AncestorIsLocalFunction(IReturnOperation operation)
{
var parent = operation.Parent;
while (parent != method)
{
if (parent is ILocalFunctionOperation or IAnonymousFunctionOperation)
{
return true;
}
parent = parent.Parent;
}
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
// This implementation uses the System.Net.Http.WinHttpHandler class on Windows. Other platforms will need to use
// their own platform specific implementation.
public partial class HttpClientHandler : HttpMessageHandler
{
private readonly WinHttpHandler _winHttpHandler;
private readonly ManagedHandler _managedHandler;
private readonly DiagnosticsHandler _diagnosticsHandler;
private bool _useProxy;
private bool _disposed;
public HttpClientHandler()
{
if (UseManagedHandler)
{
_managedHandler = new ManagedHandler();
_diagnosticsHandler = new DiagnosticsHandler(_managedHandler);
}
else
{
_winHttpHandler = new WinHttpHandler();
_diagnosticsHandler = new DiagnosticsHandler(_winHttpHandler);
// Adjust defaults to match current .NET Desktop HttpClientHandler (based on HWR stack).
AllowAutoRedirect = true;
AutomaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
UseProxy = true;
UseCookies = true;
CookieContainer = new CookieContainer();
_winHttpHandler.DefaultProxyCredentials = null;
_winHttpHandler.ServerCredentials = null;
// The existing .NET Desktop HttpClientHandler based on the HWR stack uses only WinINet registry
// settings for the proxy. This also includes supporting the "Automatic Detect a proxy" using
// WPAD protocol and PAC file. So, for app-compat, we will do the same for the default proxy setting.
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
_winHttpHandler.Proxy = null;
// Since the granular WinHttpHandler timeout properties are not exposed via the HttpClientHandler API,
// we need to set them to infinite and allow the HttpClient.Timeout property to have precedence.
_winHttpHandler.ReceiveHeadersTimeout = Timeout.InfiniteTimeSpan;
_winHttpHandler.ReceiveDataTimeout = Timeout.InfiniteTimeSpan;
_winHttpHandler.SendTimeout = Timeout.InfiniteTimeSpan;
}
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
((HttpMessageHandler)_winHttpHandler ?? _managedHandler).Dispose();
}
base.Dispose(disposing);
}
public virtual bool SupportsAutomaticDecompression => true;
public virtual bool SupportsProxy => true;
public virtual bool SupportsRedirectConfiguration => true;
public bool UseCookies
{
get => _winHttpHandler != null ? _winHttpHandler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer : _managedHandler.UseCookies;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.CookieUsePolicy = value ? CookieUsePolicy.UseSpecifiedCookieContainer : CookieUsePolicy.IgnoreCookies;
}
else
{
_managedHandler.UseCookies = value;
}
}
}
public CookieContainer CookieContainer
{
get => _winHttpHandler != null ? _winHttpHandler.CookieContainer : _managedHandler.CookieContainer;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.CookieContainer = value;
}
else
{
_managedHandler.CookieContainer = value;
}
}
}
public ClientCertificateOption ClientCertificateOptions
{
get => _winHttpHandler != null ? _winHttpHandler.ClientCertificateOption : _managedHandler.ClientCertificateOptions;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.ClientCertificateOption = value;
}
else
{
_managedHandler.ClientCertificateOptions = value;
}
}
}
public DecompressionMethods AutomaticDecompression
{
get => _winHttpHandler != null ? _winHttpHandler.AutomaticDecompression : _managedHandler.AutomaticDecompression;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.AutomaticDecompression = value;
}
else
{
_managedHandler.AutomaticDecompression = value;
}
}
}
public bool UseProxy
{
get => _winHttpHandler != null ? _useProxy : _managedHandler.UseProxy;
set
{
if (_winHttpHandler != null)
{
_useProxy = value;
}
else
{
_managedHandler.UseProxy = value;
}
}
}
public IWebProxy Proxy
{
get => _winHttpHandler != null ? _winHttpHandler.Proxy : _managedHandler.Proxy;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.Proxy = value;
}
else
{
_managedHandler.Proxy = value;
}
}
}
public ICredentials DefaultProxyCredentials
{
get => _winHttpHandler != null ? _winHttpHandler.DefaultProxyCredentials : _managedHandler.DefaultProxyCredentials;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.DefaultProxyCredentials = value;
}
else
{
_managedHandler.DefaultProxyCredentials = value;
}
}
}
public bool PreAuthenticate
{
get => _winHttpHandler != null ? _winHttpHandler.PreAuthenticate : _managedHandler.PreAuthenticate;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.PreAuthenticate = value;
}
else
{
_managedHandler.PreAuthenticate = value;
}
}
}
public bool UseDefaultCredentials
{
// WinHttpHandler doesn't have a separate UseDefaultCredentials property. There
// is just a ServerCredentials property. So, we need to map the behavior.
//
// This property only affect .ServerCredentials and not .DefaultProxyCredentials.
get => _winHttpHandler != null ? _winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials : _managedHandler.UseDefaultCredentials;
set
{
if (_winHttpHandler != null)
{
if (value)
{
_winHttpHandler.ServerCredentials = CredentialCache.DefaultCredentials;
}
else
{
if (_winHttpHandler.ServerCredentials == CredentialCache.DefaultCredentials)
{
// Only clear out the ServerCredentials property if it was a DefaultCredentials.
_winHttpHandler.ServerCredentials = null;
}
}
}
else
{
_managedHandler.UseDefaultCredentials = value;
}
}
}
public ICredentials Credentials
{
get => _winHttpHandler != null ? _winHttpHandler.ServerCredentials : _managedHandler.Credentials;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.ServerCredentials = value;
}
else
{
_managedHandler.Credentials = value;
}
}
}
public bool AllowAutoRedirect
{
get => _winHttpHandler != null ? _winHttpHandler.AutomaticRedirection : _managedHandler.AllowAutoRedirect;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.AutomaticRedirection = value;
}
else
{
_managedHandler.AllowAutoRedirect = value;
}
}
}
public int MaxAutomaticRedirections
{
get => _winHttpHandler != null ? _winHttpHandler.MaxAutomaticRedirections : _managedHandler.MaxAutomaticRedirections;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.MaxAutomaticRedirections = value;
}
else
{
_managedHandler.MaxAutomaticRedirections = value;
}
}
}
public int MaxConnectionsPerServer
{
get => _winHttpHandler != null ? _winHttpHandler.MaxConnectionsPerServer : _managedHandler.MaxConnectionsPerServer;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.MaxConnectionsPerServer = value;
}
else
{
_managedHandler.MaxConnectionsPerServer = value;
}
}
}
public int MaxResponseHeadersLength
{
get => _winHttpHandler != null ? _winHttpHandler.MaxResponseHeadersLength : _managedHandler.MaxResponseHeadersLength;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.MaxResponseHeadersLength = value;
}
else
{
_managedHandler.MaxResponseHeadersLength = value;
}
}
}
public X509CertificateCollection ClientCertificates => _winHttpHandler != null ?
_winHttpHandler.ClientCertificates :
_managedHandler.ClientCertificates;
public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback
{
get => _winHttpHandler != null ? _winHttpHandler.ServerCertificateValidationCallback : _managedHandler.ServerCertificateCustomValidationCallback;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.ServerCertificateValidationCallback = value;
}
else
{
_managedHandler.ServerCertificateCustomValidationCallback = value;
}
}
}
public bool CheckCertificateRevocationList
{
get => _winHttpHandler != null ? _winHttpHandler.CheckCertificateRevocationList : _managedHandler.CheckCertificateRevocationList;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.CheckCertificateRevocationList = value;
}
else
{
_managedHandler.CheckCertificateRevocationList = value;
}
}
}
public SslProtocols SslProtocols
{
get => _winHttpHandler != null ? _winHttpHandler.SslProtocols : _managedHandler.SslProtocols;
set
{
if (_winHttpHandler != null)
{
_winHttpHandler.SslProtocols = value;
}
else
{
_managedHandler.SslProtocols = value;
}
}
}
public IDictionary<String, object> Properties => _winHttpHandler != null ?
_winHttpHandler.Properties :
_managedHandler.Properties;
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (_winHttpHandler != null)
{
// Get current value of WindowsProxyUsePolicy. Only call its WinHttpHandler
// property setter if the value needs to change.
var oldProxyUsePolicy = _winHttpHandler.WindowsProxyUsePolicy;
if (_useProxy)
{
if (_winHttpHandler.Proxy == null)
{
if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseWinInetProxy)
{
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy;
}
}
else
{
if (oldProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy;
}
}
}
else
{
if (oldProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy)
{
_winHttpHandler.WindowsProxyUsePolicy = WindowsProxyUsePolicy.DoNotUseProxy;
}
}
return DiagnosticsHandler.IsEnabled() ?
_diagnosticsHandler.SendAsync(request, cancellationToken) :
_winHttpHandler.SendAsync(request, cancellationToken);
}
else
{
return DiagnosticsHandler.IsEnabled() ?
_diagnosticsHandler.SendAsync(request, cancellationToken) :
_managedHandler.SendAsync(request, cancellationToken);
}
}
}
}
| |
// <copyright file="RemoteWebDriver.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Html5;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a way to use the driver through
/// </summary>
/// /// <example>
/// <code>
/// [TestFixture]
/// public class Testing
/// {
/// private IWebDriver driver;
/// <para></para>
/// [SetUp]
/// public void SetUp()
/// {
/// driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),DesiredCapabilities.InternetExplorer());
/// }
/// <para></para>
/// [Test]
/// public void TestGoogle()
/// {
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// /*
/// * Rest of the test
/// */
/// }
/// <para></para>
/// [TearDown]
/// public void TearDown()
/// {
/// driver.Quit();
/// }
/// }
/// </code>
/// </example>
public class RemoteWebDriver : IWebDriver, ISearchContext, IJavaScriptExecutor, IFindsElement, ITakesScreenshot, ISupportsPrint, IActionExecutor, IHasCapabilities, IHasCommandExecutor, IAllowsFileDetection, IHasSessionId, IHasWebStorage, IHasLocationContext, IHasApplicationCache, IFindsById, IFindsByClassName, IFindsByLinkText, IFindsByName, IFindsByTagName, IFindsByXPath, IFindsByPartialLinkText, IFindsByCssSelector
{
/// <summary>
/// The default command timeout for HTTP requests in a RemoteWebDriver instance.
/// </summary>
protected static readonly TimeSpan DefaultCommandTimeout = TimeSpan.FromSeconds(60);
private const string DefaultRemoteServerUrl = "http://127.0.0.1:4444/wd/hub";
private ICommandExecutor executor;
private ICapabilities capabilities;
private SessionId sessionId;
private IWebStorage storage;
private IApplicationCache appCache;
private ILocationContext locationContext;
private IFileDetector fileDetector = new DefaultFileDetector();
private RemoteWebElementFactory elementFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(DriverOptions options)
: this(ConvertOptionsToCapabilities(options))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(ICapabilities desiredCapabilities)
: this(new Uri(DefaultRemoteServerUrl), desiredCapabilities)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(Uri remoteAddress, DriverOptions options)
: this(remoteAddress, ConvertOptionsToCapabilities(options))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities)
: this(remoteAddress, desiredCapabilities, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class using the specified remote address, desired capabilities, and command timeout.
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout)
: this(new HttpCommandExecutor(remoteAddress, commandTimeout), desiredCapabilities)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class
/// </summary>
/// <param name="commandExecutor">An <see cref="ICommandExecutor"/> object which executes commands for the driver.</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
{
this.executor = commandExecutor;
this.StartClient();
this.StartSession(desiredCapabilities);
this.elementFactory = new RemoteWebElementFactory(this);
if (this.capabilities.HasCapability(CapabilityType.SupportsApplicationCache))
{
object appCacheCapability = this.capabilities.GetCapability(CapabilityType.SupportsApplicationCache);
if (appCacheCapability is bool && (bool)appCacheCapability)
{
this.appCache = new RemoteApplicationCache(this);
}
}
if (this.capabilities.HasCapability(CapabilityType.SupportsLocationContext))
{
object locationContextCapability = this.capabilities.GetCapability(CapabilityType.SupportsLocationContext);
if (locationContextCapability is bool && (bool)locationContextCapability)
{
this.locationContext = new RemoteLocationContext(this);
}
}
if (this.capabilities.HasCapability(CapabilityType.SupportsWebStorage))
{
object webContextCapability = this.capabilities.GetCapability(CapabilityType.SupportsWebStorage);
if (webContextCapability is bool && (bool)webContextCapability)
{
this.storage = new RemoteWebStorage(this);
}
}
if ((this as ISupportsLogs) != null)
{
// Only add the legacy log commands if the driver supports
// retrieving the logs via the extension end points.
this.CommandExecutor.CommandInfoRepository.TryAddCommand(DriverCommand.GetAvailableLogTypes, new CommandInfo(CommandInfo.GetCommand, "/session/{sessionId}/se/log/types"));
this.CommandExecutor.CommandInfoRepository.TryAddCommand(DriverCommand.GetLog, new CommandInfo(CommandInfo.PostCommand, "/session/{sessionId}/se/log"));
}
}
/// <summary>
/// Gets or sets the URL the browser is currently displaying.
/// </summary>
/// <seealso cref="IWebDriver.Url"/>
/// <seealso cref="INavigation.GoToUrl(string)"/>
/// <seealso cref="INavigation.GoToUrl(System.Uri)"/>
public string Url
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetCurrentUrl, null);
return commandResponse.Value.ToString();
}
set
{
if (value == null)
{
throw new ArgumentNullException("value", "Argument 'url' cannot be null.");
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("url", value);
this.Execute(DriverCommand.Get, parameters);
}
}
/// <summary>
/// Gets the title of the current browser window.
/// </summary>
public string Title
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetTitle, null);
object returnedTitle = commandResponse != null ? commandResponse.Value : string.Empty;
return returnedTitle.ToString();
}
}
/// <summary>
/// Gets the source of the page last loaded by the browser.
/// </summary>
public string PageSource
{
get
{
string pageSource = string.Empty;
Response commandResponse = this.Execute(DriverCommand.GetPageSource, null);
pageSource = commandResponse.Value.ToString();
return pageSource;
}
}
/// <summary>
/// Gets the current window handle, which is an opaque handle to this
/// window that uniquely identifies it within this driver instance.
/// </summary>
public string CurrentWindowHandle
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetCurrentWindowHandle, null);
return commandResponse.Value.ToString();
}
}
/// <summary>
/// Gets the window handles of open browser windows.
/// </summary>
public ReadOnlyCollection<string> WindowHandles
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetWindowHandles, null);
object[] handles = (object[])commandResponse.Value;
List<string> handleList = new List<string>();
foreach (object handle in handles)
{
handleList.Add(handle.ToString());
}
return handleList.AsReadOnly();
}
}
/// <summary>
/// Gets a value indicating whether web storage is supported for this driver.
/// </summary>
public bool HasWebStorage
{
get { return this.storage != null; }
}
/// <summary>
/// Gets an <see cref="IWebStorage"/> object for managing web storage.
/// </summary>
public IWebStorage WebStorage
{
get
{
if (this.storage == null)
{
throw new InvalidOperationException("Driver does not support manipulating HTML5 web storage. Use the HasWebStorage property to test for the driver capability");
}
return this.storage;
}
}
/// <summary>
/// Gets a value indicating whether manipulating the application cache is supported for this driver.
/// </summary>
public bool HasApplicationCache
{
get { return this.appCache != null; }
}
/// <summary>
/// Gets an <see cref="IApplicationCache"/> object for managing application cache.
/// </summary>
public IApplicationCache ApplicationCache
{
get
{
if (this.appCache == null)
{
throw new InvalidOperationException("Driver does not support manipulating the HTML5 application cache. Use the HasApplicationCache property to test for the driver capability");
}
return this.appCache;
}
}
/// <summary>
/// Gets a value indicating whether manipulating geolocation is supported for this driver.
/// </summary>
public bool HasLocationContext
{
get { return this.locationContext != null; }
}
/// <summary>
/// Gets an <see cref="ILocationContext"/> object for managing browser location.
/// </summary>
public ILocationContext LocationContext
{
get
{
if (this.locationContext == null)
{
throw new InvalidOperationException("Driver does not support setting HTML5 geolocation information. Use the HasLocationContext property to test for the driver capability");
}
return this.locationContext;
}
}
/// <summary>
/// Gets the capabilities that the RemoteWebDriver instance is currently using
/// </summary>
public ICapabilities Capabilities
{
get { return this.capabilities; }
}
/// <summary>
/// Gets or sets the <see cref="IFileDetector"/> responsible for detecting
/// sequences of keystrokes representing file paths and names.
/// </summary>
public virtual IFileDetector FileDetector
{
get
{
return this.fileDetector;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value", "FileDetector cannot be null");
}
this.fileDetector = value;
}
}
/// <summary>
/// Gets the <see cref="SessionId"/> for the current session of this driver.
/// </summary>
public SessionId SessionId
{
get { return this.sessionId; }
}
/// <summary>
/// Gets a value indicating whether this object is a valid action executor.
/// </summary>
public bool IsActionExecutor
{
get { return true; }
}
/// <summary>
/// Gets the <see cref="ICommandExecutor"/> which executes commands for this driver.
/// </summary>
public ICommandExecutor CommandExecutor
{
get { return this.executor; }
}
/// <summary>
/// Gets or sets the factory object used to create instances of <see cref="RemoteWebElement"/>
/// or its subclasses.
/// </summary>
protected RemoteWebElementFactory ElementFactory
{
get { return this.elementFactory; }
set { this.elementFactory = value; }
}
/// <summary>
/// Finds the first element in the page that matches the <see cref="By"/> object
/// </summary>
/// <param name="by">By mechanism to find the object</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// IWebElement elem = driver.FindElement(By.Name("q"));
/// </code>
/// </example>
public IWebElement FindElement(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElement(this);
}
/// <summary>
/// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page
/// </summary>
/// <param name="by">By mechanism to find the element</param>
/// <returns>ReadOnlyCollection of IWebElement</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> classList = driver.FindElements(By.ClassName("class"));
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
if (by == null)
{
throw new ArgumentNullException("by", "by cannot be null");
}
return by.FindElements(this);
}
/// <summary>
/// Closes the Browser
/// </summary>
public void Close()
{
this.Execute(DriverCommand.Close, null);
}
/// <summary>
/// Close the Browser and Dispose of WebDriver
/// </summary>
public void Quit()
{
this.Dispose();
}
/// <summary>
/// Method For getting an object to set the Speed
/// </summary>
/// <returns>Returns an IOptions object that allows the driver to set the speed and cookies and getting cookies</returns>
/// <seealso cref="IOptions"/>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// driver.Manage().GetCookies();
/// </code>
/// </example>
public IOptions Manage()
{
return new RemoteOptions(this);
}
/// <summary>
/// Method to allow you to Navigate with WebDriver
/// </summary>
/// <returns>Returns an INavigation Object that allows the driver to navigate in the browser</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// </code>
/// </example>
public INavigation Navigate()
{
return new RemoteNavigator(this);
}
/// <summary>
/// Method to give you access to switch frames and windows
/// </summary>
/// <returns>Returns an Object that allows you to Switch Frames and Windows</returns>
/// <example>
/// <code>
/// IWebDriver driver = new InternetExplorerDriver();
/// driver.SwitchTo().Frame("FrameName");
/// </code>
/// </example>
public ITargetLocator SwitchTo()
{
return new RemoteTargetLocator(this);
}
/// <summary>
/// Executes JavaScript in the context of the currently selected frame or window
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
public object ExecuteScript(string script, params object[] args)
{
return this.ExecuteScriptCommand(script, DriverCommand.ExecuteScript, args);
}
/// <summary>
/// Executes JavaScript asynchronously in the context of the currently selected frame or window.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
public object ExecuteAsyncScript(string script, params object[] args)
{
return this.ExecuteScriptCommand(script, DriverCommand.ExecuteAsyncScript, args);
}
/// <summary>
/// Finds an element matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the element.</param>
/// <param name="value">The value to use to search for the element.</param>
/// <returns>The first <see cref="IWebElement"/> matching the given criteria.</returns>
public virtual IWebElement FindElement(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindElement, parameters);
return this.GetElementFromResponse(commandResponse);
}
/// <summary>
/// Finds all elements matching the given mechanism and value.
/// </summary>
/// <param name="mechanism">The mechanism by which to find the elements.</param>
/// <param name="value">The value to use to search for the elements.</param>
/// <returns>A collection of all of the <see cref="IWebElement">IWebElements</see> matching the given criteria.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(string mechanism, string value)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("using", mechanism);
parameters.Add("value", value);
Response commandResponse = this.Execute(DriverCommand.FindElements, parameters);
return this.GetElementsFromResponse(commandResponse);
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the element</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementById("id")
/// </code>
/// </example>
public IWebElement FindElementById(string id)
{
return this.FindElement("css selector", "#" + By.EscapeCssSelector(id));
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the Element</param>
/// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsById("id")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsById(string id)
{
string selector = By.EscapeCssSelector(id);
if (string.IsNullOrEmpty(selector))
{
// Finding multiple elements with an empty ID will return
// an empty list. However, finding by a CSS selector of '#'
// throws an exception, even in the multiple elements case,
// which means we need to short-circuit that behavior.
return new List<IWebElement>().AsReadOnly();
}
return this.FindElements("css selector", "#" + selector);
}
/// <summary>
/// Finds the first element in the page that matches the CSS Class supplied
/// </summary>
/// <param name="className">className of the</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByClassName("classname")
/// </code>
/// </example>
public IWebElement FindElementByClassName(string className)
{
string selector = By.EscapeCssSelector(className);
if (selector.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
return this.FindElement("css selector", "." + selector);
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="className">CSS class Name on the element</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByClassName(string className)
{
string selector = By.EscapeCssSelector(className);
if (selector.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
return this.FindElements("css selector", "." + selector);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByLinkText("linktext")
/// </code>
/// </example>
public IWebElement FindElementByLinkText(string linkText)
{
return this.FindElement("link text", linkText);
}
/// <summary>
/// Finds a list of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText)
{
return this.FindElements("link text", linkText);
}
/// <summary>
/// Finds the first of elements that match the part of the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByPartialLinkText("partOfLink")
/// </code>
/// </example>
public IWebElement FindElementByPartialLinkText(string partialLinkText)
{
return this.FindElement("partial link text", partialLinkText);
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByPartialLinkText("partOfTheLink")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText)
{
return this.FindElements("partial link text", partialLinkText);
}
/// <summary>
/// Finds the first of elements that match the name supplied
/// </summary>
/// <param name="name">Name of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public IWebElement FindElementByName(string name)
{
return this.FindElement("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds a list of elements that match the name supplied
/// </summary>
/// <param name="name">Name of element</param>
/// <returns>ReadOnlyCollect of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByName(string name)
{
return this.FindElements("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds the first of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM tag Name of the element being searched</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public IWebElement FindElementByTagName(string tagName)
{
return this.FindElement("css selector", tagName);
}
/// <summary>
/// Finds a list of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM tag Name of element being searched</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName)
{
return this.FindElements("css selector", tagName);
}
/// <summary>
/// Finds the first of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByXPath("//table/tbody/tr/td/a");
/// </code>
/// </example>
public IWebElement FindElementByXPath(string xpath)
{
return this.FindElement("xpath", xpath);
}
/// <summary>
/// Finds a list of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByXpath("//tr/td/a")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath)
{
return this.FindElements("xpath", xpath);
}
/// <summary>
/// Finds the first element matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns>
public IWebElement FindElementByCssSelector(string cssSelector)
{
return this.FindElement("css selector", cssSelector);
}
/// <summary>
/// Finds all elements matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all
/// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns>
public ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector)
{
return this.FindElements("css selector", cssSelector);
}
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
string base64 = screenshotResponse.Value.ToString();
return new Screenshot(base64);
}
/// <summary>
/// Gets a <see cref="PrintDocument"/> object representing a PDF-formatted print representation of the page.
/// </summary>
/// <param name="printOptions">A <see cref="PrintOptions"/> object describing the options of the printed document.</param>
/// <returns>The <see cref="PrintDocument"/> object containing the PDF-formatted print representation of the page.</returns>
public PrintDocument Print(PrintOptions printOptions)
{
Response commandResponse = this.Execute(DriverCommand.Print, printOptions.ToDictionary());
string base64 = commandResponse.Value.ToString();
return new PrintDocument(base64);
}
/// <summary>
/// Performs the specified list of actions with this action executor.
/// </summary>
/// <param name="actionSequenceList">The list of action sequences to perform.</param>
public void PerformActions(IList<ActionSequence> actionSequenceList)
{
if (actionSequenceList == null)
{
throw new ArgumentNullException("actionSequenceList", "List of action sequences must not be null");
}
List<object> objectList = new List<object>();
foreach (ActionSequence sequence in actionSequenceList)
{
objectList.Add(sequence.ToDictionary());
}
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["actions"] = objectList;
this.Execute(DriverCommand.Actions, parameters);
}
/// <summary>
/// Resets the input state of the action executor.
/// </summary>
public void ResetInputState()
{
this.Execute(DriverCommand.CancelActions, null);
}
/// <summary>
/// Dispose the RemoteWebDriver Instance
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Executes commands with the driver
/// </summary>
/// <param name="driverCommandToExecute">Command that needs executing</param>
/// <param name="parameters">Parameters needed for the command</param>
/// <returns>WebDriver Response</returns>
internal Response InternalExecute(string driverCommandToExecute, Dictionary<string, object> parameters)
{
return this.Execute(driverCommandToExecute, parameters);
}
/// <summary>
/// Find the element in the response
/// </summary>
/// <param name="response">Response from the browser</param>
/// <returns>Element from the page</returns>
internal IWebElement GetElementFromResponse(Response response)
{
if (response == null)
{
throw new NoSuchElementException();
}
RemoteWebElement element = null;
Dictionary<string, object> elementDictionary = response.Value as Dictionary<string, object>;
if (elementDictionary != null)
{
element = this.elementFactory.CreateElement(elementDictionary);
}
return element;
}
/// <summary>
/// Finds the elements that are in the response
/// </summary>
/// <param name="response">Response from the browser</param>
/// <returns>Collection of elements</returns>
internal ReadOnlyCollection<IWebElement> GetElementsFromResponse(Response response)
{
List<IWebElement> toReturn = new List<IWebElement>();
object[] elements = response.Value as object[];
if (elements != null)
{
foreach (object elementObject in elements)
{
Dictionary<string, object> elementDictionary = elementObject as Dictionary<string, object>;
if (elementDictionary != null)
{
RemoteWebElement element = this.elementFactory.CreateElement(elementDictionary);
toReturn.Add(element);
}
}
}
return toReturn.AsReadOnly();
}
/// <summary>
/// Stops the client from running
/// </summary>
/// <param name="disposing">if its in the process of disposing</param>
protected virtual void Dispose(bool disposing)
{
try
{
this.Execute(DriverCommand.Quit, null);
}
catch (NotImplementedException)
{
}
catch (InvalidOperationException)
{
}
catch (WebDriverException)
{
}
finally
{
this.StopClient();
this.sessionId = null;
}
}
/// <summary>
/// Starts a session with the driver
/// </summary>
/// <param name="desiredCapabilities">Capabilities of the browser</param>
protected void StartSession(ICapabilities desiredCapabilities)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
// If the object passed into the RemoteWebDriver constructor is a
// RemoteSessionSettings object, it is expected that all intermediate
// and end nodes are compliant with the W3C WebDriver Specification,
// and therefore will already contain all of the appropriate values
// for establishing a session.
RemoteSessionSettings remoteSettings = desiredCapabilities as RemoteSessionSettings;
if (remoteSettings == null)
{
Dictionary<string, object> matchCapabilities = this.GetCapabilitiesDictionary(desiredCapabilities);
List<object> firstMatchCapabilitiesList = new List<object>();
firstMatchCapabilitiesList.Add(matchCapabilities);
Dictionary<string, object> specCompliantCapabilitiesDictionary = new Dictionary<string, object>();
specCompliantCapabilitiesDictionary["firstMatch"] = firstMatchCapabilitiesList;
parameters.Add("capabilities", specCompliantCapabilitiesDictionary);
}
else
{
parameters.Add("capabilities", remoteSettings.ToDictionary());
}
Response response = this.Execute(DriverCommand.NewSession, parameters);
Dictionary<string, object> rawCapabilities = response.Value as Dictionary<string, object>;
if (rawCapabilities == null)
{
string errorMessage = string.Format(CultureInfo.InvariantCulture, "The new session command returned a value ('{0}') that is not a valid JSON object.", response.Value);
throw new WebDriverException(errorMessage);
}
ReturnedCapabilities returnedCapabilities = new ReturnedCapabilities(rawCapabilities);
this.capabilities = returnedCapabilities;
this.sessionId = new SessionId(response.SessionId);
}
/// <summary>
/// Gets the capabilities as a dictionary.
/// </summary>
/// <param name="capabilitiesToConvert">The dictionary to return.</param>
/// <returns>A Dictionary consisting of the capabilities requested.</returns>
/// <remarks>This method is only transitional. Do not rely on it. It will be removed
/// once browser driver capability formats stabilize.</remarks>
protected virtual Dictionary<string, object> GetCapabilitiesDictionary(ICapabilities capabilitiesToConvert)
{
Dictionary<string, object> capabilitiesDictionary = new Dictionary<string, object>();
IHasCapabilitiesDictionary capabilitiesObject = capabilitiesToConvert as IHasCapabilitiesDictionary;
foreach (KeyValuePair<string, object> entry in capabilitiesObject.CapabilitiesDictionary)
{
if (CapabilityType.IsSpecCompliantCapabilityName(entry.Key))
{
capabilitiesDictionary.Add(entry.Key, entry.Value);
}
}
return capabilitiesDictionary;
}
/// <summary>
/// Executes a command with this driver .
/// </summary>
/// <param name="driverCommandToExecute">A <see cref="DriverCommand"/> value representing the command to execute.</param>
/// <param name="parameters">A <see cref="Dictionary{K, V}"/> containing the names and values of the parameters of the command.</param>
/// <returns>A <see cref="Response"/> containing information about the success or failure of the command and any data returned by the command.</returns>
protected virtual Response Execute(string driverCommandToExecute, Dictionary<string, object> parameters)
{
Command commandToExecute = new Command(this.sessionId, driverCommandToExecute, parameters);
Response commandResponse;
try
{
commandResponse = this.executor.Execute(commandToExecute);
}
catch (System.Net.WebException e)
{
commandResponse = new Response
{
Status = WebDriverResult.UnhandledError,
Value = e
};
}
if (commandResponse.Status != WebDriverResult.Success)
{
UnpackAndThrowOnError(commandResponse);
}
return commandResponse;
}
/// <summary>
/// Starts the command executor, enabling communication with the browser.
/// </summary>
protected virtual void StartClient()
{
}
/// <summary>
/// Stops the command executor, ending further communication with the browser.
/// </summary>
protected virtual void StopClient()
{
}
/// <summary>
/// Executes JavaScript in the context of the currently selected frame or window using a specific command.
/// </summary>
/// <param name="script">The JavaScript code to execute.</param>
/// <param name="commandName">The name of the command to execute.</param>
/// <param name="args">The arguments to the script.</param>
/// <returns>The value returned by the script.</returns>
protected object ExecuteScriptCommand(string script, string commandName, params object[] args)
{
object[] convertedArgs = ConvertArgumentsToJavaScriptObjects(args);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("script", script);
if (convertedArgs != null && convertedArgs.Length > 0)
{
parameters.Add("args", convertedArgs);
}
else
{
parameters.Add("args", new object[] { });
}
Response commandResponse = this.Execute(commandName, parameters);
return this.ParseJavaScriptReturnValue(commandResponse.Value);
}
private static object ConvertObjectToJavaScriptObject(object arg)
{
IWrapsElement argAsWrapsElement = arg as IWrapsElement;
IWebElementReference argAsElementReference = arg as IWebElementReference;
IEnumerable argAsEnumerable = arg as IEnumerable;
IDictionary argAsDictionary = arg as IDictionary;
if (argAsElementReference == null && argAsWrapsElement != null)
{
argAsElementReference = argAsWrapsElement.WrappedElement as IWebElementReference;
}
object converted = null;
if (arg is string || arg is float || arg is double || arg is int || arg is long || arg is bool || arg == null)
{
converted = arg;
}
else if (argAsElementReference != null)
{
// TODO: Remove "ELEMENT" addition when all remote ends are spec-compliant.
Dictionary<string, object> elementDictionary = argAsElementReference.ToDictionary();
elementDictionary.Add(RemoteWebElement.LegacyElementReferencePropertyName, argAsElementReference.ElementReferenceId);
converted = elementDictionary;
}
else if (argAsDictionary != null)
{
// Note that we must check for the argument being a dictionary before
// checking for IEnumerable, since dictionaries also implement IEnumerable.
// Additionally, JavaScript objects have property names as strings, so all
// keys will be converted to strings.
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (var key in argAsDictionary.Keys)
{
dictionary.Add(key.ToString(), ConvertObjectToJavaScriptObject(argAsDictionary[key]));
}
converted = dictionary;
}
else if (argAsEnumerable != null)
{
List<object> objectList = new List<object>();
foreach (object item in argAsEnumerable)
{
objectList.Add(ConvertObjectToJavaScriptObject(item));
}
converted = objectList.ToArray();
}
else
{
throw new ArgumentException("Argument is of an illegal type" + arg.ToString(), "arg");
}
return converted;
}
/// <summary>
/// Converts the arguments to JavaScript objects.
/// </summary>
/// <param name="args">The arguments.</param>
/// <returns>The list of the arguments converted to JavaScript objects.</returns>
private static object[] ConvertArgumentsToJavaScriptObjects(object[] args)
{
if (args == null)
{
return new object[] { null };
}
for (int i = 0; i < args.Length; i++)
{
args[i] = ConvertObjectToJavaScriptObject(args[i]);
}
return args;
}
private static void UnpackAndThrowOnError(Response errorResponse)
{
// Check the status code of the error, and only handle if not success.
if (errorResponse.Status != WebDriverResult.Success)
{
Dictionary<string, object> errorAsDictionary = errorResponse.Value as Dictionary<string, object>;
if (errorAsDictionary != null)
{
ErrorResponse errorResponseObject = new ErrorResponse(errorAsDictionary);
string errorMessage = errorResponseObject.Message;
switch (errorResponse.Status)
{
case WebDriverResult.NoSuchElement:
throw new NoSuchElementException(errorMessage);
case WebDriverResult.NoSuchFrame:
throw new NoSuchFrameException(errorMessage);
case WebDriverResult.UnknownCommand:
throw new NotImplementedException(errorMessage);
case WebDriverResult.ObsoleteElement:
throw new StaleElementReferenceException(errorMessage);
case WebDriverResult.ElementClickIntercepted:
throw new ElementClickInterceptedException(errorMessage);
case WebDriverResult.ElementNotInteractable:
throw new ElementNotInteractableException(errorMessage);
case WebDriverResult.ElementNotDisplayed:
throw new ElementNotVisibleException(errorMessage);
case WebDriverResult.InvalidElementState:
case WebDriverResult.ElementNotSelectable:
throw new InvalidElementStateException(errorMessage);
case WebDriverResult.UnhandledError:
throw new WebDriverException(errorMessage);
case WebDriverResult.NoSuchDocument:
throw new NoSuchElementException(errorMessage);
case WebDriverResult.Timeout:
throw new WebDriverTimeoutException(errorMessage);
case WebDriverResult.NoSuchWindow:
throw new NoSuchWindowException(errorMessage);
case WebDriverResult.InvalidCookieDomain:
throw new InvalidCookieDomainException(errorMessage);
case WebDriverResult.UnableToSetCookie:
throw new UnableToSetCookieException(errorMessage);
case WebDriverResult.AsyncScriptTimeout:
throw new WebDriverTimeoutException(errorMessage);
case WebDriverResult.UnexpectedAlertOpen:
// TODO(JimEvans): Handle the case where the unexpected alert setting
// has been set to "ignore", so there is still a valid alert to be
// handled.
string alertText = string.Empty;
if (errorAsDictionary.ContainsKey("alert"))
{
Dictionary<string, object> alertDescription = errorAsDictionary["alert"] as Dictionary<string, object>;
if (alertDescription != null && alertDescription.ContainsKey("text"))
{
alertText = alertDescription["text"].ToString();
}
}
else if (errorAsDictionary.ContainsKey("data"))
{
Dictionary<string, object> alertData = errorAsDictionary["data"] as Dictionary<string, object>;
if (alertData != null && alertData.ContainsKey("text"))
{
alertText = alertData["text"].ToString();
}
}
throw new UnhandledAlertException(errorMessage, alertText);
case WebDriverResult.NoAlertPresent:
throw new NoAlertPresentException(errorMessage);
case WebDriverResult.InvalidSelector:
throw new InvalidSelectorException(errorMessage);
case WebDriverResult.NoSuchDriver:
throw new WebDriverException(errorMessage);
case WebDriverResult.InvalidArgument:
throw new WebDriverArgumentException(errorMessage);
case WebDriverResult.UnexpectedJavaScriptError:
throw new JavaScriptException(errorMessage);
case WebDriverResult.MoveTargetOutOfBounds:
throw new MoveTargetOutOfBoundsException(errorMessage);
default:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "{0} ({1})", errorMessage, errorResponse.Status));
}
}
else
{
throw new WebDriverException("Unexpected error. " + errorResponse.Value.ToString());
}
}
}
private static ICapabilities ConvertOptionsToCapabilities(DriverOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options", "Driver options must not be null");
}
return options.ToCapabilities();
}
private object ParseJavaScriptReturnValue(object responseValue)
{
object returnValue = null;
Dictionary<string, object> resultAsDictionary = responseValue as Dictionary<string, object>;
object[] resultAsArray = responseValue as object[];
if (resultAsDictionary != null)
{
if (this.elementFactory.ContainsElementReference(resultAsDictionary))
{
returnValue = this.elementFactory.CreateElement(resultAsDictionary);
}
else
{
// Recurse through the dictionary, re-parsing each value.
string[] keyCopy = new string[resultAsDictionary.Keys.Count];
resultAsDictionary.Keys.CopyTo(keyCopy, 0);
foreach (string key in keyCopy)
{
resultAsDictionary[key] = this.ParseJavaScriptReturnValue(resultAsDictionary[key]);
}
returnValue = resultAsDictionary;
}
}
else if (resultAsArray != null)
{
bool allElementsAreWebElements = true;
List<object> toReturn = new List<object>();
foreach (object item in resultAsArray)
{
object parsedItem = this.ParseJavaScriptReturnValue(item);
IWebElement parsedItemAsElement = parsedItem as IWebElement;
if (parsedItemAsElement == null)
{
allElementsAreWebElements = false;
}
toReturn.Add(parsedItem);
}
if (toReturn.Count > 0 && allElementsAreWebElements)
{
List<IWebElement> elementList = new List<IWebElement>();
foreach (object listItem in toReturn)
{
IWebElement itemAsElement = listItem as IWebElement;
elementList.Add(itemAsElement);
}
returnValue = elementList.AsReadOnly();
}
else
{
returnValue = toReturn.AsReadOnly();
}
}
else
{
returnValue = responseValue;
}
return returnValue;
}
}
}
| |
namespace SlimMessageBus.Host.Redis.Test
{
using System;
using System.Collections;
using System.Text;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json;
using SlimMessageBus.Host.Config;
using SlimMessageBus.Host.DependencyResolver;
using SlimMessageBus.Host.Serialization;
using StackExchange.Redis;
using Xunit;
public class RedisMessageBusTest
{
private readonly Lazy<RedisMessageBus> _subject;
private readonly MessageBusSettings _settings = new MessageBusSettings();
private readonly RedisMessageBusSettings _providerSettings;
private readonly Mock<IDependencyResolver> _dependencyResolverMock = new Mock<IDependencyResolver>();
private readonly Mock<IMessageSerializer> _messageSerializerMock = new Mock<IMessageSerializer>();
private readonly Mock<IConnectionMultiplexer> _connectionMultiplexerMock;
private readonly Mock<IDatabase> _databaseMock;
private readonly Mock<ISubscriber> _subscriberMock;
public RedisMessageBusTest()
{
_settings.DependencyResolver = _dependencyResolverMock.Object;
_settings.Serializer = _messageSerializerMock.Object;
_messageSerializerMock
.Setup(x => x.Serialize(It.IsAny<Type>(), It.IsAny<object>()))
.Returns((Type type, object message) => Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)));
_messageSerializerMock
.Setup(x => x.Deserialize(It.IsAny<Type>(), It.IsAny<byte[]>()))
.Returns((Type type, byte[] payload) => JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload), type));
_databaseMock = new Mock<IDatabase>();
_subscriberMock = new Mock<ISubscriber>();
_connectionMultiplexerMock = new Mock<IConnectionMultiplexer>();
_connectionMultiplexerMock.Setup(x => x.GetDatabase(-1, null)).Returns(() => _databaseMock.Object);
_connectionMultiplexerMock.Setup(x => x.GetSubscriber(null)).Returns(() => _subscriberMock.Object);
_providerSettings = new RedisMessageBusSettings("")
{
ConnectionFactory = () => _connectionMultiplexerMock.Object
};
_subject = new Lazy<RedisMessageBus>(() => new RedisMessageBus(_settings, _providerSettings));
}
private static ProducerSettings Producer(Type messageType, string defaultPath, PathKind kind)
{
var pb = new ProducerBuilder<object>(new ProducerSettings(), messageType);
if (kind == PathKind.Topic)
{
pb.DefaultTopic(defaultPath);
}
else
{
pb.DefaultQueue(defaultPath);
}
return pb.Settings;
}
private static ConsumerSettings Consumer(Type messageType, string topic, Type consumerType)
{
return new ConsumerBuilder<object>(new MessageBusSettings(), messageType).Topic(topic).WithConsumer(consumerType).ConsumerSettings;
}
private MessageWithHeaders UnwrapPayload(RedisValue redisValue)
=> (MessageWithHeaders)_providerSettings.EnvelopeSerializer.Deserialize(typeof(MessageWithHeaders), redisValue);
[Fact]
public async Task When_Publish_Given_QueueAndTopic_Then_RoutesToRespectiveChannels()
{
// arrange
const string topicA = "topic-a";
const string queueB = "queue-b";
_settings.Producers.Add(Producer(typeof(SomeMessageA), topicA, PathKind.Topic));
_settings.Producers.Add(Producer(typeof(SomeMessageB), queueB, PathKind.Queue));
var mA = new SomeMessageA { Value = Guid.NewGuid() };
var mB = new SomeMessageB { Value = Guid.NewGuid() };
var payloadA = _messageSerializerMock.Object.Serialize(typeof(SomeMessageA), mA);
var payloadB = _messageSerializerMock.Object.Serialize(typeof(SomeMessageB), mB);
// act
await _subject.Value.Publish(mA);
await _subject.Value.Publish(mB);
// assert
_databaseMock.Verify(x => x.PublishAsync(It.Is<RedisChannel>(channel => channel == topicA), It.Is<RedisValue>(x => StructuralComparisons.StructuralEqualityComparer.Equals(UnwrapPayload(x).Payload, payloadA)), It.IsAny<CommandFlags>()), Times.Once);
_databaseMock.Verify(x => x.PublishAsync(It.Is<RedisChannel>(channel => channel == queueB), It.IsAny<RedisValue>(), It.IsAny<CommandFlags>()), Times.Never);
_databaseMock.Verify(x => x.ListRightPushAsync(It.Is<RedisKey>(key => key == queueB),
It.Is<RedisValue>(x => StructuralComparisons.StructuralEqualityComparer.Equals(UnwrapPayload(x).Payload, payloadB)),
When.Always,
CommandFlags.None),
Times.Once);
_databaseMock.Verify(x => x.ListRightPushAsync(It.Is<RedisKey>(key => key == topicA),
It.IsAny<RedisValue>(),
When.Always,
CommandFlags.None),
Times.Never);
}
}
public class SomeMessageA
{
public Guid Value { get; set; }
#region Equality members
protected bool Equals(SomeMessageA other)
{
return Value.Equals(other.Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((SomeMessageA)obj);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
#endregion
}
public class SomeMessageB
{
public Guid Value { get; set; }
#region Equality members
protected bool Equals(SomeMessageB other)
{
return Value.Equals(other.Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((SomeMessageB)obj);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
#endregion
}
public class SomeMessageAConsumer : IConsumer<SomeMessageA>, IDisposable
{
public virtual void Dispose()
{
// Needed to check disposing
}
#region Implementation of IConsumer<in SomeMessageA>
public virtual Task OnHandle(SomeMessageA messageA, string name)
{
return Task.CompletedTask;
}
#endregion
}
public class SomeMessageAConsumer2 : IConsumer<SomeMessageA>
{
#region Implementation of IConsumer<in SomeMessageA>
public virtual Task OnHandle(SomeMessageA messageA, string name)
{
return Task.CompletedTask;
}
#endregion
}
public class SomeMessageBConsumer : IConsumer<SomeMessageB>
{
#region Implementation of IConsumer<in SomeMessageB>
public virtual Task OnHandle(SomeMessageB message, string name)
{
return Task.CompletedTask;
}
#endregion
}
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira 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.Collections.Generic;
namespace Boo.Lang.Compiler.TypeSystem.Generics
{
public interface IGenericMappedMember : IMember
{
IMember SourceMember { get; }
}
/// <summary>
/// A base class for a member mapped from a generic type onto a constructed type.
/// </summary>
public abstract class GenericMappedMember<T> : IGenericMappedMember where T : IMember
{
protected readonly TypeSystemServices _tss;
readonly T _sourceMember;
readonly GenericMapping _genericMapping;
string _fullName = null;
protected GenericMappedMember(TypeSystemServices tss, T sourceMember, GenericMapping genericMapping)
{
_tss = tss;
_sourceMember = sourceMember;
_genericMapping = genericMapping;
}
public T SourceMember
{
get { return _sourceMember; }
}
IMember IGenericMappedMember.SourceMember
{
get { return SourceMember; }
}
protected virtual string BuildFullName()
{
return DeclaringType.FullName + "." + Name;
}
public GenericMapping GenericMapping
{
get { return _genericMapping; }
}
public bool IsDuckTyped
{
get { return SourceMember.IsDuckTyped; }
}
public IType DeclaringType
{
get { return GenericMapping.MapType(SourceMember.DeclaringType); }
}
public bool IsStatic
{
get { return SourceMember.IsStatic; }
}
public IType Type
{
get { return GenericMapping.MapType(SourceMember.Type); }
}
public EntityType EntityType
{
get { return SourceMember.EntityType; }
}
public string Name
{
get
{
return SourceMember.Name;
}
}
public string FullName
{
get { return _fullName ?? (_fullName = BuildFullName()); }
}
public bool IsPublic
{
get { return SourceMember.IsPublic; }
}
public override string ToString()
{
return FullName;
}
public bool IsDefined(IType attributeType)
{
return _sourceMember.IsDefined(attributeType);
}
}
/// <summary>
/// A base class for an accessible member mapped from a generic type onto a constructed type.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class GenericMappedAccessibleMember<T> : GenericMappedMember<T>, IAccessibleMember where T : IAccessibleMember
{
protected GenericMappedAccessibleMember(TypeSystemServices tss, T source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public bool IsProtected
{
get { return SourceMember.IsProtected; }
}
public bool IsInternal
{
get { return SourceMember.IsInternal; }
}
public bool IsPrivate
{
get { return SourceMember.IsPrivate; }
}
}
/// <summary>
/// A method on a generic constructed type.
/// </summary>
public class GenericMappedMethod : GenericMappedAccessibleMember<IMethod>, IMethod, IGenericMethodInfo
{
IParameter[] _parameters = null;
IGenericParameter[] _typeParameters = null;
ICallableType _callableType = null;
IDictionary<IType[], IMethod> _constructedMethods = new Dictionary<IType[], IMethod>();
public GenericMappedMethod(TypeSystemServices tss, IMethod source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public bool IsAbstract
{
get { return SourceMember.IsAbstract; }
}
public bool IsVirtual
{
get { return SourceMember.IsVirtual; }
}
public bool IsFinal
{
get { return SourceMember.IsFinal; }
}
public bool IsSpecialName
{
get { return SourceMember.IsSpecialName; }
}
public bool IsPInvoke
{
get { return SourceMember.IsPInvoke; }
}
public virtual IConstructedMethodInfo ConstructedInfo
{
// Generic mapped methods are not constructed methods, rather they're methods on constructed types.
get { return null; }
}
public IGenericMethodInfo GenericInfo
{
get
{
if (SourceMember.GenericInfo == null)
{
return null;
}
return this;
}
}
public ICallableType CallableType
{
get
{
if (null == _callableType)
{
_callableType = _tss.GetCallableType(this);
}
return _callableType;
}
}
public bool AcceptVarArgs
{
get { return SourceMember.AcceptVarArgs; }
}
public bool IsExtension
{
get { return SourceMember.IsExtension; }
}
public IType ReturnType
{
get { return GenericMapping.MapType(SourceMember.ReturnType); }
}
public IParameter[] GetParameters()
{
if (_parameters == null)
{
_parameters = GenericMapping.MapParameters(SourceMember.GetParameters());
}
return _parameters;
}
IGenericParameter[] IGenericParametersProvider.GenericParameters
{
get
{
if (_typeParameters == null)
{
_typeParameters = Array.ConvertAll<IGenericParameter, IGenericParameter>(
SourceMember.GenericInfo.GenericParameters,
GenericMapping.MapGenericParameter);
}
return _typeParameters;
}
}
IMethod IGenericMethodInfo.ConstructMethod(params IType[] arguments)
{
IMethod constructedMethod = null;
if (!_constructedMethods.TryGetValue(arguments, out constructedMethod))
{
constructedMethod = new GenericConstructedMethod(this, arguments);
_constructedMethods.Add(arguments, constructedMethod);
}
return constructedMethod;
}
protected override string BuildFullName()
{
// TODO: pull all name-building logic for types and methods together somewhere
// instead of repeating it every time with slight variations (BOO-1097)
System.Text.StringBuilder sb = new System.Text.StringBuilder(base.BuildFullName());
if (GenericInfo != null)
{
sb.Append("[of ");
string[] genericParameterNames = Array.ConvertAll<IGenericParameter, string>(
GenericInfo.GenericParameters,
delegate(IGenericParameter gp) { return gp.Name; });
sb.Append(string.Join(", ", genericParameterNames));
sb.Append("]");
}
sb.Append("(");
string[] parameterTypeNames = Array.ConvertAll<IParameter, string>(
GetParameters(),
delegate(IParameter p) { return p.Type.Name; });
sb.Append(string.Join(", ", parameterTypeNames));
sb.Append(")");
return sb.ToString();
}
}
/// <summary>
/// A constructor on a generic constructed type.
/// </summary>
public class GenericMappedConstructor : GenericMappedMethod, IConstructor
{
public GenericMappedConstructor(TypeSystemServices tss, IConstructor source, GenericMapping genericMapping)
: base(tss, (IMethod)source, genericMapping)
{
}
}
/// <summary>
/// A property on a generic constructed type.
/// </summary>
public class GenericMappedProperty : GenericMappedAccessibleMember<IProperty>, IProperty
{
IParameter[] _parameters;
public GenericMappedProperty(TypeSystemServices tss, IProperty source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public IParameter[] GetParameters()
{
return _parameters ?? (_parameters = GenericMapping.MapParameters(SourceMember.GetParameters()));
}
public IMethod GetGetMethod()
{
return GenericMapping.Map(SourceMember.GetGetMethod());
}
public IMethod GetSetMethod()
{
return GenericMapping.Map(SourceMember.GetSetMethod());
}
public override string ToString()
{
return string.Format("{0} as {1}", Name, Type);
}
public bool AcceptVarArgs
{
get { return SourceMember.AcceptVarArgs; }
}
public bool IsExtension
{
get { return SourceMember.IsExtension; }
}
}
/// <summary>
/// An event in a constructed generic type.
/// </summary>
public class GenericMappedEvent : GenericMappedMember<IEvent>, IEvent
{
public GenericMappedEvent(TypeSystemServices tss, IEvent source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public IMethod GetAddMethod()
{
return GenericMapping.Map(SourceMember.GetAddMethod());
}
public IMethod GetRemoveMethod()
{
return GenericMapping.Map(SourceMember.GetRemoveMethod());
}
public IMethod GetRaiseMethod()
{
return GenericMapping.Map(SourceMember.GetRemoveMethod());
}
public bool IsAbstract
{
get { return SourceMember.IsAbstract; }
}
public bool IsVirtual
{
get { return SourceMember.IsVirtual; }
}
}
/// <summary>
/// A field on a generic constructed type.
/// </summary>
public class GenericMappedField : GenericMappedAccessibleMember<IField>, IField
{
public GenericMappedField(TypeSystemServices tss, IField source, GenericMapping genericMapping)
: base(tss, source, genericMapping)
{
}
public bool IsInitOnly
{
get { return SourceMember.IsInitOnly; }
}
public bool IsLiteral
{
get { return SourceMember.IsLiteral; }
}
public object StaticValue
{
get { return SourceMember.StaticValue; }
}
public bool IsVolatile
{
get { return SourceMember.IsVolatile; }
}
}
}
| |
/*
* NodeList.cs - Implementation of the "System.Xml.Private.NodeList" class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Xml.Private
{
using System;
using System.Collections;
using System.Runtime.CompilerServices;
internal sealed class NodeList : XmlNodeList
{
// Internal state.
internal XmlNode first;
internal XmlNode last;
internal XmlNode nextSibling;
internal XmlNode prevSibling;
internal int count;
internal int generation;
// Create a new node list.
public NodeList()
{
first = null;
last = null;
nextSibling = null;
prevSibling = null;
count = 0;
generation = 0;
}
// Get the number of entries in the node list.
public override int Count
{
get
{
return count;
}
}
// Get a particular item within this node list.
public override XmlNode Item(int i)
{
if(i >= 0 && i < count)
{
XmlNode child = first;
while(i > 0)
{
child = child.list.nextSibling;
--i;
}
return child;
}
else
{
return null;
}
}
// Implement the "IEnumerable" interface.
public override IEnumerator GetEnumerator()
{
return new NodeListEnumerator(this);
}
// Get the node list for a node, creating it if necessary.
public static NodeList GetList(XmlNode node)
{
if(node.list == null)
{
node.list = new NodeList();
}
return node.list;
}
// Quick access to the first child of a node.
public static XmlNode GetFirstChild(XmlNode node)
{
if(node.list != null)
{
return node.list.first;
}
else
{
return null;
}
}
// Quick access to the last child.
public static XmlNode GetLastChild(XmlNode node)
{
if(node.list != null)
{
return node.list.last;
}
else
{
return null;
}
}
// Quick access to the next sibling.
public static XmlNode GetNextSibling(XmlNode node)
{
if(node.list != null)
{
return node.list.nextSibling;
}
else
{
return null;
}
}
// Quick access to the previous sibling.
public static XmlNode GetPreviousSibling(XmlNode node)
{
if(node.list != null)
{
return node.list.prevSibling;
}
else
{
return null;
}
}
// Insert a child into a node list just after a given node.
public void InsertAfter(XmlNode newNode, XmlNode refNode)
{
if(refNode != null)
{
NodeList refList = GetList(refNode);
NodeList newList = GetList(newNode);
if(refList.nextSibling != null)
{
newList.nextSibling = refList.nextSibling;
newList.prevSibling = refNode;
refList.nextSibling = newNode;
}
else
{
refList.nextSibling = newNode;
newList.prevSibling = refNode;
last = newNode;
}
}
else if(first != null)
{
GetList(first).prevSibling = newNode;
GetList(newNode).nextSibling = first;
}
else
{
first = newNode;
last = newNode;
}
++count;
++generation;
}
// Remove a child from underneath its current parent.
public void RemoveChild(XmlNode node)
{
NodeList nodeList = GetList(node);
bool changed = false;
if(nodeList.nextSibling != null)
{
GetList(nodeList.nextSibling).prevSibling =
nodeList.prevSibling;
changed = true;
}
else if(last == node)
{
last = nodeList.prevSibling;
changed = true;
}
if(nodeList.prevSibling != null)
{
GetList(nodeList.prevSibling).nextSibling =
nodeList.nextSibling;
changed = true;
}
else if(first == node)
{
first = nodeList.nextSibling;
changed = true;
}
nodeList.nextSibling = null;
nodeList.prevSibling = null;
if(changed)
{
--count;
++generation;
}
}
// Implementation of the node list enumerator.
private sealed class NodeListEnumerator : IEnumerator
{
// Internal state.
private NodeList list;
private XmlNode current;
private int generation;
private bool done;
// Constructor.
public NodeListEnumerator(NodeList list)
{
this.list = list;
this.current = null;
this.generation = list.generation;
this.done = false;
}
// Implement the "IEnumerator" interface.
public bool MoveNext()
{
if(generation != list.generation)
{
throw new InvalidOperationException
(S._("Invalid_CollectionModified"));
}
if(current == null)
{
if(done)
{
return false;
}
current = list.first;
if(current == null)
{
done = true;
return false;
}
else
{
return true;
}
}
if(current.list != null)
{
current = current.list.nextSibling;
}
else
{
current = null;
}
if(current != null)
{
return true;
}
else
{
done = true;
return false;
}
}
public void Reset()
{
if(generation != list.generation)
{
throw new InvalidOperationException
(S._("Invalid_CollectionModified"));
}
current = null;
done = false;
}
public Object Current
{
get
{
if(generation != list.generation)
{
throw new InvalidOperationException
(S._("Invalid_CollectionModified"));
}
if(current != null)
{
return current;
}
else
{
throw new InvalidOperationException
(S._("Invalid_BadEnumeratorPosition"));
}
}
}
}; // class NodeListEnumerator
}; // class NodeList
}; // namespace System.Xml.Private
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2014 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using log4net;
namespace MindTouch.Dream {
/// <summary>
/// Enumerates the possible Http response codes.
/// </summary>
/// <remarks>
/// Codes below 100 are specific to <see cref="Plug"/> and not part of Http.
/// </remarks>
public enum DreamStatus {
/// <summary>
/// Unable to connect (0).
/// </summary>
UnableToConnect = 0,
/// <summary>
/// No <see cref="IPlugEndpoint"/> could be found for Uri. (1).
/// </summary>
NoEndpointFound = 1,
/// <summary>
/// Request is null (10).
/// </summary>
RequestIsNull = 10,
/// <summary>
/// Request Failed (11).
/// </summary>
RequestFailed = 11,
/// <summary>
/// Request failed because the connection timed out (12).
/// </summary>
RequestConnectionTimeout = 12,
/// <summary>
/// Response is null (20).
/// </summary>
ResponseIsNull = 20,
/// <summary>
/// Response Failed (21).
/// </summary>
ResponseFailed = 21,
/// <summary>
/// Response failed because the data transfer timed out (22).
/// </summary>
ResponseDataTransferTimeout = 22,
/// <summary>
/// Continue (100)
/// </summary>
Continue = 100,
///<summary>
/// Switching Protocols (101)
/// </summary>
SwitchingProtocols = 101,
/// <summary>
/// Ok (200).
/// </summary>
Ok = 200,
/// <summary>
/// Created (201).
/// </summary>
Created = 201,
/// <summary>
/// Accepted (202).
/// </summary>
Accepted = 202,
/// <summary>
/// Non-authoritative Information (203).
/// </summary>
NonAuthoritativeInformation = 203,
/// <summary>
/// No content (204).
/// </summary>
NoContent = 204,
/// <summary>
/// Reset content (205).
/// </summary>
ResetContent = 205,
/// <summary>
/// Partial content (206).
/// </summary>
PartialContent = 206,
/// <summary>
/// Multi status (207).
/// </summary>
MultiStatus = 207,
/// <summary>
/// Multiple choices (300).
/// </summary>
MultipleChoices = 300,
/// <summary>
/// Moved permanently (301).
/// </summary>
MovedPermanently = 301,
/// <summary>
/// Found (302).
/// </summary>
Found = 302,
/// <summary>
/// See other (303).
/// </summary>
SeeOther = 303,
/// <summary>
/// Not modified (304).
/// </summary>
NotModified = 304,
/// <summary>
/// Use proxy (305).
/// </summary>
UseProxy = 305,
/// <summary>
/// Temporary redirct (307).
/// </summary>
TemporaryRedirect = 307,
/// <summary>
/// Bad Request (400).
/// </summary>
BadRequest = 400,
/// <summary>
/// Unauthorized (401).
/// </summary>
Unauthorized = 401,
/// <summary>
/// License required (402).
/// </summary>
LicenseRequired = 402,
/// <summary>
/// Forbidden (403).
/// </summary>
Forbidden = 403,
/// <summary>
/// Not found (404).
/// </summary>
NotFound = 404,
/// <summary>
/// Method is not allowed (405).
/// </summary>
MethodNotAllowed = 405,
/// <summary>
/// Not acceptable (406).
/// </summary>
NotAcceptable = 406,
/// <summary>
/// Proxy authentication required (407).
/// </summary>
ProxyAuthenticationRequired = 407,
/// <summary>
/// Request timeout (408).
/// </summary>
RequestTimeout = 408,
/// <summary>
/// Conflict (409).
/// </summary>
Conflict = 409,
/// <summary>
/// Gone (410).
/// </summary>
Gone = 410,
/// <summary>
/// Length required (411).
/// </summary>
LengthRequired = 411,
/// <summary>
/// Precondition Failed (412).
/// </summary>
PreconditionFailed = 412,
/// <summary>
/// Request entity too large (413).
/// </summary>
RequestEntityTooLarge = 413,
/// <summary>
/// Request Uri is too long (414).
/// </summary>
RequestURIToLong = 414,
/// <summary>
/// Unsupported media type (415).
/// </summary>
UnsupportedMediaType = 415,
/// <summary>
/// Request range not satisfiable (416).
/// </summary>
RequestedRangeNotSatisfiable = 416,
/// <summary>
/// Expecation failed (417).
/// </summary>
ExpectationFailed = 417,
/// <summary>
/// Unprocessable entity (422).
/// </summary>
UnprocessableEntity = 422,
/// <summary>
/// Locked (423).
/// </summary>
Locked = 423,
/// <summary>
/// Failed dependency (424).
/// </summary>
FailedDependency = 424,
/// <summary>
/// Internal error (500).
/// </summary>
InternalError = 500,
/// <summary>
/// Not implemented (501).
/// </summary>
NotImplemented = 501,
/// <summary>
/// Bad Gateway (502).
/// </summary>
BadGateway = 502,
/// <summary>
/// Service unavailable (503).
/// </summary>
ServiceUnavailable = 503,
/// <summary>
/// Gateway timeout (504).
/// </summary>
GatewayTimeout = 504,
/// <summary>
/// Http version not supported (505).
/// </summary>
HTTPVersionNotSupported = 505,
/// <summary>
/// Insuffient storage (507).
/// </summary>
InsufficientStorage = 507
}
/// <summary>
/// Encapsulates a content mime type.
/// </summary>
public class MimeType {
//--- Constants ---
private const string PARAM_CHARSET = "charset";
private const string PARAM_QUALITY = "q";
//--- Class Fields ---
/* NOTE (2015-04-13, coreyc):
* These fields must be initialized before the public static readonly fields are created.
* For more information see: http://stackoverflow.com/a/2925660/45071
*/
private static readonly Dictionary<string, string> _emptyParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static readonly ILog _log = LogUtils.CreateLog();
// (bug 7232) changed ISO-8859-1 to US-ASCII as per RFC-2045/2046.
/// <summary>
/// Creates a <see cref="MimeType"/> instance that can match any mime type.
/// </summary>
/// <remarks>Signature: <b>*/*</b></remarks>
public static readonly MimeType ANY = new MimeType("*/*");
/// <summary>
/// Creates a <see cref="MimeType"/> instance that can match any text mime type.
/// </summary>
/// <remarks>Signature: <b>text/*</b></remarks>
public static readonly MimeType ANY_TEXT = new MimeType("text/*");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Atom content.
/// </summary>
/// <remarks>Signature: <b>application/atom+xml; UTF8</b></remarks>
public static readonly MimeType ATOM = new MimeType("application/atom+xml", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for binary content.
/// </summary>
/// <remarks>Signature: <b>application/octet-stream</b></remarks>
public static readonly MimeType BINARY = new MimeType("application/octet-stream");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for BMP Images.
/// </summary>
/// <remarks>Signature: <b>image/bmp</b></remarks>
public static readonly MimeType BMP = new MimeType("image/bmp");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for CSS.
/// </summary>
/// <remarks>Signature: <b>text/css; ASCII</b></remarks>
public static readonly MimeType CSS = new MimeType("text/css", Encoding.ASCII);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for dream exception xml.
/// </summary>
/// <remarks>Signature: <b>application/x-dream-exception+xml; UTF-8</b></remarks>
public static readonly MimeType DREAM_EXCEPTION = new MimeType("application/x-dream-exception+xml", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for wwww form urlencoded content.
/// </summary>
/// <remarks>Signature: <b>application/x-www-form-urlencoded; UTF-8</b></remarks>
public static readonly MimeType FORM_URLENCODED = new MimeType("application/x-www-form-urlencoded", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for GIF images.
/// </summary>
/// <remarks>Signature: <b>image/gif</b></remarks>
public static readonly MimeType GIF = new MimeType("image/gif");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Html content.
/// </summary>
/// <remarks>Signature: <b>text/html; UTF-8</b></remarks>
public static readonly MimeType HTML = new MimeType("text/html", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Http Applications.
/// </summary>
/// <remarks>Signature: <b>application/http; UTF-8</b></remarks>
public static readonly MimeType HTTP = new MimeType("application/http", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for JPEG images.
/// </summary>
/// <remarks>Signature: <b>image/jpeg</b></remarks>
public static readonly MimeType JPEG = new MimeType("image/jpeg");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for javascript source code.
/// </summary>
/// <remarks>Signature: <b>text/javascript; ASCII</b></remarks>
public static readonly MimeType JS = new MimeType("text/javascript", Encoding.ASCII);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for javascript object notation content.
/// </summary>
/// <remarks>Signature: <b>application/json; UTF-8</b></remarks>
public static readonly MimeType JSON = new MimeType("application/json", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for multipart/mixed content.
/// </summary>
/// <remarks>Signature: <b>multipart/mixed</b></remarks>
public static readonly MimeType MULTIPART_MIXED = new MimeType("multipart/mixed");
/// <summary>
/// Creates a <see cref="MimeType"/> instance indidcating no content.
/// </summary>
/// <remarks>Signature: <b>-/-</b></remarks>
public static readonly MimeType NOTHING = new MimeType("-/-");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Adobe PDF.
/// </summary>
/// <remarks>Signature: <b>application/pdf</b></remarks>
public static readonly MimeType PDF = new MimeType("application/pdf");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for PHP source code.
/// </summary>
/// <remarks>Signature: <b>application/php; UTF-8</b></remarks>
public static readonly MimeType PHP = new MimeType("application/php", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for PNG images.
/// </summary>
/// <remarks>Signature: <b>image/png</b></remarks>
public static readonly MimeType PNG = new MimeType("image/png");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for RDF content.
/// </summary>
/// <remarks>Signature: <b>application/rdf+xml; UTF-8</b></remarks>
public static readonly MimeType RDF = new MimeType("application/rdf+xml", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Relax-NG schema content.
/// </summary>
/// <remarks>Signature: <b>application/relax-ng-compact-syntax; UTF-8</b></remarks>
public static readonly MimeType RELAXNG = new MimeType("application/relax-ng-compact-syntax", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for SVG images.
/// </summary>
/// <remarks>Signature: <b>image/svg+xml; UTF-8</b></remarks>
public static readonly MimeType SVG = new MimeType("image/svg+xml", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for plain text content.
/// </summary>
/// <remarks>Signature: <b>text/plain; ASCII</b></remarks>
public static readonly MimeType TEXT = new MimeType("text/plain", Encoding.ASCII);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for UTF-8 encoded text content.
/// </summary>
/// <remarks>Signature: <b>text/plain; UTF-8</b></remarks>
public static readonly MimeType TEXT_UTF8 = new MimeType("text/plain", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for ASCII-encoded Xml content.
/// </summary>
/// <remarks>Signature: <b>text/xml; ASCII</b></remarks>
public static readonly MimeType TEXT_XML = new MimeType("text/xml", Encoding.ASCII);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for TIFF images.
/// </summary>
/// <remarks>Signature: <b>image/tiff</b></remarks>
public static readonly MimeType TIFF = new MimeType("image/tiff");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for VCal calendar files.
/// </summary>
/// <remarks>Signature: <b>text/calendar; ASCII</b></remarks>
public static readonly MimeType VCAL = new MimeType("text/calendar", Encoding.ASCII);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for VCard files.
/// </summary>
/// <remarks>Signature: <b>application/x-versit; UTF-8</b></remarks>
public static readonly MimeType VERSIT = new MimeType("application/x-versit", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for XHtml content.
/// </summary>
/// <remarks>Signature: <b>application/xhtml+xml; UTF-8</b></remarks>
public static readonly MimeType XHTML = new MimeType("application/xhtml+xml", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Xml content.
/// </summary>
/// <remarks>Signature: <b>application/xml; UTF-8</b></remarks>
public static readonly MimeType XML = new MimeType("application/xml", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Xrds content.
/// </summary>
/// <remarks>Signature: <b>application/xrds+xml; UTF-8</b></remarks>
public static readonly MimeType XRDS = new MimeType("application/xrds+xml", Encoding.UTF8);
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Microsoft Office 2003 Word content.
/// </summary>
/// <remarks>Signature: <b>application/msword</b></remarks>
public static readonly MimeType MSOFFICE_DOC = new MimeType("application/msword");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Microsoft Office 2007/2010 Word content.
/// </summary>
/// <remarks>Signature: <b>application/vnd.openxmlformats-officedocument.wordprocessingml.document</b></remarks>
public static readonly MimeType MSOFFICE_DOCX = new MimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Microsoft Office 2003 Excel content.
/// </summary>
/// <remarks>Signature: <b>application/vnd.ms-excel</b></remarks>
public static readonly MimeType MSOFFICE_XLS = new MimeType("application/vnd.ms-excel");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Microsoft Office 2007/2010 Excel content.
/// </summary>
/// <remarks>Signature: <b>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</b></remarks>
public static readonly MimeType MSOFFICE_XLSX = new MimeType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Microsoft Office 2003 Powerpoint content.
/// </summary>
/// <remarks>Signature: <b>application/vnd.ms-powerpoint</b></remarks>
public static readonly MimeType MSOFFICE_PPT = new MimeType("application/vnd.ms-powerpoint");
/// <summary>
/// Creates a <see cref="MimeType"/> instance for Microsoft Office 2007/2010 Powerpoint content.
/// </summary>
/// <remarks>Signature: <b>application/vnd.openxmlformats-officedocument.presentationml.presentation</b></remarks>
public static readonly MimeType MSOFFICE_PPTX = new MimeType("application/vnd.openxmlformats-officedocument.presentationml.presentation");
/// <summary>
/// Default mimetype returned by <see cref="FromFileExtension"/>.
/// </summary>
public static readonly MimeType DefaultMimeType = BINARY;
//--- Class Methods ---
/// <summary>
/// Create a new Mimetype instance with a manually specified content-type.
/// </summary>
/// <param name="contentTypeWithParameters">Content type string.</param>
/// <returns>New mime type instance.</returns>
public static MimeType New(string contentTypeWithParameters) {
MimeType result;
TryParse(contentTypeWithParameters, out result);
return result;
}
/// <summary>
/// Get the best matching Mimetype given a list of mime-type options and accepted mime-types.
/// </summary>
/// <param name="have">Array of possible mime-types.</param>
/// <param name="accept">Array of mime-types accepted.</param>
/// <returns>Best match mime-type instance.</returns>
public static MimeType MatchBestContentType(MimeType[] have, MimeType[] accept) {
// match each available content-type against accepted content-types
MimeType result = null;
float best = 0.0f;
foreach(MimeType haveType in have) {
foreach(MimeType acceptType in accept) {
// check if current combination yields a better result
float current = acceptType.Quality;
if((current > best) && haveType.Match(acceptType)) {
best = current;
result = haveType;
}
}
}
return result;
}
/// <summary>
/// Parse an array of accepted mime-types from an <see cref="DreamHeaders.Accept"/> header.
/// </summary>
/// <param name="accept"><see cref="DreamHeaders.Accept"/> header value.</param>
/// <returns>Array of accepted mime-types.</returns>
public static MimeType[] ParseAcceptHeader(string accept) {
List<MimeType> result = new List<MimeType>();
if(!string.IsNullOrEmpty(accept)) {
foreach(string entry in accept.Split(',')) {
MimeType type;
if(TryParse(entry, out type)) {
result.Add(type);
}
}
}
return result.ToArray();
}
/// <summary>
/// Render an <see cref="DreamHeaders.Accept"/> header value from an array of mime-types.
/// </summary>
/// <param name="types">Array of mime-types.</param>
/// <returns><see cref="DreamHeaders.Accept"/> header value string.</returns>
public static string RenderAcceptHeader(params MimeType[] types) {
StringBuilder result = new StringBuilder();
foreach(MimeType type in types) {
if(result.Length > 0) {
result.Append(", ");
}
result.Append(type);
}
return result.ToString();
}
/// <summary>
/// Derive a mime-type from a file extension.
/// </summary>
/// <remarks>The default mimetype returned is <see cref="BINARY"/>.</remarks>
/// <param name="filename">Filename to get extension from.</param>
/// <returns>Best match mime-type.</returns>
public static MimeType FromFileExtension(string filename) {
MimeType result = BINARY;
switch(Path.GetExtension(filename).ToLowerInvariant()) {
// document formats
case ".html":
case ".htm":
result = HTML;
break;
case ".txt":
result = TEXT;
break;
case ".xml":
case ".xhtml":
case ".xsl":
case ".xsd":
case ".xslt":
result = XML;
break;
case ".css":
result = CSS;
break;
case ".js":
result = JS;
break;
case ".pdf":
result = PDF;
break;
// image formats
case ".gif":
result = GIF;
break;
case ".jpg":
case ".jpeg":
result = JPEG;
break;
case ".png":
result = PNG;
break;
case ".svg":
result = SVG;
break;
case ".tif":
case ".tiff":
result = TIFF;
break;
case ".bmp":
result = BMP;
break;
// Microsoft office formats
case ".doc":
result = MSOFFICE_DOC;
break;
case ".docx":
result = MSOFFICE_DOCX;
break;
case ".xls":
result = MSOFFICE_XLS;
break;
case ".xlsx":
result = MSOFFICE_XLSX;
break;
case ".ppt":
result = MSOFFICE_PPT;
break;
case ".pptx":
result = MSOFFICE_PPTX;
break;
}
return result;
}
/// <summary>
/// Try to parse a mime-type from a content-type string.
/// </summary>
/// <param name="contentTypeWithParameters">Content type string.</param>
/// <param name="result">Mime-type instance return value.</param>
/// <returns><see langword="True"/> if a mime-type could be parsed.</returns>
public static bool TryParse(string contentTypeWithParameters, out MimeType result) {
string type;
string subtype;
Dictionary<string, string> parameters;
if(!TryParse(contentTypeWithParameters, out type, out subtype, out parameters)) {
result = null;
return false;
}
result = new MimeType(type, subtype, parameters);
return true;
}
/// <summary>
/// Try to parse a mime-type components from a content-type string.
/// </summary>
/// <param name="contentTypeWithParameters">Content type string.</param>
/// <param name="type">Main type return value.</param>
/// <param name="subtype">Sub-type return value.</param>
/// <param name="parameters">Dictionary of mime-type parameters.</param>
/// <returns></returns>
protected static bool TryParse(string contentTypeWithParameters, out string type, out string subtype, out Dictionary<string, string> parameters) {
type = null;
subtype = null;
parameters = null;
if(string.IsNullOrEmpty(contentTypeWithParameters)) {
return false;
}
// parse types
string[] parts = contentTypeWithParameters.Split(';');
string[] typeParts = parts[0].Split(new[] { '/' }, 2);
if(typeParts.Length != 2) {
return false;
}
type = typeParts[0].Trim().ToLowerInvariant();
subtype = typeParts[1].Trim().ToLowerInvariant();
// parse parameters
for(int i = 1; i < parts.Length; ++i) {
string[] assign = parts[i].Split(new[] { '=' }, 2);
if(assign.Length == 2) {
if(parameters == null) {
parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
parameters[assign[0].Trim()] = assign[1].Trim();
}
}
return true;
}
//--- Fields ---
private readonly string _mainType;
private readonly string _subType;
private readonly Dictionary<string, string> _parameters;
private readonly Encoding _encoding;
private string _text;
//--- Constructors ---
/// <summary>
/// Create a new mime-type from an exact-match content-type string.
/// </summary>
/// <param name="contentTypeWithParameters">Content type string.</param>
public MimeType(string contentTypeWithParameters) {
if(!TryParse(contentTypeWithParameters, out _mainType, out _subType, out _parameters)) {
throw new ArgumentNullException("contentTypeWithParameters");
}
_encoding = GetEncoding();
}
/// <summary>
/// Create a new mime-type from an exact-match content-type string.
/// </summary>
/// <param name="contentTypeWithParameters">Content type string.</param>
/// <param name="charset">Encoding to set for mime-type.</param>
/// <param name="quality">Match quality.</param>
public MimeType(string contentTypeWithParameters, Encoding charset, float quality) {
if(!TryParse(contentTypeWithParameters, out _mainType, out _subType, out _parameters)) {
throw new ArgumentNullException("contentTypeWithParameters");
}
if(_parameters == null) {
_parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
_parameters[PARAM_CHARSET] = charset.WebName;
_parameters[PARAM_QUALITY] = quality.ToInvariantString();
_encoding = GetEncoding();
}
/// <summary>
/// Create a new mime-type from an exact-match content-type string.
/// </summary>
/// <param name="contentTypeWithParameters">Content type string.</param>
/// <param name="quality">Match quality.</param>
public MimeType(string contentTypeWithParameters, float quality) {
if(!TryParse(contentTypeWithParameters, out _mainType, out _subType, out _parameters)) {
throw new ArgumentNullException("contentTypeWithParameters");
}
if(_parameters == null) {
_parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
_parameters[PARAM_QUALITY] = quality.ToInvariantString();
_encoding = GetEncoding();
}
/// <summary>
/// Create a new mime-type from an exact-match content-type string.
/// </summary>
/// <param name="contentTypeWithParameters">Content type string.</param>
/// <param name="charset">Encoding to set for mime-type.</param>
public MimeType(string contentTypeWithParameters, Encoding charset) {
if(!TryParse(contentTypeWithParameters, out _mainType, out _subType, out _parameters)) {
throw new ArgumentNullException("contentTypeWithParameters");
}
if(_parameters == null) {
_parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
_parameters[PARAM_CHARSET] = charset.WebName;
_encoding = GetEncoding();
}
private MimeType(string type, string subtype, Dictionary<string, string> parameters) {
_mainType = type;
_subType = subtype;
_parameters = parameters;
_encoding = GetEncoding();
}
//--- Properties ---
/// <summary>
/// Main type.
/// </summary>
public string MainType { get { return _mainType; } }
/// <summary>
/// Sub type.
/// </summary>
public string SubType { get { return _subType; } }
/// <summary>
/// Full type (without parameters).
/// </summary>
public string FullType { get { return _mainType + "/" + _subType; } }
/// <summary>
/// Type parameters.
/// </summary>
public Dictionary<string, string> Parameters { get { return _parameters ?? _emptyParameters; } }
/// <summary>
/// Match quality value.
/// </summary>
public float Quality { get { return float.Parse(GetParameter(PARAM_QUALITY) ?? "1"); } }
/// <summary>
/// Type Encoding.
/// </summary>
public Encoding CharSet { get { return _encoding; } }
/// <summary>
/// <see langword="True"/> if content represented by the mime-type is Xml.
/// </summary>
public bool IsXml {
get {
return SubType.EqualsInvariant("xml") || SubType.EndsWithInvariant("+xml");
}
}
//--- Methods ---
/// <summary>
/// Try to match instance against another instance.
/// </summary>
/// <param name="other">Other mime-type.</param>
/// <returns><see langword="True"/> if the two types match.</returns>
public bool Match(MimeType other) {
// match main type
if((MainType != "*") && (other.MainType != "*") && (MainType != other.MainType)) {
return false;
}
// match subtype
if((SubType != "*") && (other.SubType != "*") && (SubType != other.SubType)) {
return false;
}
return true;
}
/// <summary>
/// Get a named parameter.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <returns>Parameter value or null.</returns>
public string GetParameter(string name) {
string result;
Parameters.TryGetValue(name, out result);
return result;
}
/// <summary>
/// Render mime-type as a string representation including parameters.
/// </summary>
/// <returns></returns>
public override string ToString() {
if(_text == null) {
StringBuilder result = new StringBuilder();
result.Append(FullType);
foreach(KeyValuePair<string, string> param in Parameters) {
result.AppendFormat("; {0}={1}", param.Key, param.Value);
}
_text = result.ToString();
}
return _text;
}
private Encoding GetEncoding() {
Encoding encoding;
var charset = GetParameter(PARAM_CHARSET);
if(charset != null) {
try {
encoding = Encoding.GetEncoding(charset.Trim('"'));
} catch(ArgumentException ex) {
_log.Debug(string.Format("Unsupported Character Set: '{0}'. Defaulting to UTF8 encoding.", charset), ex);
encoding = Encoding.UTF8;
}
} else if(MainType.EqualsInvariant("text")) {
encoding = Encoding.ASCII;
} else {
encoding = Encoding.UTF8;
}
return encoding;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
using System.Xml;
using System.Reflection;
using System.IO;
namespace Microsoft.Research.CodeAnalysis
{
public class WarningScoresManager
{
#region Thresholds for the levels
// low: [LOWSCORE ... 1.0]
// mediumlow: [MEDIUMLOWSCORE ... 1]
// medium: [MEDIUMSCORE ... 1]
// full: all
public double LOWSCORE { get { return this.ConfidenceThresholdLowWarnings; } }
public double MEDIUMLOWSCORE { get { return this.ConfidenceThreshouldMediumLowWarning; } }
public double MEDIUMSCORE { get { return this.ConfidenceThresholdMediumWarning; } }
private double ConfidenceThresholdLowWarnings;
private double ConfidenceThreshouldMediumLowWarning;
private double ConfidenceThresholdMediumWarning;
#endregion
#region Scores for the outcomes
private double ScoreBottom;
private double ScoreFalse;
private double ScoreTrue;
private double ScoreTop;
#endregion
#region Score for the warning types
private double ScoreArithmeticDivisionByZero;
private double ScoreArithmeticDivisionOverflow;
private double ScoreArithmeticOverflow;
private double ScoreArithmeticMinValueNegation;
private double ScoreArithmeticFloatEqualityPrecisionMismatch;
private double ScoreArrayCreation;
private double ScoreArrayLowerBound;
private double ScoreArrayUpperBound;
private double ScoreArrayPurity;
private double ScoreContractAssert;
private double ScoreContractEnsures;
private double ScoreContractInvariant;
private double ScoreContractRequires;
private double ScoreEnumRange;
private double ScoreMissingPrecondition;
private double ScoreMissingPreconditionInvolvingReadonly;
private double ScoreSuggestion;
private double ScoreNonnullCall;
private double ScoreNonnullArray;
private double ScoreNonnullField;
private double ScoreNonnullUnbox;
private double ScoreUnsafeCreation;
private double ScoreUnsafeLowerBound;
private double ScoreUnsafeUpperBound;
private double ScoreUnreachedCodeAfterPrecondition;
private double ScoreTestAlwaysEvaluatingToAConstant;
private double ScoreFalseEnsures;
private double ScoreFalseRequires;
private double ScoreOffByOne;
private double ScoreCodeRepairLikelyFixingABug;
private double ScoreCodeRepairLikelyFoundAWeakenessInClousot;
private double ScoreCodeRepairThinksWrongInitialization;
private double ScoreClousotCacheNotAvailable;
#endregion
#region Scores for the various contexts
private double ScoreViaMethodCall;
private double ScoreViaArray;
private double ScoreViaPureMethodReturn;
private double ScoreViaOldValue;
private double ScoreViaCast;
private double ScoreViaOutParameter;
private double ScoreViaField;
private double ScoreViaCallThisHavoc;
private double ScoreViaParameterUnmodified;
private double ScoreViaMethodCallThatMayReturnNull;
private double ScoreContainsReadOnlyField;
private double ScoreMayContainForAllOrDisjunction;
private double ScoreContainsIsInst;
private double ScoreInferredPrecondition;
private double ScoreInferredObjectInvariant;
private double ScoreInferredCalleeAssume;
private double ScoreInferredEntryAssume;
private double ScoreAssertMayBeTurnedIntoAssume;
private double ScoreInferredConditionIsSufficient;
private double ScoreInferredConditionContainsDisjunction;
private double ScoreInferredCalleeAssumeContainsDisjunction;
private double ScoreInsideUnsafeMethod;
private double ScoreInterproceduralPathToError;
private double ScoreStringComparedAgainstNullInSwitchStatement;
private double ScoreIsInheritedEnsures;
private double ScoreObjectInvariantNeededForEnsures;
private double ScoreIsVarNotEqNullCheck;
private double ScoreIsPureMethodCallNotEqNullCheck;
private double ScoreWPReachedMaxPathSize;
private double ScoreWPReachedMethodEntry;
private double ScoreWPReachedLoop;
private double ScoreWPSkippedBecauseAdaptiveAnalysis;
#endregion
#region Scores for relational information
private double ScoreRelationalIsAssertAndVarNullCheck;
private double ScoreRelationalIsMissingPreconditionAndPureMethodNullCheck;
#endregion
#region Scores specific for the Calle assume info
private const string ScoreCalleeAssumeExtraInfo = "ScoreCalleeAssumeExtraInfo"; // Important!!! This should be the prefix of the fields before, because we use reflection to get to them
#pragma warning disable 0414 // We use reflection to read those fields
private double ScoreCalleeAssumeExtraInfoNothing;
private double ScoreCalleeAssumeExtraInfoIsAbstract;
private double ScoreCalleeAssumeExtraInfoIsAutoProperty;
private double ScoreCalleeAssumeExtraInfoIsCompilerGenerated;
private double ScoreCalleeAssumeExtraInfoIsConstructor;
private double ScoreCalleeAssumeExtraInfoIsDispose;
private double ScoreCalleeAssumeExtraInfoIsExtern;
private double ScoreCalleeAssumeExtraInfoIsFinalizer;
private double ScoreCalleeAssumeExtraInfoIsGeneric;
private double ScoreCalleeAssumeExtraInfoIsImplicitImplementation;
private double ScoreCalleeAssumeExtraInfoIsInternal;
private double ScoreCalleeAssumeExtraInfoIsNewSlot;
private double ScoreCalleeAssumeExtraInfoIsOverride;
private double ScoreCalleeAssumeExtraInfoIsPrivate;
private double ScoreCalleeAssumeExtraInfoIsPropertyGetterOrSetter;
private double ScoreCalleeAssumeExtraInfoIsProtected;
private double ScoreCalleeAssumeExtraInfoIsPublic;
private double ScoreCalleeAssumeExtraInfoIsSealed;
private double ScoreCalleeAssumeExtraInfoIsStatic;
private double ScoreCalleeAssumeExtraInfoIsVirtual;
private double ScoreCalleeAssumeExtraInfoIsVoidMethod;
private double ScoreCalleeAssumeExtraInfoReturnPrimitiveValue;
private double ScoreCalleeAssumeExtraInfoReturnReferenceType;
private double ScoreCalleeAssumeExtraInfoReturnStructValue;
private double ScoreCalleeAssumeExtraInfoDeclaredInTheSameType;
private double ScoreCalleeAssumeExtraInfoDeclaredInADifferentAssembly;
private double ScoreCalleeAssumeExtraInfoDeclaredInAFrameworkAssembly;
#pragma warning restore 0414
#endregion
#region PC based Scores
private double ScoreNoSourceContext;
#endregion
#region Constructors
/// <summary>
/// construct the warning scores with the default values
/// </summary>
public WarningScoresManager(bool lowScoreForExternalAPI)
{
InitializeDefaultValuesForWarningThresholds();
InitializeDefaultValuesForOutcomes();
InitializeDefaultValuesForWarningTypes();
InitializeDefaultValuesForContexts(lowScoreForExternalAPI);
InitializeDefaultValuesForSourceContext();
}
/// <summary>
/// If filename is null, we use the default scores
/// </summary>
/// <param name="filename"></param>
public WarningScoresManager(bool lowScoreForExternalAPI, string filename)
: this(lowScoreForExternalAPI)
{
if (filename != null)
{
InitializeValuesFromAFile(filename);
}
}
#endregion
#region Initialize the fields to the default values
private void InitializeDefaultValuesForWarningThresholds()
{
ConfidenceThresholdLowWarnings = 0.99;
ConfidenceThreshouldMediumLowWarning = 0.98;
ConfidenceThresholdMediumWarning = 0.5;
// full is implicitely 0
}
private void InitializeDefaultValuesForOutcomes()
{
ScoreBottom = 10.0;
ScoreFalse = 1000.0;
ScoreTop = 1.0;
ScoreTrue = 0.0;
}
private void InitializeDefaultValuesForWarningTypes()
{
ScoreArithmeticDivisionByZero = 60;
ScoreArithmeticDivisionOverflow = 50; // This is likely to appear each time we have x/y
ScoreArithmeticOverflow = 50;
ScoreArithmeticMinValueNegation = 50; // This is likely to appear each time we have "-x", so we give a low score
ScoreArithmeticFloatEqualityPrecisionMismatch = 200; // When we get one of those (e.g. local == o.f) we are very likely to have a possible bug
ScoreArrayCreation = 54; // Usually those are quite precise, so if we get a warning is likely to be a bug
ScoreArrayLowerBound = ScoreArrayCreation; // As above
ScoreArrayUpperBound = ScoreArrayCreation - 2; // Upper bounds can be wrong because of imprecisions in the analysis
ScoreArrayPurity = 60;
ScoreContractAssert = 120; // A violated assertion may be because it's some knowledge is missing
ScoreContractEnsures = 200; // A violated postcondition is bad
ScoreContractInvariant = 150; // A violated invariant is not good
ScoreContractRequires = 200; // A violated precondition is very bad...
ScoreOffByOne = 1000; // An off-by-one is likely to be a bug
ScoreCodeRepairLikelyFixingABug = 1000; // We think we have a fix exposing a bug, let's push the corresponding proof obligation up
ScoreCodeRepairLikelyFoundAWeakenessInClousot = 1; // Let us keep them the warning as it is. If it is a weakeness in Clousot, we want to fix it in the future
ScoreEnumRange = 200; // Enum out of range is something we want to be very careful about, let's tread it as a precondition
ScoreMissingPrecondition = 1000; // Missing a precondition, in particular in public methods, is very bad
ScoreMissingPreconditionInvolvingReadonly = ScoreMissingPrecondition / 2;
ScoreNonnullCall = 100; // Calling without being sure it's not null is bad
ScoreNonnullArray = ScoreNonnullCall + 1; // Likely to be a bug
ScoreNonnullField = ScoreNonnullCall - 10; // Likely to miss an object invariant
ScoreNonnullUnbox = ScoreNonnullCall - 1;
ScoreUnsafeCreation = ScoreArrayCreation + 10;
ScoreUnsafeLowerBound = ScoreArrayLowerBound + 10;
ScoreUnsafeUpperBound = ScoreArrayUpperBound + 10;
ScoreUnreachedCodeAfterPrecondition = ScoreTestAlwaysEvaluatingToAConstant = 1000;
ScoreFalseEnsures = 900;
ScoreFalseRequires = ScoreSuggestion = ScoreMissingPrecondition;
ScoreCodeRepairThinksWrongInitialization = 1000;
ScoreClousotCacheNotAvailable = 10000; // We abort clousot
}
private void InitializeDefaultValuesForContexts(bool lowScoreForExternalAPI)
{
// Atomic Scores
ScoreViaMethodCall = .08; // missing postcondition?
ScoreViaPureMethodReturn = .09; // missing postcondition?
ScoreViaOldValue = .02; // Old may be hard to prove
ScoreViaField = .01; // low...
ScoreViaArray = .01; // low...
ScoreViaCast = .1; // Have we lost some information?
ScoreViaParameterUnmodified = .1;
ScoreViaOutParameter = 0.1; // Missing some postcondition?
ScoreViaCallThisHavoc = 0.1; // We havoced a field
ScoreViaMethodCallThatMayReturnNull = 10.0; // Let's make it very high
ScoreInferredPrecondition = .001;
ScoreInferredObjectInvariant = .001;
ScoreInferredEntryAssume = .001;
ScoreAssertMayBeTurnedIntoAssume = 1.5; // Let's bump it a little bit
ScoreInferredConditionIsSufficient = 1.0; // By default, has no effect.
ScoreInferredConditionContainsDisjunction = 1.1; // Let's bump it a little bit, as it may be a complex warning
ScoreInferredCalleeAssumeContainsDisjunction = .01; // Let's make it very small
ScoreInferredCalleeAssume = .8; // Let's lower it just a little bit, as the extra info will give extra score
InitializeDefaultValuesForContextsOfCalleeAssumeCanDischarge(lowScoreForExternalAPI);
ScoreContainsReadOnlyField = .0001; // If it contains a readonly field, then we can put it very low
ScoreMayContainForAllOrDisjunction = .0001; // If it contains a ForAll expression, then we put it very low
ScoreContainsIsInst = .0005;
ScoreIsInheritedEnsures = 1.1;
ScoreObjectInvariantNeededForEnsures = 1.2;
ScoreStringComparedAgainstNullInSwitchStatement = ScoreInsideUnsafeMethod = 0.005;
ScoreWPReachedMaxPathSize = 0.9; // it may be our bad because the exploration does not go so deep
ScoreWPReachedMethodEntry = 1.1; // bump a little bit, we inferred a sufficient condition?
ScoreWPReachedLoop = 1.0; // do nothing by default
ScoreWPSkippedBecauseAdaptiveAnalysis = 0.9;
ScoreInterproceduralPathToError = 2.0;
ScoreIsVarNotEqNullCheck = 1.5; // little bump
ScoreIsPureMethodCallNotEqNullCheck = 1.0; // lower the score
// Relational scores
ScoreRelationalIsAssertAndVarNullCheck = 1000.0;
ScoreRelationalIsMissingPreconditionAndPureMethodNullCheck = 0.25;
}
private void InitializeDefaultValuesForContextsOfCalleeAssumeCanDischarge(bool lowScoreForExternalAPI)
{
ScoreCalleeAssumeExtraInfoIsAbstract = .8;
ScoreCalleeAssumeExtraInfoIsVirtual = .8;
ScoreCalleeAssumeExtraInfoIsCompilerGenerated = 000001;
ScoreCalleeAssumeExtraInfoIsExtern = .000001;
ScoreCalleeAssumeExtraInfoDeclaredInTheSameType = 1.5; // We want to fix it, as it's in our code!
ScoreCalleeAssumeExtraInfoDeclaredInAFrameworkAssembly = .05;
ScoreCalleeAssumeExtraInfoDeclaredInADifferentAssembly = lowScoreForExternalAPI ?
ScoreCalleeAssumeExtraInfoDeclaredInAFrameworkAssembly
: 100.0;
#region By default, we make those neutral
ScoreCalleeAssumeExtraInfoNothing = 1.0;
ScoreCalleeAssumeExtraInfoIsAutoProperty = 1.0;
ScoreCalleeAssumeExtraInfoIsConstructor = 1.0;
ScoreCalleeAssumeExtraInfoIsDispose = 1.0;
ScoreCalleeAssumeExtraInfoIsFinalizer = 1.0;
ScoreCalleeAssumeExtraInfoIsGeneric = 1.0;
ScoreCalleeAssumeExtraInfoIsImplicitImplementation = 1.0;
ScoreCalleeAssumeExtraInfoIsNewSlot = 1.0;
ScoreCalleeAssumeExtraInfoIsPrivate = 1.0;
ScoreCalleeAssumeExtraInfoIsPropertyGetterOrSetter = 1.0;
ScoreCalleeAssumeExtraInfoIsProtected = 1.0;
ScoreCalleeAssumeExtraInfoIsPublic = 1.0;
ScoreCalleeAssumeExtraInfoIsSealed = 1.0;
ScoreCalleeAssumeExtraInfoIsVoidMethod = 1.0;
ScoreCalleeAssumeExtraInfoReturnPrimitiveValue = 1.0;
ScoreCalleeAssumeExtraInfoReturnReferenceType = 1.0;
ScoreCalleeAssumeExtraInfoReturnStructValue = 1.0;
ScoreCalleeAssumeExtraInfoIsOverride = 1.0;
ScoreCalleeAssumeExtraInfoIsInternal = 1.0;
ScoreCalleeAssumeExtraInfoIsStatic = 1.0;
#endregion
}
private void InitializeDefaultValuesForSourceContext()
{
ScoreNoSourceContext = .2;
}
private void InitializeValuesFromAFile(string filename)
{
Contract.Requires(filename != null);
try
{
filename = filename.TrimStart('@');
var str = new StringReader(File.ReadAllText(filename));
var reader = new XmlTextReader(str);
var state = -1;
var name = String.Empty;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
state = 0;
name = reader.Name;
}
break;
case XmlNodeType.Text:
{
if (state == 0)
{
InitializeField(name, reader.Value);
}
state = -1;
}
break;
case XmlNodeType.EndElement:
{
state = -1;
name = String.Empty;
}
break;
default:
break;
}
}
}
catch (Exception e)
{
Console.Error.WriteLine("Cannot open the configuration file {0}", filename);
Console.Error.WriteLine(" Reason: {0}", e.ToString());
}
}
private void InitializeField(string fieldName, string fieldValue)
{
double value;
if (Double.TryParse(fieldValue, out value))
{
// Get the field
var field = typeof(WarningScoresManager).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
// Let's be sure it's a double
if (field.GetValue(this) is double)
{
field.SetValue(this, value);
#if DEBUG
Console.WriteLine("The field {0} is set to value {1}", field, value);
#endif
return;
}
Console.Error.WriteLine("Cannot set the field {0} to the value {1}", fieldName, value);
}
else
{
Console.Error.WriteLine("Cannot parse the value {0} = {1}", fieldName, fieldValue);
}
}
#endregion
#region Score Logic
/// <summary>
/// We normalize the score to return a value in the interval [0, 1]
/// </summary>
/// <param name="witness"></param>
/// <returns></returns>
[Pure]
[ContractVerification(true)]
public Tuple<double, List<string>> GetScore(Witness witness)
{
Contract.Requires(witness != null);
Contract.Ensures(0.0 <= Contract.Result<Tuple<double, List<string>>>().Item1);
Contract.Ensures(Contract.Result<Tuple<double, List<string>>>().Item1 <= 2.0);
Contract.Ensures(Contract.Result<Tuple<double, List<string>>>().Item2 != null);
List<string> why;
var ScoreForOutcome = this.GetScoreForOutcome(witness.Outcome);
var ScoreForWarning = this.GetScoreForWarningType(witness.Warning);
var ScoreForContext = this.GetScoreForWarningContexts(witness.Context, out why);
var ScoreForPC = this.GetScoreForPC(witness.PC);
var ScoreForRelationalInformation = this.GetScoreForRelationalInformation(witness);
var result = ScoreForOutcome * ScoreForWarning * ScoreForContext * ScoreForPC * ScoreForRelationalInformation;
Contract.Assume(!double.IsNaN(result));
var score = NormalizeScore(result);
return new Tuple<double, List<string>>(score, why);
}
[Pure]
[ContractVerification(true)]
private double NormalizeScore(double r)
{
Contract.Requires(!Double.IsNaN(r));
Contract.Ensures(0.0 <= Contract.Result<double>());
Contract.Ensures(Contract.Result<double>() <= 1.0);
if (1.0 < r)
{
return (2 - 1 / r) / 2;
}
// We abstract all the scores under 1 to epsilon
if (0.0 <= r /*&& r <= 1.0*/)
{
return r / 2;
}
Contract.Assume(false, "Should be unreachable");
return 0;
}
[Pure]
[ContractVerification(true)]
private double GetScoreForOutcome(ProofOutcome proofOutcome)
{
switch (proofOutcome)
{
#region All the cases
case ProofOutcome.Bottom:
return this.ScoreBottom;
case ProofOutcome.False:
return this.ScoreFalse;
case ProofOutcome.Top:
return this.ScoreTop;
case ProofOutcome.True:
return this.ScoreTrue;
default:
// should be unreachable
#if DEBUG
Contract.Assert(false);
#endif
return 0.0;
#endregion
}
}
[Pure]
[ContractVerification(true)]
private double GetScoreForWarningType(WarningType warningType)
{
switch (warningType)
{
#region All the cases ...
case WarningType.ArithmeticDivisionByZero:
return ScoreArithmeticDivisionByZero;
case WarningType.ArithmeticDivisionOverflow:
return ScoreArithmeticDivisionOverflow;
case WarningType.ArithmeticMinValueNegation:
return ScoreArithmeticMinValueNegation;
case WarningType.ArithmeticFloatEqualityPrecisionMismatch:
return ScoreArithmeticFloatEqualityPrecisionMismatch;
case WarningType.ArithmeticOverflow:
case WarningType.ArithmeticUnderflow:
return ScoreArithmeticOverflow;
case WarningType.ArrayCreation:
return ScoreArrayCreation;
case WarningType.ArrayLowerBound:
return ScoreArrayLowerBound;
case WarningType.ArrayUpperBound:
return ScoreArrayUpperBound;
case WarningType.ArrayPurity:
return ScoreArrayPurity;
case WarningType.ClousotCacheNotAvailable:
return ScoreClousotCacheNotAvailable;
case WarningType.ContractAssert:
return ScoreContractAssert;
case WarningType.ContractEnsures:
return ScoreContractEnsures;
case WarningType.ContractInvariant:
return ScoreContractInvariant;
case WarningType.ContractRequires:
return ScoreContractRequires;
case WarningType.EnumRange:
return ScoreEnumRange;
case WarningType.MissingPrecondition:
return ScoreMissingPrecondition;
case WarningType.MissingPreconditionInvolvingReadonly:
return ScoreMissingPreconditionInvolvingReadonly;
case WarningType.Suggestion:
return ScoreSuggestion;
case WarningType.NonnullArray:
return ScoreNonnullArray;
case WarningType.NonnullCall:
return ScoreNonnullCall;
case WarningType.NonnullField:
return ScoreNonnullField;
case WarningType.NonnullUnbox:
return ScoreNonnullUnbox;
case WarningType.UnsafeCreation:
return ScoreUnsafeCreation;
case WarningType.UnsafeLowerBound:
return ScoreUnsafeLowerBound;
case WarningType.UnsafeUpperBound:
return ScoreUnsafeUpperBound;
case WarningType.UnreachedCodeAfterPrecondition:
return ScoreUnreachedCodeAfterPrecondition;
case WarningType.FalseEnsures:
return ScoreFalseEnsures;
case WarningType.FalseRequires:
return ScoreFalseRequires;
case WarningType.TestAlwaysEvaluatingToAConstant:
return ScoreTestAlwaysEvaluatingToAConstant;
default:
// should be unreachable
#if DEBUG
Contract.Assume(false);
#endif
return 1.0;
#endregion
}
}
[Pure]
[ContractVerification(true)]
private double GetScoreForWarningContexts(Set<WarningContext> contexts, out List<string> why)
{
Contract.Ensures(Contract.ValueAtReturn(out why) != null);
var score = 1.0;
why = new List<string>();
if (contexts == null || contexts.Count == 0)
{
why.Add("no context");
return score;
}
foreach (var context in contexts)
{
why.Add(string.Format("{0}", context.ToString()));
#region All the cases
switch (context.Type)
{
case WarningContext.ContextType.NonNullAccessPath:
{
score *= context.AssociatedInfo > 1 ? (1.0 / (context.AssociatedInfo - 1)) : 1.0;
}
break;
case WarningContext.ContextType.ViaParameterUnmodified:
{
var exp = Math.Max(1, context.AssociatedInfo);
score *= ScoreViaParameterUnmodified / Math.Pow(2.0, exp);
}
break;
case WarningContext.ContextType.InferredPrecondition:
{
// we do not take div here, because we assume that one precondition is enough
// Also at the point we get this info, it may be the case we have not run the full simplification (because of performance) so there may be fewer "real" preconditions
score *= ScoreInferredPrecondition;
}
break;
case WarningContext.ContextType.InferredObjectInvariant:
{
var div = (double)Math.Max(1, context.AssociatedInfo);
score *= ScoreInferredObjectInvariant / div;
}
break;
case WarningContext.ContextType.InferredCalleeAssume:
{
score *= ComputeScoreForInferredCalleeAssume((WarningContext.CalleeInfo)context.AssociatedInfo);
}
break;
case WarningContext.ContextType.AssertMayBeTurnedIntoAssume:
{
score *= ScoreAssertMayBeTurnedIntoAssume;
}
break;
case WarningContext.ContextType.InferredEntryAssume:
{
var div = (double)Math.Max(1, context.AssociatedInfo);
score *= ScoreInferredEntryAssume / div;
}
break;
case WarningContext.ContextType.ViaArray:
{
score *= ScoreViaArray * (1.0 / (context.AssociatedInfo != 0 ? context.AssociatedInfo : 1.0));
}
break;
case WarningContext.ContextType.ViaField:
{
score *= ScoreViaField * (1.0 / (context.AssociatedInfo != 0 ? context.AssociatedInfo : 1.0));
}
break;
case WarningContext.ContextType.ViaMethodCall:
{
score *= ScoreViaMethodCall * (1.0 / (context.AssociatedInfo != 0 ? context.AssociatedInfo : 1.0));
}
break;
case WarningContext.ContextType.ViaMethodCallThatMayReturnNull:
{
// Ignore associated info
score *= ScoreViaMethodCallThatMayReturnNull;
}
break;
case WarningContext.ContextType.ContainsReadOnly:
{
score *= ScoreContainsReadOnlyField;
}
break;
case WarningContext.ContextType.MayContainForAllOrADisjunction:
{
score *= ScoreMayContainForAllOrDisjunction;
}
break;
case WarningContext.ContextType.IsVarNotEqNullCheck:
{
score *= ScoreIsVarNotEqNullCheck;
}
break;
case WarningContext.ContextType.IsPureMethodCallNotEqNullCheck:
{
score *= ScoreIsPureMethodCallNotEqNullCheck;
}
break;
case WarningContext.ContextType.ContainsIsInst:
{
score *= ScoreContainsIsInst;
}
break;
case WarningContext.ContextType.OffByOne:
{
score *= ScoreOffByOne;
}
break;
case WarningContext.ContextType.CodeRepairLikelyFixingABug:
{
score *= ScoreCodeRepairLikelyFixingABug;
}
break;
case WarningContext.ContextType.CodeRepairLikelyFoundAWeakenessInClousot:
{
score *= ScoreCodeRepairLikelyFoundAWeakenessInClousot;
}
break;
case WarningContext.ContextType.CodeRepairThinksWrongInitialization:
{
score *= ScoreCodeRepairThinksWrongInitialization;
}
break;
case WarningContext.ContextType.ViaPureMethodReturn:
{
score *= ScoreViaPureMethodReturn * Math.Pow(2.0, 1-context.AssociatedInfo);
}
break;
case WarningContext.ContextType.ViaCast:
{
score *= ScoreViaCast;
}
break;
case WarningContext.ContextType.ViaOutParameter:
{
score *= ScoreViaOutParameter;
}
break;
case WarningContext.ContextType.ViaCallThisHavoc:
{
score *= ScoreViaCallThisHavoc;
}
break;
case WarningContext.ContextType.ViaOldValue:
case WarningContext.ContextType.ConditionContainsValueAtReturn:
{
score *= ScoreViaOldValue;
}
break;
case WarningContext.ContextType.InferredConditionIsSufficient:
{
score *= ScoreInferredConditionIsSufficient;
}
break;
case WarningContext.ContextType.InferredConditionContainsDisjunction:
{
score *= ScoreInferredConditionContainsDisjunction;
}
break;
case WarningContext.ContextType.InferredCalleeAssumeContainsDisjunction:
{
score *= ScoreInferredCalleeAssumeContainsDisjunction;
}
break;
case WarningContext.ContextType.InheritedEnsures:
{
score *= ScoreIsInheritedEnsures;
}
break;
case WarningContext.ContextType.InsideUnsafeMethod:
{
score *= ScoreInsideUnsafeMethod;
}
break;
case WarningContext.ContextType.InterproceduralPathToError:
{
score *= (ScoreInterproceduralPathToError + (1.0 * context.AssociatedInfo));
}
break;
case WarningContext.ContextType.ObjectInvariantNeededForEnsures:
{
score *= ScoreObjectInvariantNeededForEnsures;
}
break;
case WarningContext.ContextType.StringComparedAgainstNullInSwitchStatement:
{
score *= ScoreStringComparedAgainstNullInSwitchStatement;
}
break;
case WarningContext.ContextType.WPReachedMaxPathSize:
{
score *= ScoreWPReachedMaxPathSize;
}
break;
case WarningContext.ContextType.WPReachedMethodEntry:
{
score *= ScoreWPReachedMethodEntry;
}
break;
case WarningContext.ContextType.WPReachedLoop:
{
score *= ScoreWPReachedLoop;
}
break;
case WarningContext.ContextType.WPSkippedBecauseAdaptiveAnalysis:
{
score *= ScoreWPSkippedBecauseAdaptiveAnalysis;
}
break;
default:
Contract.Assert(false, "Should be unreached, we forgot one case? " + context.Type);
// do nothing
break;
#endregion
}
}
return score;
}
[Pure]
private double GetScoreForRelationalInformation(Witness witness)
{
// assert (x != null)
if(witness.WarningKind == WarningKind.Assert && ContainsWarningContext(witness, WarningContext.ContextType.IsVarNotEqNullCheck))
{
return ScoreRelationalIsAssertAndVarNullCheck;
}
// Requires(a.Property != null)
if(witness.WarningKind == WarningKind.MissingPrecondition && ContainsWarningContext(witness, WarningContext.ContextType.IsPureMethodCallNotEqNullCheck))
{
return ScoreRelationalIsMissingPreconditionAndPureMethodNullCheck;
}
return 1.0;
}
[Pure]
static private bool ContainsWarningContext(Witness witness, WarningContext.ContextType what)
{
return witness.Context.Any(wc => wc.Type == what);
}
[Pure]
private double ComputeScoreForInferredCalleeAssume(WarningContext.CalleeInfo calleeInfo)
{
var result = ScoreInferredCalleeAssume;
// Using reflection, there are too many cases (26?) to consider, and we may add more in the future...
var thisFields = typeof(WarningScoresManager).GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(f => f.Name.StartsWith(ScoreCalleeAssumeExtraInfo))
.ToArray(); // Use ToArray to force the evaluation
foreach (var enumFlag in Enum.GetValues(typeof(WarningContext.CalleeInfo)).Cast<WarningContext.CalleeInfo>())
{
if (calleeInfo.HasFlag(enumFlag))
{
var fieldName = ScoreCalleeAssumeExtraInfo + enumFlag.ToString();
var field = thisFields.Where(f => f.Name == fieldName).FirstOrDefault();
if (field != null) // Sanity check, should never happen
{
var score = (double)field.GetValue(this);
result *= score;
}
else
{
Contract.Assume(false, "Should never happen");
}
}
}
return result;
}
[Pure]
[ContractVerification(true)]
private double GetScoreForPC(APC pc)
{
var Score = 1.0;
if (pc.Block != null && !pc.PrimaryMethodLocation().HasRealSourceContext)
{
Score *= ScoreNoSourceContext;
}
return Score;
}
#endregion
#region Tracing
public static bool Tracing = false;
#endregion
#region Dump the scores
public void DumpScores(Action<string, object[]> writeline)
{
Contract.Requires(writeline != null);
var empty = new object[0];
writeline("<ClousotScores>", empty);
foreach (var f in typeof(WarningScoresManager).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
{
writeline(" <{0}>{1}</{0}>", new object[] { f.Name, f.GetValue(this).ToString() });
}
writeline("</ClousotScores>", empty);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public class GestureTester : MonoBehaviour {
public Attack beamAttack;
static SteamVR_TrackedController leftController;
static SteamVR_TrackedController rightController;
static SteamVR_Camera thisCamera;
static float armLength = 1.6f / 3;
static float headsetToCenterChest = 0.5f / 3f;
List<Gesture> gestures = new List<Gesture>();
GestureStep gestureStep;
int beamRay = 0;
private Attack beamShot;
private CalibrationTutorial calibrationTutorial;
// Use this for initialization
void Start() {
getCamera();
GetComponent<SteamVR_TrackedController>().TriggerClicked += new ClickedEventHandler(DoTrigger);
GetComponent<SteamVR_TrackedController>().PadTouched += new ClickedEventHandler(DoPad);
calibrationTutorial = FindObjectOfType<CalibrationTutorial>();
}
// Update is called once per frame
void Update() {
if (getLeftController() != null && getRightController() != null) {
if (calibrationTutorial.currentIndex == 0) {
calibrationTutorial.moveTo(1);
}
}
if (beamRay == 0 && beamShot != null) {
SoundEffect sfx = beamShot.gameObject.GetComponent<SoundEffect>();
if (sfx != null) {
sfx.audioSource.Stop();
}
}
if (beamRay >= 2 && (!controllersAreOutstretched() || !controllersAreWithin(0.33f))) {
if (beamShot == null) {
beamRay = 0;
return;
}
beamRay = 0;
BeamParam bp = beamShot.GetComponent<BeamParam>();
if (bp != null) {
bp.bEnd = true;
}
StartCoroutine(destroyBeamShotDelayed());
} else if (beamRay >= 2) {
if (beamShot == null) {
beamRay = 0;
return;
}
beamShot.transform.position = beamGetOrigin();
beamShot.transform.rotation = Quaternion.FromToRotation(Vector3.forward, beamGetOrigin() - beamGetChestLocation());
}
}
System.Collections.IEnumerator destroyBeamShotDelayed() {
yield return new WaitForSeconds(2);
Destroy(beamShot);
}
void DoTrigger(object sender, ClickedEventArgs e) {
if (!getPlayerCharacter().GetComponent<Character>().isAlive()) {
return;
}
if (controllersAreWithin(0.33f) && controllersAtMostAngleFromUp(120f) && controllersAreOutstretched() && beamRay == 1) {
beamRay = 2;
if (beamShot != null) {
Debug.Log("Not going to instantiate another beamShot");
return;
}
beamShot = (Attack) Instantiate(beamAttack, beamGetOrigin(), Quaternion.FromToRotation(Vector3.forward, beamGetOrigin() - beamGetChestLocation()));
SoundEffect sfx = beamShot.gameObject.GetComponent<SoundEffect>();
if (sfx != null) {
sfx.playLoopRandomAudioClip();
}
GeroBeam gb = beamShot.gameObject.GetComponent<GeroBeam>();
if (gb != null) {
gb.hitEvent.AddListener(gbHitEvent);
}
}
if (controllersAreWithin(0.33f) && controllersAtLeastAngleFromUp(120f) && beamRay == 0) {
beamRay = 1;
calibrationTutorial.moveTo(2);
}
}
PlayerCharacter getPlayerCharacter() {
return FindObjectOfType<PlayerCharacter>();
}
void gbHitEvent(GameObject go) {
Character character = go.GetComponent<Character>();
if (character != null) {
Attack.Element damageType = Attack.Element.Physical;
beamAttack.attack(getPlayerCharacter().GetComponent<Character>(), character, damageType);
}
}
static Vector3 beamGetOrigin() {
return (getLeftController().transform.position + getRightController().transform.position) / 2;
}
static Vector3 beamGetChestLocation() {
Vector3 chestLocation = (getCamera()).transform.position;
chestLocation.y -= headsetToCenterChest;
return chestLocation;
}
static bool cameraAtMostAngleFromUp(float angleFromUp) {
return angleFromUp > Vector3.Angle(getCamera().transform.forward, Vector3.up);
}
static bool controllersAreWithin(float rangeOfEachOther) {
Vector3 lPos = getLeftController().transform.position;
Vector3 rPos = getRightController().transform.position;
bool result = (lPos - rPos).magnitude < rangeOfEachOther;
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(rangeOfEachOther): " + result + "\n" +
"rangeOfEachOther: " + rangeOfEachOther + "\n" +
"lPos: " + lPos + "\n" +
"rPos: " + rPos + "\n"
);
*/
return result;
}
static bool controllersAtLeastAngleFromUp(float angleFromUp) {
Vector3 cPos = getCamera().transform.position;
Vector3 lPos = getLeftController().transform.position;
Vector3 rPos = getRightController().transform.position;
float lTheta = Vector3.Angle(Vector3.up, lPos - cPos);
float rTheta = Vector3.Angle(Vector3.up, rPos - cPos);
bool result = lTheta >= angleFromUp && rTheta >= angleFromUp;
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(angleFromUp): " + result + "\n" +
"angleFromUp: " + angleFromUp + "\n" +
"lTheta: " + lTheta + "\n" +
"rTheta: " + rTheta + "\n" +
"cPos: " + cPos + "\n" +
"lPos: " + lPos + "\n" +
"rPos: " + rPos + "\n"
);
);
*/
return result;
}
static bool controllersAtMostAngleFromUp(float angleFromUp) {
Vector3 cPos = getCamera().transform.position;
Vector3 lPos = getLeftController().transform.position;
Vector3 rPos = getRightController().transform.position;
float lTheta = Vector3.Angle(Vector3.up, lPos - cPos);
float rTheta = Vector3.Angle(Vector3.up, lPos - cPos);
bool result = lTheta <= angleFromUp && rTheta <= angleFromUp;
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(angleFromUp): " + result + "\n" +
"angleFromUp: " + angleFromUp + "\n" +
"lTheta: " + lTheta + "\n" +
"rTheta: " + rTheta + "\n" +
"cPos: " + cPos + "\n" +
"lPos: " + lPos + "\n" +
"rPos: " + rPos + "\n"
);
);
*/
return result;
}
static bool controllersAreLevel() {
float lY = getLeftController().transform.position.y;
float rY = getRightController().transform.position.y;
bool result = Mathf.Abs(lY - rY) <= 0.1f;
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(): " + result + "\n" +
"lY: " + lY + "\n" +
"rY: " + rY + "\n"
);
*/
return result;
}
static bool controllersAreOutstretchedLeftAndRight() {
Vector3 cPos = getCamera().transform.position;
Vector3 cRight = getCamera().transform.right;
Vector3 lPos = getLeftController().transform.position;
Vector3 rPos = getRightController().transform.position;
float lTheta = Vector3.Angle(cRight, (lPos - cPos));
float rTheta = Vector3.Angle(cRight, (rPos - cPos));
bool result = lTheta > 180 - 10 && rTheta < 10;
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(): " + result + "\n" +
"lTheta: " + lTheta + "\n" +
"rTheta: " + rTheta + "\n" +
"cRight: " + cRight + "\n" +
"cPos: " + cPos + "\n" +
"lPos: " + lPos + "\n" +
"rPos: " + rPos + "\n"
);
*/
return result;
}
static bool controllersAreOutstretched() {
return controllersAreOutstretched(armLength);
}
static bool controllersAreOutstretched(float armLength) {
Vector3 cPos = getCamera().transform.position;
Vector3 lPos = getLeftController().transform.position;
Vector3 rPos = getRightController().transform.position;
//float lTheta = Vector3.Angle(Vector3.up, lPos - cPos);
//float rTheta = Vector3.Angle(Vector3.up, rPos - cPos);
float lDelta = (lPos - cPos).magnitude;
float rDelta = (rPos - cPos).magnitude;
//bool result = lTheta < 100f && rTheta < 100f && lDelta >= armLength && rDelta >= armLength;
bool result = lDelta >= armLength && rDelta >= armLength;
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(): " + result + "\n" +
"armLength: " + armLength + "\n" +
//"lTheta: " + lTheta + "\n" +
//"rTheta: " + rTheta + "\n" +
"lDelta: " + lDelta + "\n" +
"rDelta: " + rDelta + "\n"
);
*/
return result;
}
static bool controllersAreForward() {
Vector3 cPos = getCamera().transform.position;
Vector3 lPos = getLeftController().transform.position;
Vector3 rPos = getRightController().transform.position;
Vector3 cFwd = getCamera().transform.forward;
bool result = true;
float lTheta = Vector3.Angle(cFwd, (lPos - cPos));
float rTheta = Vector3.Angle(cFwd, (rPos - cPos));
if (lTheta > 85 || rTheta > 85) {
result = false;
}
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(): " + result + "\n" +
"cFwd: " + cFwd + "\n" +
"lTheta: " + lTheta + "\n" +
"rTheta: " + rTheta + "\n" +
"cPos: " + cPos + "\n" +
"lPos: " + lPos + "\n" +
"rPos: " + rPos + "\n"
);
*/
return result;
}
static bool controllersAreAngledForward() {
Vector3 cFwd = getCamera().transform.forward;
Vector3 lFwd = getLeftController().transform.forward;
Vector3 rFwd = getRightController().transform.forward;
bool result = true;
float lTheta = Vector3.Angle(cFwd, lFwd);
float rTheta = Vector3.Angle(cFwd, rFwd);
if (lTheta < 30 || rTheta < 30 || lTheta > 45 || rTheta > 45) {
result = false;
}
/*
Debug.Log(
System.Reflection.MethodBase.GetCurrentMethod().Name + "(): " + result + "\n" +
"lTheta: " + lTheta + "\n" +
"rTheta: " + rTheta + "\n" +
"cFwd: " + cFwd + "\n" +
"lFwd: " + lFwd + "\n" +
"rFwd: " + rFwd + "\n"
);
*/
return result;
}
static bool controllersAreOutstretchedForward() {
return controllersAreOutstretched() & controllersAreForward();
}
static SteamVR_Camera getCamera() {
if (thisCamera == null) {
thisCamera = FindObjectOfType<SteamVR_Camera>();
}
return thisCamera;
}
static SteamVR_TrackedController getLeftController() {
if (leftController == null) {
foreach (SteamVR_TrackedController trackedController in FindObjectsOfType<SteamVR_TrackedController>()) {
float angle = Vector3.Angle(getCamera().transform.right, (trackedController.transform.position - getCamera().transform.position));
if (angle > 135) {
leftController = trackedController;
}
}
}
return leftController;
}
static SteamVR_TrackedController getRightController() {
if (rightController == null) {
foreach (SteamVR_TrackedController trackedController in FindObjectsOfType<SteamVR_TrackedController>()) {
float angle = Vector3.Angle(getCamera().transform.right, (trackedController.transform.position - getCamera().transform.position));
if (angle < 45) {
rightController = trackedController;
}
}
}
return rightController;
}
void DoPad(object sender, ClickedEventArgs e) {
foreach (Gesture gesture in gestures) {
if (gesture.inNextPoint(thisCamera, GetComponent<SteamVR_TrackedObject>())) {
Debug.Log("Yea" + GestureStep.recordGestureStep(thisCamera, GetComponent<SteamVR_TrackedObject>(), 0).ToJson());
} else {
Debug.Log("Naw" + GestureStep.recordGestureStep(thisCamera, GetComponent<SteamVR_TrackedObject>(), 0).ToJson());
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Tests
{
public partial class SelectManyTests : EnumerableTests
{
[Fact]
public void EmptySource()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total));
}
[Fact]
public void EmptySourceIndexedSelector()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, i) => e.total));
}
[Fact]
public void EmptySourceResultSelector()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total, (e, f) => f.ToString()));
}
[Fact]
public void EmptySourceResultSelectorIndexedSelector()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, i) => e.total, (e, f) => f.ToString()));
}
[Fact]
public void SingleElement()
{
int?[] expected = { 90, 55, null, 43, 89 };
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = expected }
};
Assert.Equal(expected, source.SelectMany(e => e.total));
}
[Fact]
public void NonEmptySelectingEmpty()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[0] },
new StringWithIntArray { name="Bob", total=new int?[0] },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[0] },
new StringWithIntArray { name="Prakash", total=new int?[0] }
};
Assert.Empty(source.SelectMany(e => e.total));
}
[Fact]
public void NonEmptySelectingEmptyIndexedSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[0] },
new StringWithIntArray { name="Bob", total=new int?[0] },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[0] },
new StringWithIntArray { name="Prakash", total=new int?[0] }
};
Assert.Empty(source.SelectMany((e, i) => e.total));
}
[Fact]
public void NonEmptySelectingEmptyWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[0] },
new StringWithIntArray { name="Bob", total=new int?[0] },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[0] },
new StringWithIntArray { name="Prakash", total=new int?[0] }
};
Assert.Empty(source.SelectMany(e => e.total, (e, f) => f.ToString()));
}
[Fact]
public void NonEmptySelectingEmptyIndexedSelectorWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[0] },
new StringWithIntArray { name="Bob", total=new int?[0] },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[0] },
new StringWithIntArray { name="Prakash", total=new int?[0] }
};
Assert.Empty(source.SelectMany((e, i) => e.total, (e, f) => f.ToString()));
}
[Fact]
public void ResultsSelected()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} }
};
int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 };
Assert.Equal(expected, source.SelectMany(e => e.total));
}
[Fact]
public void RunOnce()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} }
};
int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 };
Assert.Equal(expected, source.RunOnce().SelectMany(e => e.total.RunOnce()));
}
[Fact]
public void SourceEmptyIndexUsed()
{
Assert.Empty(Enumerable.Empty<StringWithIntArray>().SelectMany((e, index) => e.total));
}
[Fact]
public void SingleElementIndexUsed()
{
int?[] expected = { 90, 55, null, 43, 89 };
StringWithIntArray[] source =
{
new StringWithIntArray { name = "Prakash", total = expected }
};
Assert.Equal(expected, source.SelectMany((e, index) => e.total));
}
[Fact]
public void NonEmptySelectingEmptyIndexUsed()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total= new int?[0] },
new StringWithIntArray { name="Bob", total=new int?[0] },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[0] },
new StringWithIntArray { name="Prakash", total=new int?[0] }
};
Assert.Empty(source.SelectMany((e, index) => e.total));
}
[Fact]
public void ResultsSelectedIndexUsed()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} }
};
int?[] expected = { 1, 2, 3, 4, 5, 6, 8, 9, -10, 100 };
Assert.Equal(expected, source.SelectMany((e, index) => e.total));
}
[Fact]
public void IndexCausingFirstToBeSelected()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} }
};
Assert.Equal(source.First().total, source.SelectMany((e, i) => i == 0 ? e.total : Enumerable.Empty<int?>()));
}
[Fact]
public void IndexCausingLastToBeSelected()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Robert", total=new int?[]{-10, 100} }
};
Assert.Equal(source.Last().total, source.SelectMany((e, i) => i == 4 ? e.total : Enumerable.Empty<int?>()));
}
[Fact(Skip = "Valid test but too intensive to enable even in OuterLoop")]
public void IndexOverflow()
{
var selected = new FastInfiniteEnumerator<int>().SelectMany((e, i) => Enumerable.Empty<int>());
using (var en = selected.GetEnumerator())
Assert.Throws<OverflowException>(() =>
{
while(en.MoveNext())
{
}
});
}
[Fact]
public void ResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} }
};
string[] expected = { "1", "2", "3", "4", "5", "6", "8", "9", "-10", "100" };
Assert.Equal(expected, source.SelectMany(e => e.total, (e, f) => f.ToString()));
}
[Fact]
public void NullResultSelector()
{
Func<StringWithIntArray, int?, string> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany(e => e.total, resultSelector));
}
[Fact]
public void NullResultSelectorIndexedSelector()
{
Func<StringWithIntArray, int?, string> resultSelector = null;
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany((e, i) => e.total, resultSelector));
}
[Fact]
public void NullSourceWithResultSelector()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.SelectMany(e => e.total, (e, f) => f.ToString()));
}
[Fact]
public void NullCollectionSelector()
{
Func<StringWithIntArray, IEnumerable<int?>> collectionSelector = null;
AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany(collectionSelector, (e, f) => f.ToString()));
}
[Fact]
public void NullIndexedCollectionSelector()
{
Func<StringWithIntArray, int, IEnumerable<int?>> collectionSelector = null;
AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () => Enumerable.Empty<StringWithIntArray>().SelectMany(collectionSelector, (e, f) => f.ToString()));
}
[Fact]
public void NullSource()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.SelectMany(e => e.total));
}
[Fact]
public void NullSourceIndexedSelector()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.SelectMany((e, i) => e.total));
}
[Fact]
public void NullSourceIndexedSelectorWithResultSelector()
{
StringWithIntArray[] source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.SelectMany((e, i) => e.total, (e, f) => f.ToString()));
}
[Fact]
public void NullSelector()
{
Func<StringWithIntArray, int[]> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => new StringWithIntArray[0].SelectMany(selector));
}
[Fact]
public void NullIndexedSelector()
{
Func<StringWithIntArray, int, int[]> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => new StringWithIntArray[0].SelectMany(selector));
}
[Fact]
public void IndexCausingFirstToBeSelectedWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Prakash", total=new int?[]{-10, 100} }
};
string[] expected = { "1", "2", "3", "4" };
Assert.Equal(expected, source.SelectMany((e, i) => i == 0 ? e.total : Enumerable.Empty<int?>(), (e, f) => f.ToString()));
}
[Fact]
public void IndexCausingLastToBeSelectedWithResultSelector()
{
StringWithIntArray[] source =
{
new StringWithIntArray { name="Prakash", total=new int?[]{1, 2, 3, 4} },
new StringWithIntArray { name="Bob", total=new int?[]{5, 6} },
new StringWithIntArray { name="Chris", total=new int?[0] },
new StringWithIntArray { name=null, total=new int?[]{8, 9} },
new StringWithIntArray { name="Robert", total=new int?[]{-10, 100} }
};
string[] expected = { "-10", "100" };
Assert.Equal(expected, source.SelectMany((e, i) => i == 4 ? e.total : Enumerable.Empty<int?>(), (e, f) => f.ToString()));
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany(i => new int[0]);
// Don't insist on this behaviour, but check it's correct if it happens
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateIndexed()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany((e, i) => new int[0]);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateResultSel()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany(i => new int[0], (e, i) => e);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerateIndexedResultSel()
{
var iterator = NumberRangeGuaranteedNotCollectionType(0, 3).SelectMany((e, i) => new int[0], (e, i) => e);
var en = iterator as IEnumerator<int>;
Assert.False(en != null && en.MoveNext());
}
[Theory]
[MemberData(nameof(ParameterizedTestsData))]
public void ParameterizedTests(IEnumerable<int> source, Func<int, IEnumerable<int>> selector)
{
var expected = source.Select(i => selector(i)).Aggregate((l, r) => l.Concat(r));
var actual = source.SelectMany(selector);
Assert.Equal(expected, actual);
Assert.Equal(expected.Count(), actual.Count()); // SelectMany may employ an optimized Count implementation.
Assert.Equal(expected.ToArray(), actual.ToArray());
Assert.Equal(expected.ToList(), actual.ToList());
}
public static IEnumerable<object[]> ParameterizedTestsData()
{
for (int i = 1; i <= 20; i++)
{
Func<int, IEnumerable<int>> selector = n => Enumerable.Range(i, n);
yield return new object[] { Enumerable.Range(1, i), selector };
}
}
[Theory]
[MemberData(nameof(DisposeAfterEnumerationData))]
public void DisposeAfterEnumeration(int sourceLength, int subLength)
{
int sourceState = 0;
int subIndex = 0; // Index within the arrays the sub-collection is supposed to be at.
int[] subState = new int[sourceLength];
bool sourceDisposed = false;
bool[] subCollectionDisposed = new bool[sourceLength];
var source = new DelegateIterator<int>(
moveNext: () => ++sourceState <= sourceLength,
current: () => 0,
dispose: () => sourceDisposed = true);
var subCollection = new DelegateIterator<int>(
moveNext: () => ++subState[subIndex] <= subLength, // Return true `subLength` times.
current: () => subState[subIndex],
dispose: () => subCollectionDisposed[subIndex++] = true); // Record that Dispose was called, and move on to the next index.
var iterator = source.SelectMany(_ => subCollection);
int index = 0; // How much have we gone into the iterator?
IEnumerator<int> e = iterator.GetEnumerator();
using (e)
{
while (e.MoveNext())
{
int item = e.Current;
Assert.Equal(subState[subIndex], item); // Verify Current.
Assert.Equal(index / subLength, subIndex);
Assert.False(sourceDisposed); // Not yet.
// This represents whehter the sub-collection we're iterating thru right now
// has been disposed. Also not yet.
Assert.False(subCollectionDisposed[subIndex]);
// However, all of the sub-collections before us should have been disposed.
// Their indices should also be maxed out.
Assert.All(subState.Take(subIndex), s => Assert.Equal(subLength + 1, s));
Assert.All(subCollectionDisposed.Take(subIndex), t => Assert.True(t));
index++;
}
}
Assert.True(sourceDisposed);
Assert.Equal(sourceLength, subIndex);
Assert.All(subState, s => Assert.Equal(subLength + 1, s));
Assert.All(subCollectionDisposed, t => Assert.True(t));
// .NET Core fixes an oversight where we wouldn't properly dispose
// the SelectMany iterator. See https://github.com/dotnet/corefx/pull/13942.
int expectedCurrent = PlatformDetection.IsFullFramework ? subLength : 0;
Assert.Equal(expectedCurrent, e.Current);
Assert.False(e.MoveNext());
Assert.Equal(expectedCurrent, e.Current);
}
public static IEnumerable<object[]> DisposeAfterEnumerationData()
{
int[] lengths = { 1, 2, 3, 5, 8, 13, 21, 34 };
return lengths.SelectMany(l => lengths, (l1, l2) => new object[] { l1, l2 });
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core optimizes SelectMany and throws an OverflowException. On the full .NET Framework this takes a long time. See https://github.com/dotnet/corefx/pull/13942.")]
[InlineData(new[] { int.MaxValue, 1 })]
[InlineData(new[] { 2, int.MaxValue - 1 })]
[InlineData(new[] { 123, 456, int.MaxValue - 100000, 123456 })]
public void ThrowOverflowExceptionOnConstituentLargeCounts(int[] counts)
{
IEnumerable<int> iterator = counts.SelectMany(c => Enumerable.Range(1, c));
Assert.Throws<OverflowException>(() => iterator.Count());
}
[Theory]
[MemberData(nameof(GetToArrayDataSources))]
public void CollectionInterleavedWithLazyEnumerables_ToArray(IEnumerable<int>[] arrays)
{
// See https://github.com/dotnet/corefx/issues/23680
int[] results = arrays.SelectMany(ar => ar).ToArray();
for (int i = 0; i < results.Length; i++)
{
Assert.Equal(i, results[i]);
}
}
private static IEnumerable<object[]> GetToArrayDataSources()
{
// Marker at the end
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new TestEnumerable<int>(new int[] { 1 }),
new TestEnumerable<int>(new int[] { 2 }),
new int[] { 3 },
}
};
// Marker at beginning
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new TestEnumerable<int>(new int[] { 2 }),
new TestEnumerable<int>(new int[] { 3 }),
}
};
// Marker in middle
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new int[] { 1 },
new TestEnumerable<int>(new int[] { 2 }),
}
};
// Non-marker in middle
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new int[] { 2 },
}
};
// Big arrays (marker in middle)
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(Enumerable.Range(0, 100).ToArray()),
Enumerable.Range(100, 100).ToArray(),
new TestEnumerable<int>(Enumerable.Range(200, 100).ToArray()),
}
};
// Big arrays (non-marker in middle)
yield return new object[]
{
new IEnumerable<int>[]
{
Enumerable.Range(0, 100).ToArray(),
new TestEnumerable<int>(Enumerable.Range(100, 100).ToArray()),
Enumerable.Range(200, 100).ToArray(),
}
};
// Interleaved (first marker)
yield return new object[]
{
new IEnumerable<int>[]
{
new int[] { 0 },
new TestEnumerable<int>(new int[] { 1 }),
new int[] { 2 },
new TestEnumerable<int>(new int[] { 3 }),
new int[] { 4 },
}
};
// Interleaved (first non-marker)
yield return new object[]
{
new IEnumerable<int>[]
{
new TestEnumerable<int>(new int[] { 0 }),
new int[] { 1 },
new TestEnumerable<int>(new int[] { 2 }),
new int[] { 3 },
new TestEnumerable<int>(new int[] { 4 }),
}
};
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Index;
using Lucene.Net.Support;
using Lucene.Net.Util;
namespace Lucene.Net.Search
{
public class BooleanFilter : Filter
{
/// <summary>
/// The filters that are optional clauses.
/// </summary>
private List<Filter> shouldFilters = null;
/// <summary>
/// The filters that are used for exclusion.
/// </summary>
private List<Filter> notFilters = null;
/// <summary>
/// The filters that must be met.
/// </summary>
private List<Filter> mustFilters = null;
/// <summary>
/// Get the iterator for a specific filter.
/// </summary>
/// <param name="filters">The list of filters</param>
/// <param name="index">The index of the iterator to get.</param>
/// <param name="reader">The reader for the index.</param>
/// <returns></returns>
private DocIdSetIterator GetDISI(List<Filter> filters, int index, IndexReader reader)
{
return filters[index].GetDocIdSet(reader).Iterator();
}
/// <summary>
/// Get the id set for the filter.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>The filter set to use.</returns>
public override DocIdSet GetDocIdSet(IndexReader reader)
{
OpenBitSetDISI res = null;
if (shouldFilters != null)
{
for (int i = 0; i < shouldFilters.Count; i++)
{
if (res == null)
{
res = new OpenBitSetDISI(GetDISI(shouldFilters, i, reader), reader.MaxDoc);
}
else
{
DocIdSet dis = shouldFilters[i].GetDocIdSet(reader);
if (dis is OpenBitSet)
{
// optimized case for OpenBitSets
res.Or((OpenBitSet)dis);
}
else
{
res.InPlaceOr(GetDISI(shouldFilters, i, reader));
}
}
}
}
if (notFilters != null)
{
for (int i = 0; i < notFilters.Count; i++)
{
if (res == null)
{
res = new OpenBitSetDISI(GetDISI(notFilters, i, reader), reader.MaxDoc);
res.Flip(0, reader.MaxDoc); // NOTE: may set bits on deleted docs
}
else
{
DocIdSet dis = notFilters[i].GetDocIdSet(reader);
if (dis is OpenBitSet)
{
// optimized case for OpenBitSets
res.AndNot((OpenBitSet)dis);
}
else
{
res.InPlaceNot(GetDISI(notFilters, i, reader));
}
}
}
}
if (mustFilters != null)
{
for (int i = 0; i < mustFilters.Count; i++)
{
if (res == null)
{
res = new OpenBitSetDISI(GetDISI(mustFilters, i, reader), reader.MaxDoc);
}
else
{
DocIdSet dis = mustFilters[i].GetDocIdSet(reader);
if (dis is OpenBitSet)
{
// optimized case for OpenBitSets
res.And((OpenBitSet)dis);
}
else
{
res.InPlaceAnd(GetDISI(mustFilters, i, reader));
}
}
}
}
if (res != null)
return FinalResult(res, reader.MaxDoc);
return DocIdSet.EMPTY_DOCIDSET;
}
/* Provide a SortedVIntList when it is definitely smaller
* than an OpenBitSet.
* @deprecated Either use CachingWrapperFilter, or
* switch to a different DocIdSet implementation yourself.
* This method will be removed in Lucene 4.0
*/
protected DocIdSet FinalResult(OpenBitSetDISI result, int maxDocs)
{
return result;
}
/// <summary>
/// Add a filter clause.
/// </summary>
/// <param name="filterClause">The clause to add.</param>
public void Add(FilterClause filterClause)
{
if (filterClause.Occur == Occur.MUST)
{
if (mustFilters == null)
{
mustFilters = new EquatableList<Filter>();
}
mustFilters.Add(filterClause.Filter);
}
if (filterClause.Occur == Occur.SHOULD)
{
if (shouldFilters == null)
{
shouldFilters = new EquatableList<Filter>();
}
shouldFilters.Add(filterClause.Filter);
}
if (filterClause.Occur == Occur.MUST_NOT)
{
if (notFilters == null)
{
notFilters = new EquatableList<Filter>();
}
notFilters.Add(filterClause.Filter);
}
}
/// <summary>
/// Determine equality between two lists.
/// </summary>
/// <param name="filters1"></param>
/// <param name="filters2"></param>
/// <returns></returns>
private bool EqualFilters(List<Filter> filters1, List<Filter> filters2)
{
return (filters1 == filters2) ||
((filters1 != null) && filters1.Equals(filters2));
}
/// <summary>
/// Equality
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(Object obj)
{
if (this == obj)
return true;
if ((obj == null) || !(obj is BooleanFilter))
return false;
BooleanFilter other = (BooleanFilter)obj;
return EqualFilters(notFilters, other.notFilters)
&& EqualFilters(mustFilters, other.mustFilters)
&& EqualFilters(shouldFilters, other.shouldFilters);
}
/// <summary>
/// Hash code.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
int hash = 7;
hash = 31 * (hash + this.ListHash(this.mustFilters));
hash = 31 * (hash + this.ListHash(this.notFilters));
hash = 31 * (hash + this.ListHash(this.shouldFilters));
return hash;
}
private int ListHash(List<Filter> filters)
{
int sum = 0;
if (filters != null && filters.Count > 0)
{
for (int i = 0; i < filters.Count; i++)
{
sum += filters[i].GetHashCode();
}
}
return sum;
}
/// <summary>
/// String representation.
/// </summary>
/// <returns></returns>
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("BooleanFilter(");
AppendFilters(shouldFilters, "", buffer);
AppendFilters(mustFilters, "+", buffer);
AppendFilters(notFilters, "-", buffer);
buffer.Append(")");
return buffer.ToString();
}
/// <summary>
/// Append individual filters.
/// </summary>
/// <param name="filters"></param>
/// <param name="occurString"></param>
/// <param name="buffer"></param>
private void AppendFilters(List<Filter> filters, String occurString, StringBuilder buffer)
{
if (filters != null)
{
for (int i = 0; i < filters.Count(); i++)
{
buffer.Append(' ');
buffer.Append(occurString);
buffer.Append(filters[i].ToString());
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.DocumentationCommentFormatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly ISymbolDisplayService _displayService;
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap =
new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>();
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
ISymbolDisplayService displayService,
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_displayService = displayService;
_anonymousTypeDisplayService = anonymousTypeDisplayService;
this.Workspace = workspace;
this.CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected void AddPrefixTextForAwaitKeyword()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.PrefixTextForAwaitKeyword),
Space());
}
protected void AddTextForSystemVoid()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.TextForSystemVoid));
}
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations())
{
// find the reference that contains the given tree
if (referencedCompilation.ContainsSyntaxTree(tree))
{
return referencedCompilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Contract.Requires(false, "How?");
return null;
}
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(symbols[0]);
AddExceptions(symbols[0]);
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions}"));
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute"))
{
AddDeprecatedPrefix();
}
if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol)
{
await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol)
{
await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol)
{
AddDescriptionForMethod((IMethodSymbol)symbol);
}
else if (symbol is ILabelSymbol)
{
AddDescriptionForLabel((ILabelSymbol)symbol);
}
else if (symbol is INamedTypeSymbol)
{
AddDescriptionForNamedType((INamedTypeSymbol)symbol);
}
else if (symbol is INamespaceSymbol)
{
AddDescriptionForNamespace((INamespaceSymbol)symbol);
}
else if (symbol is IParameterSymbol)
{
await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol)
{
AddDescriptionForProperty((IPropertySymbol)symbol);
}
else if (symbol is IRangeVariableSymbol)
{
AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol);
}
else if (symbol is ITypeParameterSymbol)
{
AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol);
}
else if (symbol is IAliasSymbol)
{
await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
// Everything else is in a group on its own
return 2;
default:
return Contract.FailWithReturn<int>("unknown part kind");
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>> BuildDescriptionSections()
{
return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AsImmutableOrEmpty());
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.RepresentsAnObjectWhoseOperations));
}
private void AddDescriptionForNamedType(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitable(_semanticModel, _position))
{
AddAwaitablePrefix();
}
var token = _semanticModel.SyntaxTree.GetTouchingToken(_position, this.CancellationToken);
if (token != default(SyntaxToken))
{
var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>();
if (syntaxFactsService.IsAwaitKeyword(token))
{
AddPrefixTextForAwaitKeyword();
if (symbol.SpecialType == SpecialType.System_Void)
{
AddTextForSystemVoid();
return;
}
}
}
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle));
}
if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol))
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
}
private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (int i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.Constant)
: Description(FeaturesResources.Field),
parts);
}
}
private async Task<IEnumerable<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.LocalConstant)
: Description(FeaturesResources.LocalVariable),
parts);
}
private async Task<IEnumerable<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.RangeVariable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
// TODO : a way to check whether it is a member call off dynamic type?
var awaitable = method.IsAwaitable(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
if (awaitable)
{
AddAwaitableUsageText(method, _semanticModel, _position);
}
}
protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position);
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
IEnumerable<SymbolDisplayPart> initializerParts;
if (symbol.IsOptional)
{
initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.Parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
protected virtual void AddDescriptionForProperty(IPropertySymbol symbol)
{
if (symbol.IsIndexer)
{
// TODO : show duplicated member case
// TODO : a way to check whether it is a member call off dynamic type?
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
return;
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.In),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.Overload) : PlainText(FeaturesResources.Overloads),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (int i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.Is));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
{
AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
}
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
IList<SymbolDisplayPart> existingParts;
if (!_groupMap.TryGetValue(group, out existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected IEnumerable<SymbolDisplayPart> Keyword(string text)
{
return Part(SymbolDisplayPartKind.Keyword, text);
}
protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (int i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected IEnumerable<SymbolDisplayPart> PlainText(string text)
{
return Part(SymbolDisplayPartKind.Text, text);
}
protected IEnumerable<SymbolDisplayPart> Punctuation(string text)
{
return Part(SymbolDisplayPartKind.Punctuation, text);
}
protected IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected IEnumerable<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format = format ?? MinimallyQualifiedFormat;
return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format);
}
protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
return _displayService.ToDisplayParts(symbol, format);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
{
return Part(kind, null, text);
}
private IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
{
return Part(SymbolDisplayPartKind.TypeParameterName, text);
}
protected IEnumerable<SymbolDisplayPart> ConvertClassifications(SourceText text, IEnumerable<ClassifiedSpan> classifications)
{
var parts = new List<SymbolDisplayPart>();
ClassifiedSpan? lastSpan = null;
foreach (var span in classifications)
{
// If there is space between this span and the last one, then add a space.
if (lastSpan != null && lastSpan.Value.TextSpan.End != span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, text.ToString(span.TextSpan)));
lastSpan = span;
}
}
return parts;
}
private SymbolDisplayPartKind? GetClassificationKind(string type)
{
switch (type)
{
default:
return null;
case ClassificationTypeNames.Identifier:
return SymbolDisplayPartKind.Text;
case ClassificationTypeNames.Keyword:
return SymbolDisplayPartKind.Keyword;
case ClassificationTypeNames.NumericLiteral:
return SymbolDisplayPartKind.NumericLiteral;
case ClassificationTypeNames.StringLiteral:
return SymbolDisplayPartKind.StringLiteral;
case ClassificationTypeNames.WhiteSpace:
return SymbolDisplayPartKind.Space;
case ClassificationTypeNames.Operator:
return SymbolDisplayPartKind.Operator;
case ClassificationTypeNames.Punctuation:
return SymbolDisplayPartKind.Punctuation;
case ClassificationTypeNames.ClassName:
return SymbolDisplayPartKind.ClassName;
case ClassificationTypeNames.StructName:
return SymbolDisplayPartKind.StructName;
case ClassificationTypeNames.InterfaceName:
return SymbolDisplayPartKind.InterfaceName;
case ClassificationTypeNames.DelegateName:
return SymbolDisplayPartKind.DelegateName;
case ClassificationTypeNames.EnumName:
return SymbolDisplayPartKind.EnumName;
case ClassificationTypeNames.TypeParameterName:
return SymbolDisplayPartKind.TypeParameterName;
case ClassificationTypeNames.ModuleName:
return SymbolDisplayPartKind.ModuleName;
case ClassificationTypeNames.VerbatimStringLiteral:
return SymbolDisplayPartKind.StringLiteral;
}
}
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2008 the Open Toolkit library, except where noted.
//
// 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.Text;
using System.Drawing;
namespace OpenTK.Graphics.Text
{
class GlyphPacker
{
Node root;
#region --- Constructors ---
public GlyphPacker(int width, int height)
{
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width, "Must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height, "Must be greater than zero.");
root = new Node();
root.Rectangle = new Rectangle(0, 0, width, width);
}
#endregion
#region --- Public Methods ---
#region public bool TryAdd(Rectangle boundingBox)
/// <summary>
/// Adds boundingBox to the GlyphPacker.
/// </summary>
/// <param name="boundingBox">The bounding box of the item to pack.</param>
/// <param name="packedRectangle">The System.Drawing.Rectangle that contains the position of the packed item.</param>
/// <returns>True, if the item was successfully packed; false if the item is too big for this packer..</returns>
/// <exception cref="InvalidOperationException">Occurs if the item is larger than the available TexturePacker area</exception>
/// <exception cref="TexturePackerFullException">Occurs if the item cannot fit in the remaining packer space.</exception>
public bool TryAdd(Rectangle boundingBox, out Rectangle packedRectangle)
{
if (!root.Rectangle.Contains(boundingBox))
{
packedRectangle = new Rectangle();
return false;
}
// Increase size so that the glyphs do not touch each other (to avoid rendering artifacts).
boundingBox.Width += 2;
boundingBox.Height += 2;
Node node = root.Insert(boundingBox);
// Tree is full and insertion failed:
if (node == null)
{
packedRectangle = new Rectangle();
return false;
}
packedRectangle = new Rectangle(node.Rectangle.X, node.Rectangle.Y, node.Rectangle.Width - 2, node.Rectangle.Height - 2);
return true;
}
#endregion
#region public Rectangle TryAdd(RectangleF boundingBox)
/// <summary>
/// Adds boundingBox to the GlyphPacker.
/// </summary>
/// <param name="boundingBox">The bounding box of the item to pack.</param>
/// <param name="packedRectangle">The System.Drawing.RectangleF that contains the position of the packed item.</param>
/// <returns>True, if the item was successfully packed; false if the item is too big for this packer..</returns>
/// <exception cref="InvalidOperationException">Occurs if the item is larger than the available TexturePacker area</exception>
/// <exception cref="TexturePackerFullException">Occurs if the item cannot fit in the remaining packer space.</exception>
public bool TryAdd(RectangleF boundingBox, out RectangleF packedRectangle)
{
Rectangle bbox = new Rectangle(
(int)boundingBox.X, (int)boundingBox.Y,
(int)(boundingBox.Width + 0.5f), (int)(boundingBox.Height + 0.5f));
return TryAdd(bbox, out packedRectangle);
}
#endregion
#region public Rectangle Add(Rectangle boundingBox)
/// <summary>
/// Adds boundingBox to the GlyphPacker.
/// </summary>
/// <param name="boundingBox">The bounding box of the item to pack.</param>
/// <returns>A System.Drawing.Rectangle containing the coordinates of the packed item.</returns>
/// <exception cref="InvalidOperationException">Occurs if the item is larger than the available TexturePacker area</exception>
/// <exception cref="TexturePackerFullException">Occurs if the item cannot fit in the remaining packer space.</exception>
public Rectangle Add(Rectangle boundingBox)
{
if (!TryAdd(boundingBox, out boundingBox))
throw new TexturePackerFullException();
return boundingBox;
}
#endregion
#region public Rectangle Add(RectangleF boundingBox)
/// <summary>
/// Rounds boundingBox to the largest integer and adds the resulting Rectangle to the GlyphPacker.
/// </summary>
/// <param name="boundingBox">The bounding box of the item to pack.</param>
/// <returns>A System.Drawing.Rectangle containing the coordinates of the packed item.</returns>
/// <exception cref="InvalidOperationException">Occurs if the item is larger than the available TexturePacker area</exception>
/// <exception cref="ArgumentException">Occurs if the item already exists in the TexturePacker.</exception>
public Rectangle Add(RectangleF boundingBox)
{
Rectangle bbox = new Rectangle(
(int)boundingBox.X, (int)boundingBox.Y,
(int)(boundingBox.Width + 0.5f), (int)(boundingBox.Height + 0.5f));
return Add(bbox);
}
#endregion
#region public void Clear()
/// <summary>
/// Discards all packed items.
/// </summary>
public void Clear()
{
root.Clear();
}
#endregion
#endregion
#region Node
class Node
{
public Node()
{
}
Node left, right;
Rectangle rect;
bool occupied;
public Rectangle Rectangle { get { return rect; } set { rect = value; } }
public Node Left { get { return left; } set { left = value; } }
public Node Right { get { return right; } set { right = value; } }
#region --- Constructor ---
public bool Leaf
{
get { return left == null && right == null; }
}
#endregion
#region Node Insert(Rectangle bbox)
public Node Insert( Rectangle bbox)
{
if (!this.Leaf)
{
// Recurse towards left child, and if that fails, towards the right.
Node new_node = left.Insert(bbox);
return new_node ?? right.Insert(bbox);
}
else
{
// We have recursed to a leaf.
// If it is not empty go back.
if (occupied)
return null;
// If this leaf is too small go back.
if (rect.Width < bbox.Width || rect.Height < bbox.Height)
return null;
// If this leaf is the right size, insert here.
if (rect.Width == bbox.Width && rect.Height == bbox.Height)
{
occupied = true;
return this;
}
// This leaf is too large, split it up. We'll decide which way to split
// by checking the width and height difference between this rectangle and
// out item's bounding box. If the width difference is larger, we'll split
// horizontaly, else verticaly.
left = new Node();
right = new Node();
int dw = this.rect.Width - bbox.Width + 1;
int dh = this.rect.Height - bbox.Height + 1;
if (dw > dh)
{
left.rect = new Rectangle(rect.Left, rect.Top, bbox.Width, rect.Height);
right.rect = new Rectangle(rect.Left + bbox.Width, rect.Top, rect.Width - bbox.Width, rect.Height);
}
else
{
left.rect = new Rectangle(rect.Left, rect.Top, rect.Width, bbox.Height);
right.rect = new Rectangle(rect.Left, rect.Top + bbox.Height, rect.Width, rect.Height - bbox.Height);
}
return left.Insert(bbox);
}
}
#endregion
#region public void Clear()
public void Clear()
{
if (left != null)
left.Clear();
if (right != null)
right.Clear();
left = right = null;
}
#endregion
}
#endregion
}
class TexturePackerFullException : Exception
{
public TexturePackerFullException() : base("There is not enough space to add this item. Consider calling the Clear() method.") { }
}
}
| |
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>
/// A matrix of type Complex with 2 columns and 3 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct cmat2x3 : IReadOnlyList<Complex>, IEquatable<cmat2x3>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public Complex m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public Complex m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
[DataMember]
public Complex m02;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public Complex m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public Complex m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
[DataMember]
public Complex m12;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public cmat2x3(Complex m00, Complex m01, Complex m02, Complex m10, Complex m11, Complex m12)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
}
/// <summary>
/// Constructs this matrix from a cmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = Complex.Zero;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a cmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a cmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a cmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a cmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a cmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a cmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cvec2 c0, cvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = Complex.Zero;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = Complex.Zero;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public cmat2x3(cvec3 c0, cvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public Complex[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public Complex[] Values1D => new[] { m00, m01, m02, m10, m11, m12 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public cvec3 Column0
{
get
{
return new cvec3(m00, m01, m02);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public cvec3 Column1
{
get
{
return new cvec3(m10, m11, m12);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public cvec2 Row0
{
get
{
return new cvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public cvec2 Row1
{
get
{
return new cvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public cvec2 Row2
{
get
{
return new cvec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static cmat2x3 Zero { get; } = new cmat2x3(Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static cmat2x3 Ones { get; } = new cmat2x3(Complex.One, Complex.One, Complex.One, Complex.One, Complex.One, Complex.One);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static cmat2x3 Identity { get; } = new cmat2x3(Complex.One, Complex.Zero, Complex.Zero, Complex.Zero, Complex.One, Complex.Zero);
/// <summary>
/// Predefined all-imaginary-ones matrix
/// </summary>
public static cmat2x3 ImaginaryOnes { get; } = new cmat2x3(Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne);
/// <summary>
/// Predefined diagonal-imaginary-one matrix
/// </summary>
public static cmat2x3 ImaginaryIdentity { get; } = new cmat2x3(Complex.ImaginaryOne, Complex.Zero, Complex.Zero, Complex.Zero, Complex.ImaginaryOne, Complex.Zero);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<Complex> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m10;
yield return m11;
yield return m12;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 3 = 6).
/// </summary>
public int Count => 6;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public Complex this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m10;
case 4: return m11;
case 5: return m12;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m10 = value; break;
case 4: this.m11 = value; break;
case 5: this.m12 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public Complex this[int col, int row]
{
get
{
return this[col * 3 + row];
}
set
{
this[col * 3 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(cmat2x3 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && m12.Equals(rhs.m12)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is cmat2x3 && Equals((cmat2x3) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(cmat2x3 lhs, cmat2x3 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(cmat2x3 lhs, cmat2x3 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public cmat3x2 Transposed => new cmat3x2(m00, m10, m01, m11, m02, m12);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public double Length => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + m02.LengthSqr()) + ((m10.LengthSqr() + m11.LengthSqr()) + m12.LengthSqr())));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public double LengthSqr => (((m00.LengthSqr() + m01.LengthSqr()) + m02.LengthSqr()) + ((m10.LengthSqr() + m11.LengthSqr()) + m12.LengthSqr()));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public Complex Sum => (((m00 + m01) + m02) + ((m10 + m11) + m12));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public double Norm => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + m02.LengthSqr()) + ((m10.LengthSqr() + m11.LengthSqr()) + m12.LengthSqr())));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public double Norm1 => (((m00.Magnitude + m01.Magnitude) + m02.Magnitude) + ((m10.Magnitude + m11.Magnitude) + m12.Magnitude));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public double Norm2 => (double)Math.Sqrt((((m00.LengthSqr() + m01.LengthSqr()) + m02.LengthSqr()) + ((m10.LengthSqr() + m11.LengthSqr()) + m12.LengthSqr())));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public Complex NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00.Magnitude, m01.Magnitude), m02.Magnitude), m10.Magnitude), m11.Magnitude), m12.Magnitude);
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)m00.Magnitude, p) + Math.Pow((double)m01.Magnitude, p)) + Math.Pow((double)m02.Magnitude, p)) + ((Math.Pow((double)m10.Magnitude, p) + Math.Pow((double)m11.Magnitude, p)) + Math.Pow((double)m12.Magnitude, p))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication cmat2x3 * cmat2 -> cmat2x3.
/// </summary>
public static cmat2x3 operator*(cmat2x3 lhs, cmat2 rhs) => new cmat2x3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication cmat2x3 * cmat3x2 -> cmat3.
/// </summary>
public static cmat3 operator*(cmat2x3 lhs, cmat3x2 rhs) => new cmat3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication cmat2x3 * cmat4x2 -> cmat4x3.
/// </summary>
public static cmat4x3 operator*(cmat2x3 lhs, cmat4x2 rhs) => new cmat4x3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static cvec3 operator*(cmat2x3 m, cvec2 v) => new cvec3((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static cmat2x3 CompMul(cmat2x3 A, cmat2x3 B) => new cmat2x3(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static cmat2x3 CompDiv(cmat2x3 A, cmat2x3 B) => new cmat2x3(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static cmat2x3 CompAdd(cmat2x3 A, cmat2x3 B) => new cmat2x3(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static cmat2x3 CompSub(cmat2x3 A, cmat2x3 B) => new cmat2x3(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static cmat2x3 operator+(cmat2x3 lhs, cmat2x3 rhs) => new cmat2x3(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static cmat2x3 operator+(cmat2x3 lhs, Complex rhs) => new cmat2x3(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static cmat2x3 operator+(Complex lhs, cmat2x3 rhs) => new cmat2x3(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static cmat2x3 operator-(cmat2x3 lhs, cmat2x3 rhs) => new cmat2x3(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static cmat2x3 operator-(cmat2x3 lhs, Complex rhs) => new cmat2x3(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static cmat2x3 operator-(Complex lhs, cmat2x3 rhs) => new cmat2x3(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static cmat2x3 operator/(cmat2x3 lhs, Complex rhs) => new cmat2x3(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static cmat2x3 operator/(Complex lhs, cmat2x3 rhs) => new cmat2x3(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static cmat2x3 operator*(cmat2x3 lhs, Complex rhs) => new cmat2x3(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static cmat2x3 operator*(Complex lhs, cmat2x3 rhs) => new cmat2x3(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12);
}
}
| |
// ----------------------------------------------------------------------------------
//
// 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 Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Sql.Backup.Services;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Commands.Sql.Database.Model;
using System;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Sql.Backup.Cmdlet
{
[Cmdlet(VerbsData.Restore, "AzureRmSqlDatabase",
ConfirmImpact = ConfirmImpact.None)]
public class RestoreAzureRmSqlDatabase
: AzureSqlCmdletBase<Database.Model.AzureSqlDatabaseModel, AzureSqlDatabaseBackupAdapter>
{
private const string FromPointInTimeBackupSetName = "FromPointInTimeBackup";
private const string FromDeletedDatabaseBackupSetName = "FromDeletedDatabaseBackup";
private const string FromGeoBackupSetName = "FromGeoBackup";
private const string FromLongTermRetentionBackupSetName = "FromLongTermRetentionBackup";
/// <summary>
/// Gets or sets flag indicating a restore from a point-in-time backup.
/// </summary>
[Parameter(
ParameterSetName = FromPointInTimeBackupSetName,
Mandatory = true,
HelpMessage = "Restore from a point-in-time backup.")]
public SwitchParameter FromPointInTimeBackup { get; set; }
/// <summary>
/// Gets or sets flag indicating a restore of a deleted database.
/// </summary>
[Parameter(
ParameterSetName = FromDeletedDatabaseBackupSetName,
Mandatory = true,
HelpMessage = "Restore a deleted database.")]
public SwitchParameter FromDeletedDatabaseBackup { get; set; }
/// <summary>
/// Gets or sets flag indicating a geo-restore (recover) request
/// </summary>
[Parameter(
ParameterSetName = FromGeoBackupSetName,
Mandatory = true,
HelpMessage = "Restore from a geo backup.")]
public SwitchParameter FromGeoBackup { get; set; }
/// <summary>
/// Gets or sets flag indicating a restore from a long term retention backup
/// </summary>
[Parameter(
ParameterSetName = FromLongTermRetentionBackupSetName,
Mandatory = true,
HelpMessage = "Restore from a long term retention backup backup.")]
public SwitchParameter FromLongTermRetentionBackup { get; set; }
/// <summary>
/// Gets or sets the point in time to restore the database to
/// </summary>
[Parameter(
ParameterSetName = FromPointInTimeBackupSetName,
Mandatory = true,
HelpMessage = "The point in time to restore the database to.")]
[Parameter(
ParameterSetName = FromDeletedDatabaseBackupSetName,
Mandatory = false,
HelpMessage = "The point in time to restore the database to.")]
public DateTime PointInTime { get; set; }
/// <summary>
/// Gets or sets the deletion DateTime of the deleted database to restore.
/// </summary>
[Parameter(
ParameterSetName = FromDeletedDatabaseBackupSetName,
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The deletion DateTime of the deleted database to restore.")]
public DateTime DeletionDate { get; set; }
/// <summary>
/// The resource ID of the database to restore (deleted DB, geo backup DB, live DB, long term retention backup, etc.)
/// </summary>
[Alias("Id")]
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource ID of the database to restore.")]
public string ResourceId { get; set; }
/// <summary>
/// Gets or sets the name of the database server to use.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the Azure SQL Server to restore the database to.")]
[ValidateNotNullOrEmpty]
public string ServerName { get; set; }
/// <summary>
/// Gets or sets the name of the target database to restore to
/// </summary>
[Parameter(Mandatory = true,
HelpMessage = "The name of the target database to restore to.")]
public string TargetDatabaseName { get; set; }
/// <summary>
/// Gets or sets the target edition of the database to restore
/// </summary>
[Parameter(Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The database edition to use for the restored database.")]
public DatabaseEdition Edition { get; set; }
/// <summary>
/// Gets or sets the SLO of the database to restore
/// </summary>
[Parameter(Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The service level objective to use for the restored database.")]
public string ServiceObjectiveName { get; set; }
/// <summary>
/// Gets or sets the target elastic pool name
/// </summary>
[Parameter(Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the elastic pool into which the database should be restored.")]
public string ElasticPoolName { get; set; }
/// <summary>
/// Gets or sets whether or not to run this cmdlet in the background as a job
/// </summary>
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
/// <summary>
/// Initializes the adapter
/// </summary>
/// <param name="subscription">The subscription ID to operate on</param>
/// <returns></returns>
protected override AzureSqlDatabaseBackupAdapter InitModelAdapter(IAzureSubscription subscription)
{
return new AzureSqlDatabaseBackupAdapter(DefaultProfile.DefaultContext);
}
/// <summary>
/// Send the restore request
/// </summary>
/// <returns>The list of entities</returns>
protected override AzureSqlDatabaseModel GetEntity()
{
AzureSqlDatabaseModel model;
DateTime restorePointInTime = DateTime.MinValue;
string createMode;
string location = ModelAdapter.GetServerLocation(ResourceGroupName, ServerName);
switch (ParameterSetName)
{
case FromPointInTimeBackupSetName:
createMode = "PointInTimeRestore";
restorePointInTime = PointInTime;
break;
case FromDeletedDatabaseBackupSetName:
createMode = "Restore";
restorePointInTime = PointInTime == DateTime.MinValue ? DeletionDate : PointInTime;
break;
case FromGeoBackupSetName:
createMode = "Recovery";
break;
case FromLongTermRetentionBackupSetName:
createMode = "RestoreLongTermRetentionBackup";
break;
default:
throw new ArgumentException("No ParameterSet name");
}
model = new AzureSqlDatabaseModel()
{
Location = location,
ResourceGroupName = ResourceGroupName,
ServerName = ServerName,
DatabaseName = TargetDatabaseName,
Edition = Edition,
RequestedServiceObjectiveName = ServiceObjectiveName,
ElasticPoolName = ElasticPoolName,
CreateMode = createMode
};
return ModelAdapter.RestoreDatabase(this.ResourceGroupName, restorePointInTime, ResourceId, model);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>HotelPerformanceView</c> resource.</summary>
public sealed partial class HotelPerformanceViewName : gax::IResourceName, sys::IEquatable<HotelPerformanceViewName>
{
/// <summary>The possible contents of <see cref="HotelPerformanceViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>customers/{customer_id}/hotelPerformanceView</c>.</summary>
Customer = 1,
}
private static gax::PathTemplate s_customer = new gax::PathTemplate("customers/{customer_id}/hotelPerformanceView");
/// <summary>Creates a <see cref="HotelPerformanceViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="HotelPerformanceViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static HotelPerformanceViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new HotelPerformanceViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="HotelPerformanceViewName"/> with the pattern
/// <c>customers/{customer_id}/hotelPerformanceView</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="HotelPerformanceViewName"/> constructed from the provided ids.
/// </returns>
public static HotelPerformanceViewName FromCustomer(string customerId) =>
new HotelPerformanceViewName(ResourceNameType.Customer, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="HotelPerformanceViewName"/> with pattern
/// <c>customers/{customer_id}/hotelPerformanceView</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="HotelPerformanceViewName"/> with pattern
/// <c>customers/{customer_id}/hotelPerformanceView</c>.
/// </returns>
public static string Format(string customerId) => FormatCustomer(customerId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="HotelPerformanceViewName"/> with pattern
/// <c>customers/{customer_id}/hotelPerformanceView</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="HotelPerformanceViewName"/> with pattern
/// <c>customers/{customer_id}/hotelPerformanceView</c>.
/// </returns>
public static string FormatCustomer(string customerId) =>
s_customer.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="HotelPerformanceViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/hotelPerformanceView</c></description></item>
/// </list>
/// </remarks>
/// <param name="hotelPerformanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="HotelPerformanceViewName"/> if successful.</returns>
public static HotelPerformanceViewName Parse(string hotelPerformanceViewName) =>
Parse(hotelPerformanceViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="HotelPerformanceViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/hotelPerformanceView</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="hotelPerformanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="HotelPerformanceViewName"/> if successful.</returns>
public static HotelPerformanceViewName Parse(string hotelPerformanceViewName, bool allowUnparsed) =>
TryParse(hotelPerformanceViewName, allowUnparsed, out HotelPerformanceViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="HotelPerformanceViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/hotelPerformanceView</c></description></item>
/// </list>
/// </remarks>
/// <param name="hotelPerformanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="HotelPerformanceViewName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string hotelPerformanceViewName, out HotelPerformanceViewName result) =>
TryParse(hotelPerformanceViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="HotelPerformanceViewName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/hotelPerformanceView</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="hotelPerformanceViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="HotelPerformanceViewName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string hotelPerformanceViewName, bool allowUnparsed, out HotelPerformanceViewName result)
{
gax::GaxPreconditions.CheckNotNull(hotelPerformanceViewName, nameof(hotelPerformanceViewName));
gax::TemplatedResourceName resourceName;
if (s_customer.TryParseName(hotelPerformanceViewName, out resourceName))
{
result = FromCustomer(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(hotelPerformanceViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private HotelPerformanceViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="HotelPerformanceViewName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/hotelPerformanceView</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
public HotelPerformanceViewName(string customerId) : this(ResourceNameType.Customer, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Customer: return s_customer.Expand(CustomerId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as HotelPerformanceViewName);
/// <inheritdoc/>
public bool Equals(HotelPerformanceViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(HotelPerformanceViewName a, HotelPerformanceViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(HotelPerformanceViewName a, HotelPerformanceViewName b) => !(a == b);
}
public partial class HotelPerformanceView
{
/// <summary>
/// <see cref="HotelPerformanceViewName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal HotelPerformanceViewName ResourceNameAsHotelPerformanceViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : HotelPerformanceViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if NET20 || NET35
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
// using System.Diagnostics.Contracts;
namespace System {
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
internal interface ITuple {
string ToString(StringBuilder sb);
int GetHashCode(IEqualityComparer comparer);
int Size { get; }
}
public static class Tuple {
public static Tuple<T1> Create<T1>(T1 item1) {
return new Tuple<T1>(item1);
}
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) {
return new Tuple<T1, T2>(item1, item2);
}
public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) {
return new Tuple<T1, T2, T3>(item1, item2, item3);
}
public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) {
return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4);
}
public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {
return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
}
public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {
return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {
return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) {
return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8));
}
// From System.Web.Util.HashCodeCombiner
internal static int CombineHashCodes(int h1, int h2) {
return (((h1 << 5) + h1) ^ h2);
}
internal static int CombineHashCodes(int h1, int h2, int h3) {
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4) {
return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) {
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8));
}
}
[Serializable]
public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
public T1 Item1 { get { return m_Item1; } }
public Tuple(T1 item1) {
m_Item1 = item1;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1> objTuple = other as Tuple<T1>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1> objTuple = other as Tuple<T1>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
return comparer.Compare(m_Item1, objTuple.m_Item1);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
return comparer.GetHashCode(m_Item1);
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(")");
return sb.ToString();
}
int ITuple.Size {
get {
return 1;
}
}
}
[Serializable]
public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public Tuple(T1 item1, T2 item2) {
m_Item1 = item1;
m_Item2 = item2;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
return comparer.Compare(m_Item2, objTuple.m_Item2);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2));
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(")");
return sb.ToString();
}
int ITuple.Size {
get {
return 2;
}
}
}
[Serializable]
public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public Tuple(T1 item1, T2 item2, T3 item3) {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
return comparer.Compare(m_Item3, objTuple.m_Item3);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3));
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(")");
return sb.ToString();
}
int ITuple.Size {
get {
return 3;
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
return comparer.Compare(m_Item4, objTuple.m_Item4);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4));
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(")");
return sb.ToString();
}
int ITuple.Size {
get {
return 4;
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
return comparer.Compare(m_Item5, objTuple.m_Item5);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5));
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(")");
return sb.ToString();
}
int ITuple.Size {
get {
return 5;
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
private readonly T6 m_Item6;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public T6 Item6 { get { return m_Item6; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
m_Item6 = item6;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
c = comparer.Compare(m_Item5, objTuple.m_Item5);
if (c != 0) return c;
return comparer.Compare(m_Item6, objTuple.m_Item6);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6));
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(", ");
sb.Append(m_Item6);
sb.Append(")");
return sb.ToString();
}
int ITuple.Size {
get {
return 6;
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
private readonly T6 m_Item6;
private readonly T7 m_Item7;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public T6 Item6 { get { return m_Item6; } }
public T7 Item7 { get { return m_Item7; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) {
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
m_Item6 = item6;
m_Item7 = item7;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
c = comparer.Compare(m_Item5, objTuple.m_Item5);
if (c != 0) return c;
c = comparer.Compare(m_Item6, objTuple.m_Item6);
if (c != 0) return c;
return comparer.Compare(m_Item7, objTuple.m_Item7);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7));
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(", ");
sb.Append(m_Item6);
sb.Append(", ");
sb.Append(m_Item7);
sb.Append(")");
return sb.ToString();
}
int ITuple.Size {
get {
return 7;
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple {
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
private readonly T6 m_Item6;
private readonly T7 m_Item7;
private readonly TRest m_Rest;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public T6 Item6 { get { return m_Item6; } }
public T7 Item7 { get { return m_Item7; } }
public TRest Rest { get { return m_Rest; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) {
if (!(rest is ITuple)) {
throw new ArgumentException(string.Format("The last element of an eight element tuple must be a Tuple."));
}
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
m_Item6 = item6;
m_Item7 = item7;
m_Rest = rest;
}
public override Boolean Equals(Object obj) {
return ((IStructuralEquatable) this).Equals(obj, EqualityComparer<Object>.Default);;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
if (objTuple == null) {
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest);
}
Int32 IComparable.CompareTo(Object obj) {
return ((IStructuralComparable) this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
if (objTuple == null) {
throw new ArgumentException(string.Format("Argument must be of type {0}.", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
c = comparer.Compare(m_Item5, objTuple.m_Item5);
if (c != 0) return c;
c = comparer.Compare(m_Item6, objTuple.m_Item6);
if (c != 0) return c;
c = comparer.Compare(m_Item7, objTuple.m_Item7);
if (c != 0) return c;
return comparer.Compare(m_Rest, objTuple.m_Rest);
}
public override int GetHashCode() {
return ((IStructuralEquatable) this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
ITuple t = (ITuple) m_Rest;
if(t.Size >= 8) { return t.GetHashCode(comparer); }
// In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - t.Size;
switch(k) {
case 1:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 2:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 3:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 4:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 5:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 6:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 7:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
}
// Contract.Assert(false, "Missed all cases for computing Tuple hash code");
Debug.Assert(false, "Missed all cases for computing Tuple hash code");
return -1;
}
Int32 ITuple.GetHashCode(IEqualityComparer comparer) {
return ((IStructuralEquatable) this).GetHashCode(comparer);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITuple)this).ToString(sb);
}
string ITuple.ToString(StringBuilder sb) {
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(", ");
sb.Append(m_Item6);
sb.Append(", ");
sb.Append(m_Item7);
sb.Append(", ");
return ((ITuple)m_Rest).ToString(sb);
}
int ITuple.Size {
get {
return 7 + ((ITuple)m_Rest).Size;
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Reflection;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MaskLoadDouble()
{
var test = new SimpleBinaryOpTest__MaskLoadDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MaskLoadDouble
{
private struct TestStruct
{
public Vector256<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MaskLoadDouble testClass)
{
var result = Avx.MaskLoad((Double*)testClass._dataTable.inArray1Ptr, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(testClass._dataTable.inArray1Ptr, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__MaskLoadDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
}
public SimpleBinaryOpTest__MaskLoadDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.MaskLoad(
(Double*)_dataTable.inArray1Ptr,
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.MaskLoad(
(Double*)_dataTable.inArray1Ptr,
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.MaskLoad(
(Double*)_dataTable.inArray1Ptr,
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.MaskLoad), new Type[] { typeof(Double*), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*)),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.MaskLoad), new Type[] { typeof(Double*), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.MaskLoad), new Type[] { typeof(Double*), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.MaskLoad(
(Double*)_dataTable.inArray1Ptr,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = (Double*)_dataTable.inArray1Ptr;
var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.MaskLoad(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = (Double*)_dataTable.inArray1Ptr;
var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.MaskLoad(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = (Double*)_dataTable.inArray1Ptr;
var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.MaskLoad(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MaskLoadDouble();
var result = Avx.MaskLoad((Double*)_dataTable.inArray1Ptr, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.MaskLoad((Double*)_dataTable.inArray1Ptr, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.MaskLoad((Double*)_dataTable.inArray1Ptr, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(void* left, Vector256<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits((BitConverter.DoubleToInt64Bits(right[0]) < 0) ? left[0] : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits((BitConverter.DoubleToInt64Bits(right[i]) < 0) ? left[i] : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.MaskLoad)}<Double>(Double*, Vector256<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
using System.Runtime.InteropServices;
namespace Microsoft.Zelig.Runtime
{
using System;
internal static class SelfTest
{
[DllImport( "C" )]
public static unsafe extern int get_a_number( );
[DllImport( "C" )]
public static unsafe extern void violent_breakpoint( );
[DllImport( "C" )]
public static unsafe extern void break_and_watch( uint n );
//
// Zelig Self Test - Early bootstrap, no heap:
// integers, pointers and value types
//
[NoInline]
internal static unsafe void SELFTEST_ASSERT( bool expression )
{
if( !expression )
{
violent_breakpoint( );
}
}
//--//
//--//
//--//
#region basic math, and flow controls
private static int FibonacciInterative( int num )
{
int a = 0, b = 1, c = 0;
if( num == 1 ) return 1;
for( int i = 1; i < num; i++ )
{
c = a + b;
a = b;
b = c;
}
return c;
}
private static int FibonacciRecursive( int num )
{
if( num <= 1 )
{
return num;
}
return FibonacciRecursive( num - 1 ) + FibonacciRecursive( num - 2 );
}
private static void SelfTest__Test__Fibonacci( )
{
const int iter_0 = 0;
const int iter_1 = 1;
const int iter_2 = 1;
const int iter_3 = 2;
const int iter_4 = 3;
const int iter_5 = 5;
const int iter_6 = 8;
const int iter_7 = 13;
const int iter_8 = 21;
const int iter_9 = 34;
const int iter_10 = 55;
const int iter_11 = 89;
const int iter_12 = 144;
const int iter_13 = 233;
const int iter_14 = 377;
const int iter_15 = 610;
int iterations = 16;
int count = -1;
while( ++count < iterations )
{
int rec = FibonacciRecursive( count );
switch( count )
{
case 0:
SELFTEST_ASSERT( rec == iter_0 );
break;
case 1:
SELFTEST_ASSERT( rec == iter_1 );
break;
case 2:
SELFTEST_ASSERT( rec == iter_2 );
break;
case 3:
SELFTEST_ASSERT( rec == iter_3 );
break;
case 4:
SELFTEST_ASSERT( rec == iter_4 );
break;
case 5:
SELFTEST_ASSERT( rec == iter_5 );
break;
case 6:
SELFTEST_ASSERT( rec == iter_6 );
break;
case 7:
SELFTEST_ASSERT( rec == iter_7 );
break;
case 8:
SELFTEST_ASSERT( rec == iter_8 );
break;
case 9:
SELFTEST_ASSERT( rec == iter_9 );
break;
case 10:
SELFTEST_ASSERT( rec == iter_10 );
break;
case 11:
SELFTEST_ASSERT( rec == iter_11 );
break;
case 12:
SELFTEST_ASSERT( rec == iter_12 );
break;
case 13:
SELFTEST_ASSERT( rec == iter_13 );
break;
case 14:
SELFTEST_ASSERT( rec == iter_14 );
break;
case 15:
SELFTEST_ASSERT( rec == iter_15 );
break;
default:
SELFTEST_ASSERT( false );
break;
}
}
}
private static void SelfTest__Test__CallsAndControls( )
{
const int iterations = 25;
int count = 0;
while( count++ < iterations )
{
int rec = FibonacciRecursive( count );
int ite = FibonacciInterative( count );
SELFTEST_ASSERT( ite == rec );
}
}
#endregion
#region native types, basic casts
private static void SelfTest__Test__NativeTypes_Casts()
{
const int mask = ( 1 << 16 ) - 1;
// get a number smaller than 16 bits
int seed = get_a_number() % mask;
SELFTEST_ASSERT( seed < mask );
int i = seed << 16;
// downcast
short s = ( short )i;
SELFTEST_ASSERT( s == 0 );
}
#endregion
#region Value Types, basic copy semantic
struct ToCopy
{
public int i;
public char c;
}
private static void SelfTest__Test__ValueTypesCopy_1()
{
//
// Vanilla assignment between value types
//
ToCopy a;
a.i = 1;
a.c = 'a';
SELFTEST_ASSERT( a.i == 1 && a.c == 'a' );
ToCopy b;
b.i = 2;
b.c = 'b';
SELFTEST_ASSERT( b.i == 2 && b.c == 'b' );
ToCopy aa = a;
a = b;
// new values
SELFTEST_ASSERT( a.i == 2 && a.c == 'b' );
// old values
SELFTEST_ASSERT( aa.i == 1 && aa.c == 'a' );
}
private static void SelfTest__Test__ValueTypesCopy_2()
{
//
// Vanilla assignment between value types
//
ToCopy a;
a.i = 1;
a.c = 'a';
SELFTEST_ASSERT( a.i == 1 && a.c == 'a' );
ToCopy aa = a;
PassByValue( a );
// new values
SELFTEST_ASSERT( a.i == 1 && a.c == 'a' );
// old values
SELFTEST_ASSERT( aa.i == 1 && aa.c == 'a' );
// cross check values
SELFTEST_ASSERT( aa.i == a.i && aa.c == a.c );
}
private static void PassByValue( ToCopy byValue )
{
byValue.i = 2;
byValue.c = 'b';
}
private static void SelfTest__Test__ValueTypesCopy_3()
{
//
// Vanilla assignment between value types
//
ToCopy a;
a.i = 1;
a.c = 'a';
SELFTEST_ASSERT( a.i == 1 && a.c == 'a' );
ToCopy aa = a;
PassByRef( ref a );
// new values
SELFTEST_ASSERT( a.i == 2 && a.c == 'b' );
// old values
SELFTEST_ASSERT( aa.i == 1 && aa.c == 'a' );
// cross check values
SELFTEST_ASSERT( aa.i + 1 == a.i );
}
private static void PassByRef( ref ToCopy byValue )
{
byValue.i = 2;
byValue.c = 'b';
}
private static void SelfTest__Test__ValueTypesCopy_4()
{
//
// Vanilla assignment between value types
//
ToCopy a;
a.i = 1;
a.c = 'a';
SELFTEST_ASSERT( a.i == 1 && a.c == 'a' );
ToCopy aa = a;
a = ReturnByValue();
// new values
SELFTEST_ASSERT( a.i == 2 && a.c == 'b' );
// old values
SELFTEST_ASSERT( aa.i == 1 && aa.c == 'a' );
}
private static ToCopy ReturnByValue( )
{
ToCopy b;
b.i = 2;
b.c = 'b';
return b;
}
#endregion
//--//
//--//
//--//
internal static void SelfTest__Bootstrap( )
{
//
// Basic math and flow controls
//
SelfTest__Test__Fibonacci( );
SelfTest__Test__CallsAndControls( );
//
// Native types, basic casts
//
SelfTest__Test__NativeTypes_Casts( );
//
// Value Types, basic copy semantic
//
SelfTest__Test__ValueTypesCopy_1( );
SelfTest__Test__ValueTypesCopy_2( );
SelfTest__Test__ValueTypesCopy_3( );
//SelfTest__Test__ValueTypesCopy_4(); KNOWN FAILURE
//
// pointers...
//
SelfTest__Test__Pointers_Conversions_1( );
SelfTest__Test__Pointers_Conversions_2( );
SelfTest__Test__Pointers_Conversions_3( );
SelfTest__Test__Pointers_Conversions_4( );
SelfTest__Test__RawPointers_Arithmetic_Pointer_1( );
SelfTest__Test__RawPointers_Arithmetic_Pointer_2( );
SelfTest__Test__RawPointers_Arithmetic_Values_1 ( );
SelfTest__Test__RawPointers_Arithmetic_Values_2 ( );
SelfTest__Test__Pointers_PassByValue( );
SelfTest__Test__Pointers_PassByRef( );
//--//
//--// ...value types...
//--//
SelfTest__Test__ValueTypes_PassByValue( );
SelfTest__Test__ValueTypes_PassByRef( );
//
// ...else...
//
SelfTest__Test__Integers_Conversions( );
SelfTest__Test__Integers_PassByValue( );
SelfTest__Test__Integers_PassByRef( );
SelfTest__Test__Integers_BoxUnbox( );
SelfTest__Test__Integers_BoxUnboxInverted( );
//Trap end of tests
SELFTEST_ASSERT( false );
}
//--//
//--//
//--//
#region pointers basic
private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Pointer_1( )
{
//
// Pointer arithmetic, 1 value
//
int pointed = 42;
int* a = &pointed;
int* aa = &pointed;
a += 1;
SELFTEST_ASSERT( a == aa + 1 );
}
private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Pointer_2( )
{
//
// Pointer arithmetic, 2 values
//
int pointed = 42;
int* a = &pointed;
int* b = &pointed;
int* aa = &pointed;
int* bb = &pointed;
a += 1;
b += 2;
SELFTEST_ASSERT( a == aa + 1 );
SELFTEST_ASSERT( b == bb + 2 );
}
private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Values_1( )
{
//
// Pointer arithmetic, 2 values
//
int pointed = 42;
/*const*/ int const_pointed = 42;
int* a = &pointed;
int* aa = &const_pointed;
*a += 1;
SELFTEST_ASSERT( *a == *aa + 1 );
}
private static unsafe void SelfTest__Test__RawPointers_Arithmetic_Values_2( )
{
//
// Pointer arithmetic, 2 values
//
int pointed = 42;
/*const*/ int const_pointed = 42;
int* a = &pointed;
int* b = &pointed;
int* aa = &const_pointed;
int* bb = &const_pointed;
*a += 1;
*b += 2;
SELFTEST_ASSERT( *a == *aa + 3 );
SELFTEST_ASSERT( *b == *bb + 3 );
}
private static void SelfTest__Test__Pointers_Conversions_1( )
{
IntPtr a = ( IntPtr )0x10004000;
int aa = a.ToInt32( );
SELFTEST_ASSERT( aa == 0x10004000 );
}
private static void SelfTest__Test__Pointers_Conversions_2( )
{
IntPtr a = ( IntPtr )0x10004000;
IntPtr b = ( IntPtr )0x10004000;
int aa = a.ToInt32( );
int bb = b.ToInt32( );
SELFTEST_ASSERT( a == b );
SELFTEST_ASSERT( aa == bb );
}
private static void SelfTest__Test__Pointers_Conversions_3( )
{
UIntPtr a = ( UIntPtr )0x10004000;
uint aa = a.ToUInt32( );
SELFTEST_ASSERT( aa == 0x10004000 );
}
private static void SelfTest__Test__Pointers_Conversions_4( )
{
UIntPtr a = ( UIntPtr )0x10004000;
UIntPtr b = ( UIntPtr )0x10004000;
uint aa = a.ToUInt32( );
uint bb = b.ToUInt32( );
SELFTEST_ASSERT( a == b );
SELFTEST_ASSERT( aa == bb );
}
private static void SelfTest__Test__Pointers_PassByValue( )
{
IntPtr a = ( IntPtr )10;
IntPtr b = ( IntPtr )10;
PassByValue( a, b );
SELFTEST_ASSERT( a.ToInt32( ) == 10 );
SELFTEST_ASSERT( b.ToInt32( ) == 10 );
SELFTEST_ASSERT( ( a.ToInt32( ) == b.ToInt32( ) ) );
SELFTEST_ASSERT( ( a.ToInt32( ) + b.ToInt32( ) ) == 20);
}
private static void PassByValue( IntPtr a, IntPtr b )
{
int val = 5;
a = ( IntPtr )val;
b = ( IntPtr )val;
}
private static void SelfTest__Test__Pointers_PassByRef( )
{
IntPtr a = ( IntPtr )10;
IntPtr b = ( IntPtr )11;
PassByRef( ref a, ref b );
SELFTEST_ASSERT( a.ToInt32( ) == 5 );
SELFTEST_ASSERT( b.ToInt32( ) == 5 );
SELFTEST_ASSERT( ( a.ToInt32( ) == b.ToInt32( ) ) );
SELFTEST_ASSERT( ( a.ToInt32( ) + b.ToInt32( ) ) == 10);
}
private static void PassByRef( ref IntPtr a, ref IntPtr b )
{
int val = 5;
a = ( IntPtr )val;
b = ( IntPtr )val;
}
#endregion pointers basic
//--//
//--//
//--//
#region pointers advanced
private struct Foo
{
public IntPtr barSigned;
public int dummyNativeInt;
public byte dummy;
public Int32 dummyInt;
public UIntPtr barUnsigned;
}
private static void SelfTest__Test__ValueType_Pointer_ByteDummy( )
{
byte b = ( byte )0xFF;
Foo foo1;
foo1.barSigned = ( IntPtr )10;
foo1.dummyNativeInt = 7;
foo1.dummy = b;
foo1.dummyInt = 15;
foo1.barUnsigned = ( UIntPtr )20;
Foo foo2;
foo2.barSigned = ( IntPtr )5;
foo2.dummyNativeInt = 7;
foo2.dummy = b;
foo2.dummyInt = 15;
foo2.barUnsigned = ( UIntPtr )15;
SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 );
SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 );
SELFTEST_ASSERT( foo1.dummy == foo2.dummy );
SELFTEST_ASSERT( foo1.dummyInt == foo2.dummyInt );
SELFTEST_ASSERT( foo1.dummyNativeInt == foo2.dummyNativeInt );
PassByRef( ref foo1, ref foo2 );
SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 );
SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 );
SELFTEST_ASSERT( foo1.dummy == foo2.dummy );
SELFTEST_ASSERT( foo1.dummyInt == foo2.dummyInt + 5 );
SELFTEST_ASSERT( foo1.dummyNativeInt == foo2.dummyNativeInt + 5 );
}
private static void PassByRef( ref Foo foo1, ref Foo foo2 )
{
foo1.barSigned = ( IntPtr )50;
foo1.barUnsigned = ( UIntPtr )60;
foo1.dummyInt = 65;
foo1.dummyNativeInt = ( Int32 )75;
foo2.barSigned = ( IntPtr )45;
foo2.barUnsigned = ( UIntPtr )55;
foo2.dummyInt = 60;
foo2.dummyNativeInt = ( Int32 )70;
}
private unsafe struct FooBytePointer
{
public IntPtr barSigned;
public byte* dummy;
public UIntPtr barUnsigned;
}
private static unsafe void SelfTest__Test__ValueType_Pointer_BytePointerDummy( )
{
byte b = ( byte )0xFF;
FooBytePointer foo1;
foo1.barSigned = ( IntPtr )10;
foo1.dummy = &b;
foo1.barUnsigned = ( UIntPtr )20;
FooBytePointer foo2;
foo2.barSigned = ( IntPtr )5;
foo2.dummy = &b;
foo2.barUnsigned = ( UIntPtr )15;
SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 );
SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 );
SELFTEST_ASSERT( foo1.dummy == foo2.dummy );
PassByRef( ref foo1, ref foo2 );
SELFTEST_ASSERT( ( ( int )foo1.barSigned ) == ( ( int )foo2.barSigned ) + 5 );
SELFTEST_ASSERT( ( ( int )foo1.barUnsigned ) == ( ( int )foo2.barUnsigned ) + 5 );
SELFTEST_ASSERT( foo1.dummy == foo2.dummy );
}
private static void PassByRef( ref FooBytePointer foo1, ref FooBytePointer foo2 )
{
foo1.barSigned = ( IntPtr )50;
foo1.barUnsigned = ( UIntPtr )60;
foo2.barSigned = ( IntPtr )45;
foo2.barUnsigned = ( UIntPtr )55;
}
#endregion pointers advanced
//--//
//--//
//--//
#region value types advanced
private struct Mixed
{
public int ii;
public byte bb;
public long ll;
public static Mixed operator +( Mixed a, Mixed b )
{
Mixed c;
c.ii = a.ii + b.ii;
c.bb = ( byte )( a.bb + b.bb );
c.ll = a.ll + b.ll;
return c;
}
}
private static void SelfTest__Test__ValueTypes_PassByValue( )
{
Mixed a;
a.ii = 5;
a.bb = 10;
a.ll = 20;
const int delta = 1;
Mixed b;
b.ii = 5 + delta;
b.bb = 10 + delta;
b.ll = 5 + delta;
Mixed c = PassByValue( a, b );
SELFTEST_ASSERT( c.ii == a.ii + b.ii );
SELFTEST_ASSERT( c.bb == a.bb + b.bb );
SELFTEST_ASSERT( c.ll == a.ll + b.ll );
}
private static Mixed PassByValue( Mixed a, Mixed b )
{
return a + b;
}
private static void SelfTest__Test__ValueTypes_PassByRef( )
{
Mixed a;
a.ii = 5;
a.bb = 10;
a.ll = 20;
const int delta = 1;
Mixed b;
b.ii = 5 + delta;
b.bb = 10 + delta;
b.ll = 5 + delta;
Mixed aa = a;
Mixed bb = b;
Mixed c = PassByRef( ref a, ref b );
Mixed d = aa + bb;
SELFTEST_ASSERT( c.ii == a.ii + b.ii );
SELFTEST_ASSERT( c.bb == a.bb + b.bb );
SELFTEST_ASSERT( c.ll == a.ll + b.ll );
SELFTEST_ASSERT( d.ii == aa.ii + bb.ii );
SELFTEST_ASSERT( d.bb == aa.bb + bb.bb );
SELFTEST_ASSERT( d.ll == aa.ll + bb.ll );
}
private static Mixed PassByRef( ref Mixed a, ref Mixed b )
{
a += b;
b += a;
return a + b;
}
#endregion value types advanced
//--//
//--//
//--//
#region integers
private static void SelfTest__Test__Integers_Conversions( )
{
#region up
#region signed
//
// up - int to long
//
int a3 = 10;
long b3 = a3;
SELFTEST_ASSERT( a3 == b3 );
//
// up - short to int
//
short a4 = 10;
int b4 = a4;
SELFTEST_ASSERT( a4 == b4 );
//
// up - sbyte to int
//
sbyte a5 = 10;
int b5 = a5;
SELFTEST_ASSERT( a5 == b5 );
#endregion signed
#region unsigned
//
// up - uint to ulong
//
uint a31 = 10;
ulong b31 = a31;
SELFTEST_ASSERT( a31 == b31 );
//
// up - ushort to uint
//
ushort a41 = 10;
uint b41 = a41;
SELFTEST_ASSERT( a41 == b41 );
//
// up - byte to uint
//
byte a51 = 10;
uint b51 = a51;
SELFTEST_ASSERT( a51 == b51 );
#endregion unsigned
#endregion up
#region down
#region signed
//
// down - long to int
//
long a = 10;
int b = ( int )a;
SELFTEST_ASSERT( a == b );
//
// down - int to short
//
int a0 = 10;
short b0 = ( short )a;
SELFTEST_ASSERT( a0 == b0 );
//
// down - int to byte
//
int a1 = 10;
byte b1 = ( byte )a1;
SELFTEST_ASSERT( a1 == b1 );
#endregion signed
#region unsigned
//
// down - ulong to uint
//
ulong a6 = 10;
uint b6 = ( uint )a6;
SELFTEST_ASSERT( a6 == b6 );
//
// down - uint to ushort
//
uint a7 = 10;
ushort b7 = ( ushort )a7;
SELFTEST_ASSERT( a7 == b7 );
//
// down - uint to byte
//
uint a8 = 10;
byte b8 = ( byte )a8;
SELFTEST_ASSERT( a8 == b8 );
#endregion unsigned
#endregion down
}
//--//
//--//
//--//
private static void SelfTest__Test__Integers_PassByValue( )
{
int a = get_a_number();
int b = get_a_number();
SELFTEST_ASSERT( a + b == PassByValue( a, b ) );
}
private static int PassByValue( int a, int b )
{
return a + b;
}
private static void SelfTest__Test__Integers_PassByRef( )
{
int a = get_a_number();
int b = get_a_number();
int c = a + b;
PassByRef( ref a, ref b );
SELFTEST_ASSERT( c + 3 == a + b );
}
private static void PassByRef( ref int a, ref int b )
{
a += 1;
b += 2;
}
//--//
//--//
//--//
private static void SelfTest__Test__Integers_BoxUnbox( )
{
int a = 20;
int b = 22;
PassByRef( ref a, ref b ); SELFTEST_ASSERT( 45 == a + b );
PassByValue( a, b ); SELFTEST_ASSERT( 45 == a + b );
PassByRef( ref a, ref b ); SELFTEST_ASSERT( 48 == a + b );
}
private static void SelfTest__Test__Integers_BoxUnboxInverted( )
{
int a = 20;
int b = 22;
PassByValue( a, b ); SELFTEST_ASSERT( 42 == a + b );
PassByRef( ref a, ref b ); SELFTEST_ASSERT( 45 == a + b );
PassByValue( a, b ); SELFTEST_ASSERT( 45 == a + b );
}
#endregion integers
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InfiniteCity.Control;
using InfiniteCity.Control.AI;
using InfiniteCity.Control.Tiles;
using InfiniteCity.Model;
using InfiniteCity.Model.Enums;
using InfiniteCity.Model.Exceptions;
using InfiniteCity.Model.Interfaces;
using InfiniteCity.View;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace InfiniteCity
{
/// <summary>
/// This is the main type for your game
/// </summary>
internal sealed class Game : Microsoft.Xna.Framework.Game
{
private readonly GraphicsDeviceManager _graphics;
private SpriteBatch _handSpriteBatch;
private SpriteBatch _boardSpriteBatch;
private SpriteBatch _scoreSpriteBatch;
private SpriteBatch _endGameSpriteBatch;
private SpriteBatch _menuSpriteBatch;
private SpriteBatch _tooltipSpriteBatch;
private int _tooltipOffset;
private Controller _controller;
private SpriteFont _seguiUI;
/// <summary>
/// View classes should only access controller function defined in ISelectionManager
/// </summary>
private ISelectionManager _selectionManager;
private KeyboardState _oldKeyboardState;
private HandViewLayer _handViewLayer;
private HandViewLayer _customViewLayer;
private BoardViewLayer _boardViewLayer;
private MenuViewLayer _menuViewLayer;
private Camera _camera;
private Texture2D _line;
private Texture2D _white;
private Texture2D _gray;
private Tile[] _currentHand;
private Tile[] _playerSelection;
private Point _selectionPoint;
private Boolean _moveCamera;
private Color _oldColor;
private Boolean _displayHelp;
private Boolean _endGame;
private Menu _menu;
private Screen _currentScreen;
private List<Tuple<string, int>> _aiParams;
/// <summary>
/// Creates the game
/// </summary>
public Game()
{
_graphics = new GraphicsDeviceManager(this) {PreferredBackBufferWidth = 1280, PreferredBackBufferHeight = 720};
//Use 720p resolution for now.
//May change later
Content.RootDirectory = "Content";
}
/// <summary>
/// Creates the players' source of inputs
/// </summary>
/// <param name = "inputParams">A list of Tuples to create the player source of inputs</param>
public static Player[] InitPlayerInputs(List<Tuple<string, int>> inputParams)
{
var players = new List<Player>();
int playerIndex = 0;
for (int inputParamsIndex = 0; inputParamsIndex<inputParams.Count(); inputParamsIndex++)
if (inputParams[inputParamsIndex].Item1 != "Disabled")
{
players.Add(new Player(inputParams[inputParamsIndex].Item1+(inputParamsIndex+1),
Controller.PlayerColors[inputParamsIndex],
(ColorName)inputParamsIndex));
if (inputParams[inputParamsIndex].Item1 != "Human")
{
int index = inputParamsIndex;
Func<int, AI> inputSource =
(from ai in AI.Opponents where ai.Key == inputParams[index].Item1 select ai.Value).ElementAt(0);
players[playerIndex].Input = inputSource(inputParams[inputParamsIndex].Item2);
}
players[playerIndex].Name = inputParams[inputParamsIndex].Item1+" "+(inputParamsIndex+1);
playerIndex++;
}
return players.ToArray();
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name = "gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
switch (_currentScreen)
{
case Screen.Menu:
_menuSpriteBatch.Begin();
_menuViewLayer.Draw(_menuSpriteBatch);
_menuSpriteBatch.End();
break;
default:
DrawGameView(gameTime);
break;
}
base.Draw(gameTime);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
_currentScreen = Screen.Menu;
IsMouseVisible = true;
_camera = new Camera(_graphics);
// Why is the board starting at (1600,1100)? No one knows....
_camera.PointTo(new Vector2(1600, 1100));
_controller = Controller.DefaultInstance;
_selectionManager = _controller;
_oldKeyboardState = Keyboard.GetState();
_boardViewLayer = new BoardViewLayer(_graphics, _controller);
_handViewLayer = new HandViewLayer(_graphics, _controller) {IsCustom = false};
_customViewLayer = new HandViewLayer(_graphics, _controller) {IsCustom = true};
_menu = new Menu();
// a blank tile for each player, colors get added later
_playerSelection = new Tile[_controller.Players.Count()];
for (int i = 0; i<_controller.Players.Count(); i++)
_playerSelection[i] = new Blank {Owner = _controller.Players.ElementAt(i), Space = new Space()};
_selectionPoint = new Point(0, 0);
_moveCamera = true;
_oldColor = Color.Wheat;
_displayHelp = false;
_endGame = false;
_aiParams = null;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
_seguiUI = Content.Load<SpriteFont>("Fonts\\SeguiUI");
_menuViewLayer = new MenuViewLayer(_menu, _seguiUI);
// textures for tiles
Crossroads.TileTexture = Content.Load<Texture2D>("Tiles\\PlazaTile");
Grove.TileTexture = Content.Load<Texture2D>("Tiles\\Complete\\Woodlands");
Quarry.TileTexture = Content.Load<Texture2D>("Tiles\\Complete\\Tile_Quarry");
Graveyard.TileTexture = Content.Load<Texture2D>("Tiles\\MausoleumTile");
Market.TileTexture = Content.Load<Texture2D>("Tiles\\ShoppingComplexTile");
Village.TileTexture = Content.Load<Texture2D>("Tiles\\HousingTile");
Cathedral.TileTexture = Content.Load<Texture2D>("Tiles\\LibraryTile");
Plantation.TileTexture = Content.Load<Texture2D>("Tiles\\FactoryTile");
Plague.TileTexture = Content.Load<Texture2D>("Tiles\\SecurityGuardpostTile");
Militia.TileTexture = Content.Load<Texture2D>("Tiles\\EmbassyTile");
Amphitheater.TileTexture = Content.Load<Texture2D>("Tiles\\PoliceHQTile");
ReflectingPond.TileTexture = Content.Load<Texture2D>("Tiles\\PostOfficeTile");
AbandonedMine.TileTexture = Content.Load<Texture2D>("Tiles\\TransitStationTile");
Wasteland.TileTexture = Content.Load<Texture2D>("Tiles\\Complete\\Tile_Wasteland");
Spring.TileTexture = Content.Load<Texture2D>("Tiles\\PortTile");
ThievesGuild.TileTexture = Content.Load<Texture2D>("Tiles\\TempleTile");
Keep.TileTexture = Content.Load<Texture2D>("Tiles\\Complete\\Tile_Keep");
Sanctum.TileTexture = Content.Load<Texture2D>("Tiles\\PowerStationTile");
Treasury.TileTexture = Content.Load<Texture2D>("Tiles\\Complete\\Tile_Treasury");
Tavern.TileTexture = Content.Load<Texture2D>("Tiles\\StadiumTile");
Blank.TileTexture = Content.Load<Texture2D>("Tiles\\BaseTile");
// load the arrows for the hand view layer
_handViewLayer.LeftArrow = Content.Load<Texture2D>("LeftArrow");
_handViewLayer.RightArrow = Content.Load<Texture2D>("RightArrow");
_handViewLayer.Glow = Content.Load<Texture2D>("Tiles\\BaseTileGlow");
_customViewLayer.Glow = Content.Load<Texture2D>("Tiles\\BaseTileGlow");
_customViewLayer.LeftArrow = Content.Load<Texture2D>("LeftArrow");
_customViewLayer.RightArrow = Content.Load<Texture2D>("RightArrow");
// texture for the selector
_boardViewLayer.Blank = Content.Load<Texture2D>("Tiles\\BaseTileGlow");
_boardViewLayer.Holy = Content.Load<Texture2D>("Tiles\\holy");
// texture for playable spaces
_boardViewLayer.Possible = Content.Load<Texture2D>("Tiles\\good");
// textures for ownership, pass them to the boardViewLayer
_boardViewLayer.RedOwner = Content.Load<Texture2D>("Tiles\\Ownership\\BaseTerritoryColorRed");
_boardViewLayer.BlueOwner = Content.Load<Texture2D>("Tiles\\Ownership\\BaseTerritoryColorBlue");
_boardViewLayer.YellowOwner = Content.Load<Texture2D>("Tiles\\Ownership\\BaseTerritoryColorYellow");
_boardViewLayer.GreenOwner = Content.Load<Texture2D>("Tiles\\Ownership\\BaseTerritoryColorGreen");
_boardViewLayer.TanOwner = Content.Load<Texture2D>("Tiles\\Ownership\\BaseTerritoryColorTan");
_boardViewLayer.SilverOwner = Content.Load<Texture2D>("Tiles\\Ownership\\BaseTerritoryColorSilver");
_boardViewLayer.FlippedTile = Content.Load<Texture2D>("Tiles\\FlippedTile");
// textures for tile worth in board display
_boardViewLayer.Worth1 = Content.Load<Texture2D>("Tiles\\Worth1");
_boardViewLayer.Worth2 = Content.Load<Texture2D>("Tiles\\Worth2");
_boardViewLayer.Worth3 = Content.Load<Texture2D>("Tiles\\Worth3");
_boardViewLayer.Worth4 = Content.Load<Texture2D>("Tiles\\Worth4");
_boardViewLayer.Worth5 = Content.Load<Texture2D>("Tiles\\Worth5");
// textures for tile worth in hand display
_handViewLayer.Worth1 = _boardViewLayer.Worth1;
_handViewLayer.Worth2 = _boardViewLayer.Worth2;
_handViewLayer.Worth3 = _boardViewLayer.Worth3;
_handViewLayer.Worth4 = _boardViewLayer.Worth4;
_handViewLayer.Worth5 = _boardViewLayer.Worth5;
_customViewLayer.Worth1 = _boardViewLayer.Worth1;
_customViewLayer.Worth2 = _boardViewLayer.Worth2;
_customViewLayer.Worth3 = _boardViewLayer.Worth3;
_customViewLayer.Worth4 = _boardViewLayer.Worth4;
_customViewLayer.Worth5 = _boardViewLayer.Worth5;
_customViewLayer.Cross = Content.Load<Texture2D>("Tiles\\cross");
// Create a new SpriteBatch, which can be used to draw textures.
_handSpriteBatch = new SpriteBatch(GraphicsDevice);
_boardSpriteBatch = new SpriteBatch(GraphicsDevice);
_scoreSpriteBatch = new SpriteBatch(GraphicsDevice);
_tooltipSpriteBatch = new SpriteBatch(GraphicsDevice);
_endGameSpriteBatch = new SpriteBatch(GraphicsDevice);
_menuSpriteBatch = new SpriteBatch(GraphicsDevice);
//for drawing boarder between hand and board
_line = Content.Load<Texture2D>("black");
_white = Content.Load<Texture2D>("white");
_gray = Content.Load<Texture2D>("gray");
Content.Load<Texture2D>("board");
MediaPlayer.Play(Content.Load<Song>("477450_Our-Ancestors-Menu-")); // http://www.newgrounds.com/audio/listen/477450
MediaPlayer.IsRepeating = true;
MediaPlayer.IsMuted = true;
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
Content.Unload();
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name = "gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
KeyboardState newKeyboardState = Keyboard.GetState();
switch (_currentScreen)
{
case Screen.Menu:
UpdateMenuScreen(newKeyboardState);
break;
default:
UpdateGameScreen(newKeyboardState);
break;
}
_oldKeyboardState = newKeyboardState;
base.Update(gameTime);
}
private void CheckEsc(KeyboardState newKeyboardState)
{
if (newKeyboardState.IsKeyDown(Keys.Escape))
Exit();
}
private void CheckMute(KeyboardState newKeyboardState)
{
Keys[] oldStateKeys = _oldKeyboardState.GetPressedKeys();
// Toggle for media player
if (newKeyboardState.IsKeyDown(Keys.M) && !oldStateKeys.Contains(Keys.M))
MediaPlayer.IsMuted = !MediaPlayer.IsMuted;
}
private void DrawBorder()
{
var outerTileDrawRectangle = new Rectangle(10,
_graphics.PreferredBackBufferHeight*4/5-10,
_graphics.PreferredBackBufferWidth-20,
_graphics.PreferredBackBufferHeight-5-_graphics.PreferredBackBufferHeight*4/5);
var innerTileDrawRectangle = new Rectangle(20,
_graphics.PreferredBackBufferHeight*4/5,
_graphics.PreferredBackBufferWidth-40,
_graphics.PreferredBackBufferHeight-25-_graphics.PreferredBackBufferHeight*4/5);
_handSpriteBatch.Draw(_line, outerTileDrawRectangle, Color.White);
_handSpriteBatch.Draw(_white, innerTileDrawRectangle, Color.White);
}
private void DrawGameView(GameTime gameTime)
{
if (_controller.ActivePlayer.Input == null)
_oldColor = _controller.ActivePlayer.Color;
GraphicsDevice.Clear(_oldColor);
// draw the tiles on the board
_boardSpriteBatch.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.LinearClamp,
DepthStencilState.None,
RasterizerState.CullCounterClockwise,
null,
_camera.GetTransformation());
_boardViewLayer.Draw(_boardSpriteBatch, _selectionPoint);
_boardSpriteBatch.End();
if (_controller.ActivePlayer.Input == null)
DrawHumanView();
if (_endGame)
{
_endGameSpriteBatch.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.LinearClamp,
DepthStencilState.None,
RasterizerState.CullCounterClockwise,
null,
Matrix.Identity);
_endGameSpriteBatch.DrawString(_seguiUI,
_selectionManager.Message,
new Vector2(
_graphics.PreferredBackBufferWidth/2f-
_seguiUI.MeasureString(_selectionManager.Message).X/2,
0),
Color.Black);
_endGameSpriteBatch.End();
}
int offset = 2;
// Draw the scoreboard and scores
_scoreSpriteBatch.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.LinearClamp,
DepthStencilState.None,
RasterizerState.CullCounterClockwise,
null,
Matrix.Identity);
_scoreSpriteBatch.Draw(_white,
new Rectangle(_graphics.PreferredBackBufferWidth*13/16,
0,
_graphics.PreferredBackBufferWidth*3/16,
18*(_controller.Players.ToArray().Length+3)),
Color.Black);
_scoreSpriteBatch.DrawString(_seguiUI, "SCOREBOARD", new Vector2(_graphics.PreferredBackBufferWidth*13/16+5, 0), Color.Gold);
_scoreSpriteBatch.DrawString(_seguiUI,
string.Format("{0,8}:{1,4}:{2,4}", "Name", "Pts", "Tkns"),
new Vector2(_graphics.PreferredBackBufferWidth*13/16+5, 15),
Color.White);
int winning = _controller.Score.Max(kvp => kvp.Value);
foreach (Player p in _controller.Players)
{
_scoreSpriteBatch.DrawString(_seguiUI,
string.Format("{0,8}:{1,4}:{3,4}{2}",
p.Name,
_controller.Score[p],
_controller.Score[p] == winning && winning != 0 ? "!" : string.Empty,
p.Tokens),
new Vector2(_graphics.PreferredBackBufferWidth*13/16+5, 15*offset),
p.Color);
offset++;
}
_scoreSpriteBatch.DrawString(_seguiUI,
string.Format("Sanctums:{0,4}", _controller.Board.Tiles.Where(t => t.Building == "Sanctum").Count()),
new Vector2(_graphics.PreferredBackBufferWidth*13/16+5, 15*offset),
Color.Gold);
_scoreSpriteBatch.End();
//Display tooltips for tiles
if (!_displayHelp)
return;
_tooltipSpriteBatch.Begin();
_tooltipOffset -= (int)(gameTime.ElapsedGameTime.Milliseconds/10f);
_tooltipSpriteBatch.Draw(_gray,
new Rectangle(0, _graphics.PreferredBackBufferHeight*4/5-50, _graphics.PreferredBackBufferWidth, 40),
new Color(128F, 128F, 128F, 128F));
int tooltipYPosition = _graphics.PreferredBackBufferHeight*4/5-40;
if (!_moveCamera)
{
Tile selectedTile = _controller.Board[_selectionPoint].Tile;
if (selectedTile != null)
// don't display tool tips for unflipped tiles, that's cheating
if (!selectedTile.IsFlipped)
{
int nextMarqueeTextPosition = 0;
_tooltipOffset %= (int)_seguiUI.MeasureString("Tile is flipped over"+" - ").X;
while (nextMarqueeTextPosition+_tooltipOffset<_graphics.PreferredBackBufferWidth)
{
_tooltipSpriteBatch.DrawString(_seguiUI,
"Tile is flipped over"+" - ",
new Vector2(nextMarqueeTextPosition+_tooltipOffset, tooltipYPosition),
Color.White);
nextMarqueeTextPosition += (int)_seguiUI.MeasureString("Tile is flipped over"+" - ").X;
}
}
else
{
int nextMarqueeTextPosition = 0;
_tooltipOffset %= (int)_seguiUI.MeasureString(selectedTile.Building+" : "+selectedTile.Rules+" - ").X;
while (nextMarqueeTextPosition+_tooltipOffset<_graphics.PreferredBackBufferWidth)
{
_tooltipSpriteBatch.DrawString(_seguiUI,
selectedTile.Building+" : "+selectedTile.Rules+" - ",
new Vector2(nextMarqueeTextPosition+_tooltipOffset, tooltipYPosition),
Color.White);
nextMarqueeTextPosition += (int)_seguiUI.MeasureString(selectedTile.Building+" : "+selectedTile.Rules+" - ").X;
}
}
}
else
// if there isn't a custom selection, display tool tips for selected hand tile
if (_controller.Selection != Selection.TileFromCustom)
{
if (_handViewLayer.SelectedTileIndex>=0 && _handViewLayer.SelectedTileIndex<_currentHand.Count())
{
Tile selectedTile = _currentHand[_handViewLayer.SelectedTileIndex];
if (selectedTile != null)
{
int nextMarqueeTextPosition = 0;
_tooltipOffset %= (int)_seguiUI.MeasureString(selectedTile.Building+":"+selectedTile.Rules+" - ").X;
while (nextMarqueeTextPosition+_tooltipOffset<_graphics.PreferredBackBufferWidth)
{
_tooltipSpriteBatch.DrawString(_seguiUI,
selectedTile.Building+":"+selectedTile.Rules+" - ",
new Vector2(nextMarqueeTextPosition+_tooltipOffset, tooltipYPosition),
Color.White);
nextMarqueeTextPosition += (int)_seguiUI.MeasureString(selectedTile.Building+":"+selectedTile.Rules+" - ").X;
}
}
}
}
else // Display tool tip for selected custom tile
if (_customViewLayer.SelectedTileIndex>=0 && _customViewLayer.SelectedTileIndex<_controller.TileSet.Count())
{
Tile selectedTile = _controller.TileSet[_customViewLayer.SelectedTileIndex];
if (selectedTile != null)
{
int nextMarqueeTextPosition = 0;
_tooltipOffset %= (int)_seguiUI.MeasureString(selectedTile.Building+":"+selectedTile.Rules+" - ").X;
while (nextMarqueeTextPosition+_tooltipOffset<_graphics.PreferredBackBufferWidth)
{
_tooltipSpriteBatch.DrawString(_seguiUI,
selectedTile.Building+":"+selectedTile.Rules+" - ",
new Vector2(nextMarqueeTextPosition+_tooltipOffset, tooltipYPosition),
Color.White);
nextMarqueeTextPosition += (int)_seguiUI.MeasureString(selectedTile.Building+":"+selectedTile.Rules+" - ").X;
}
}
}
_tooltipSpriteBatch.End();
}
private void DrawHumanView()
{
if (_moveCamera)
{
var colorOverlay = new SpriteBatch(GraphicsDevice);
colorOverlay.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.LinearClamp,
DepthStencilState.None,
RasterizerState.CullCounterClockwise,
null,
Matrix.Identity);
colorOverlay.Draw(_gray,
new Rectangle(0, 0, _graphics.PreferredBackBufferWidth, _graphics.PreferredBackBufferHeight),
new Color(128F, 128F, 128F, 128F));
colorOverlay.End();
}
// draw the tiles in the hand
_handSpriteBatch.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.LinearClamp,
DepthStencilState.None,
RasterizerState.CullCounterClockwise,
null,
Matrix.Identity);
DrawBorder();
_handViewLayer.Draw(_handSpriteBatch,
_controller.ActivePlayer.Hand,
_handViewLayer.SelectedTileIndex,
_graphics.PreferredBackBufferHeight*4/5+10);
// if we are displaying custom tiles, display them
if (_controller.Selection == Selection.TileFromCustom)
_customViewLayer.Draw(_handSpriteBatch,
_controller.TileSet,
_customViewLayer.SelectedTileIndex,
_graphics.PreferredBackBufferHeight*1/2);
// if we are looking for a player, pass in the blank tiles for color display
if (_controller.Selection == Selection.Opponent || _controller.Selection == Selection.Player)
_customViewLayer.Draw(_handSpriteBatch,
_playerSelection,
_customViewLayer.SelectedTileIndex,
_graphics.PreferredBackBufferHeight*1/2);
_handSpriteBatch.DrawString(_seguiUI,
_selectionManager.Message,
new Vector2(
_graphics.PreferredBackBufferWidth/2f-_seguiUI.MeasureString(_selectionManager.Message).X/2, 0),
Color.Black);
_handSpriteBatch.Draw(_white,
new Rectangle(_graphics.PreferredBackBufferWidth*7/8,
0,
_graphics.PreferredBackBufferWidth/8,
18*(_controller.Players.ToArray().Length+1)),
Color.Black);
_handSpriteBatch.End();
if (!_moveCamera)
{
var colorOverlay = new SpriteBatch(GraphicsDevice);
colorOverlay.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend,
SamplerState.LinearClamp,
DepthStencilState.None,
RasterizerState.CullCounterClockwise,
null,
Matrix.Identity);
colorOverlay.Draw(_gray,
new Rectangle(20,
_graphics.PreferredBackBufferHeight*4/5,
_graphics.PreferredBackBufferWidth-40,
_graphics.PreferredBackBufferHeight-25-_graphics.PreferredBackBufferHeight*4/5),
new Color(128F, 128F, 128F, 128F));
colorOverlay.End();
}
}
/// <summary>
/// Initialize a new game if new controllers/models/views are necessary. This is usually done
/// when Options changes some settings and various objects need to be reinitialized.
/// </summary>
/// <param name = "players">Players playing the game</param>
private void InitializeNewGame(Player[] players)
{
IsMouseVisible = true;
_camera = new Camera(_graphics);
// Why is the board starting at (1600,1100)? No one knows....
_camera.PointTo(new Vector2(1600, 1100));
_controller = Controller.CustomInstance(players);
_selectionManager = _controller;
_oldKeyboardState = Keyboard.GetState();
_boardViewLayer = new BoardViewLayer(_graphics, _controller);
_handViewLayer = new HandViewLayer(_graphics, _controller) {IsCustom = false};
_customViewLayer = new HandViewLayer(_graphics, _controller) {IsCustom = true};
// a blank tile for each player, colors get added later
_playerSelection = new Tile[_controller.Players.Count()];
for (int i = 0; i<_controller.Players.Count(); i++)
_playerSelection[i] = new Blank {Owner = _controller.Players.ElementAt(i), Space = new Space()};
_selectionPoint = new Point(0, 0);
_moveCamera = true;
_oldColor = Color.Wheat;
_displayHelp = false;
_endGame = false;
base.Initialize();
}
private void UpdateCamera(KeyboardState newKeyboardState)
{
// check if we need to move the camera
if (newKeyboardState.IsKeyDown(Keys.Up))
_camera.Position = _camera.Position-new Vector2(0, 3/_camera.Zoom);
if (newKeyboardState.IsKeyDown(Keys.Left))
_camera.Position = _camera.Position-new Vector2(3/_camera.Zoom, 0);
if (newKeyboardState.IsKeyDown(Keys.Right))
_camera.Position = _camera.Position-new Vector2(-3/_camera.Zoom, 0);
if (newKeyboardState.IsKeyDown(Keys.Down))
_camera.Position = _camera.Position-new Vector2(0, -3/_camera.Zoom);
// Perform zoom on held buttons
if (newKeyboardState.IsKeyDown(Keys.Q))
_camera.ZoomOut();
if (newKeyboardState.IsKeyDown(Keys.E))
_camera.ZoomIn();
}
private void UpdateGameScreen(KeyboardState newKeyboardState)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
Exit();
_currentHand = _controller.ActivePlayer.Hand.ToArray();
UpdateCamera(newKeyboardState);
CheckEsc(newKeyboardState);
CheckMute(newKeyboardState);
if (!_endGame)
{
// if the player is siting at the keyboard
if (_controller.ActivePlayer.Input == null)
// try to process user input
try
{
UpdateInput(newKeyboardState);
}
catch (EndGameException e)
{
_endGame = true;
_controller.Message = e.Message;
}
catch (Exception e)
{
// if the user did something bad, catch the exception and display the message
_controller.Message = e.Message;
}
else if (!_controller.ActivePlayer.Input.IsThinking)
if (_controller.ActivePlayer.Input.IsComplete)
{
object input = _controller.ActivePlayer.Input.Acknowledge();
try
{
_selectionManager.Submit(input);
}
catch (EndGameException e)
{
_endGame = true;
_controller.Message = e.Message;
}
}
else
_controller.ActivePlayer.Input.GetInputAsync();
}
else if (newKeyboardState.IsKeyDown(Keys.Space) && !_oldKeyboardState.IsKeyDown(Keys.Space))
_controller.TogglePlayers();
}
/// <summary>
/// Here we check the keyboard for user input.
/// If we have any, we pass the right input
/// to the selectionManager.
/// </summary>
private void UpdateInput(KeyboardState newKeyboardState)
{
// Get the old key state to make sure buttom is pressed and not held
Keys[] oldStateKeys = _oldKeyboardState.GetPressedKeys();
if (newKeyboardState.IsKeyDown(Keys.I) && !oldStateKeys.Contains(Keys.I))
{
Tile temp = _controller.Board[_selectionPoint].Tile;
if (temp != null)
_controller.Message = temp.Rules;
}
if (newKeyboardState.IsKeyDown(Keys.H) && !oldStateKeys.Contains(Keys.H))
_displayHelp = !_displayHelp;
if (newKeyboardState.IsKeyDown(Keys.D) && !oldStateKeys.Contains(Keys.D)) {}
// testing the tile skip() functionality
if (newKeyboardState.IsKeyDown(Keys.C) && !oldStateKeys.Contains(Keys.C))
_selectionManager.Skip();
// If we are not moving the camera, we are moving the selector
if (!_moveCamera)
{
if (newKeyboardState.IsKeyDown(Keys.W) && !oldStateKeys.Contains(Keys.W))
_selectionPoint.Y--;
if (newKeyboardState.IsKeyDown(Keys.A) && !oldStateKeys.Contains(Keys.A))
_selectionPoint.X++;
if (newKeyboardState.IsKeyDown(Keys.D) && !oldStateKeys.Contains(Keys.D))
_selectionPoint.X--;
if (newKeyboardState.IsKeyDown(Keys.S) && !oldStateKeys.Contains(Keys.S))
_selectionPoint.Y++;
}
else
{
if (newKeyboardState.IsKeyDown(Keys.A) && !oldStateKeys.Contains(Keys.A))
if (_controller.Selection != Selection.TileFromCustom && _controller.Selection != Selection.Opponent &&
_controller.Selection != Selection.Player)
_handViewLayer.SelectedTileIndex--;
else
_customViewLayer.SelectedTileIndex--;
if (newKeyboardState.IsKeyDown(Keys.D) && !oldStateKeys.Contains(Keys.D))
if (_controller.Selection != Selection.TileFromCustom && _controller.Selection != Selection.Opponent &&
_controller.Selection != Selection.Player)
_handViewLayer.SelectedTileIndex++;
else
_customViewLayer.SelectedTileIndex++;
}
if (newKeyboardState.IsKeyDown(Keys.Enter) && !oldStateKeys.Contains(Keys.Enter))
switch (_controller.Selection)
{
case Selection.TileFromHand:
_selectionManager.Submit(_currentHand[_handViewLayer.SelectedTileIndex]);
break;
case Selection.PlayableSpace:
_selectionManager.Submit(_controller.Board[_selectionPoint]);
break;
case Selection.TileFromCustom:
_selectionManager.Submit(_controller.TileSet[_customViewLayer.SelectedTileIndex]);
break;
case Selection.TileFromBoard:
_selectionManager.Submit(_controller.Board[_selectionPoint].Tile);
break;
case Selection.Opponent:
case Selection.Player:
_selectionManager.Submit(_customViewLayer.ValidPlayers[_customViewLayer.SelectedTileIndex].Owner);
break;
}
if (newKeyboardState.IsKeyDown(Keys.Space) && !oldStateKeys.Contains(Keys.Space))
_moveCamera = !_moveCamera;
}
private void UpdateMenuScreen(KeyboardState newKeyboardState)
{
MenuItem selectedMenuItem = _menu.MenuItems[_menu.SelectedMenuItemIndex];
if ((newKeyboardState.IsKeyDown(Keys.Enter) && _oldKeyboardState.IsKeyUp(Keys.Enter)) ||
(newKeyboardState.IsKeyDown(Keys.Space) && _oldKeyboardState.IsKeyUp(Keys.Space)))
switch (_menu.CurrentSubMenu)
{
case SubMenu.Main:
if (_menu.SelectedMenuItemIndex == 0)
_currentScreen = Screen.Game;
switch (_menu.SelectedMenuItemIndex)
{
case 1:
_menu.TransitionToOptions(_aiParams);
break;
case 2:
Exit();
break;
}
break;
case SubMenu.Options:
if (_menu.SelectedMenuItemIndex == _menu.MenuItems.Count-1)
{
if (_aiParams == null)
_aiParams = new List<Tuple<string, int>>();
_aiParams.Clear();
for (int currentPlayer = 0; currentPlayer<6; currentPlayer++)
_aiParams.Add(new Tuple<string, int>(MenuItem.AIs[_menu.MenuItems[currentPlayer*2].SelectedAIIndex].Item1,
_menu.MenuItems[(currentPlayer*2)+1].SliderValue));
_menu.TransitionToMainMenu();
InitializeNewGame(InitPlayerInputs(_aiParams));
}
break;
}
else if ((newKeyboardState.IsKeyDown(Keys.Left) && _oldKeyboardState.IsKeyUp(Keys.Left)))
switch (selectedMenuItem.MenuItemType)
{
case MenuItemType.Bool:
selectedMenuItem.BoolValue = !selectedMenuItem.BoolValue;
break;
case MenuItemType.Slider:
selectedMenuItem.SliderDecrement();
break;
case MenuItemType.AISelector:
selectedMenuItem.SelectedAIIndex--;
selectedMenuItem.ToggleLevelSelector();
break;
default:
break;
}
else if ((newKeyboardState.IsKeyDown(Keys.Right) && _oldKeyboardState.IsKeyUp(Keys.Right)))
switch (selectedMenuItem.MenuItemType)
{
case MenuItemType.Bool:
selectedMenuItem.BoolValue = !selectedMenuItem.BoolValue;
break;
case MenuItemType.Slider:
selectedMenuItem.SliderIncrement();
break;
case MenuItemType.AISelector:
selectedMenuItem.SelectedAIIndex++;
selectedMenuItem.ToggleLevelSelector();
break;
default:
break;
}
if (newKeyboardState.IsKeyDown(Keys.Up) && _oldKeyboardState.IsKeyUp(Keys.Up))
do
{
_menu.SelectedMenuItemIndex--;
} while (!_menu.MenuItems[_menu.SelectedMenuItemIndex].Enabled);
if (newKeyboardState.IsKeyDown(Keys.Down) && _oldKeyboardState.IsKeyUp(Keys.Down))
do
{
_menu.SelectedMenuItemIndex++;
} while (!_menu.MenuItems[_menu.SelectedMenuItemIndex].Enabled);
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using UMA.CharacterSystem;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Animations;
#endif
namespace UMA
{
public class UMAAssetIndexer : MonoBehaviour, ISerializationCallbackReceiver
{
#region constants and static strings
public static string SortOrder = "Name";
public static string[] SortOrders = { "Name", "AssetName" };
public static Dictionary<string, System.Type> TypeFromString = new Dictionary<string, System.Type>();
#endregion
#region Fields
public bool AutoUpdate;
private Dictionary<System.Type, System.Type> TypeToLookup = new Dictionary<System.Type, System.Type>()
{
{ (typeof(SlotDataAsset)),(typeof(SlotDataAsset)) },
{ (typeof(OverlayDataAsset)),(typeof(OverlayDataAsset)) },
{ (typeof(RaceData)),(typeof(RaceData)) },
{ (typeof(UMATextRecipe)),(typeof(UMATextRecipe)) },
{ (typeof(UMAWardrobeRecipe)),(typeof(UMAWardrobeRecipe)) },
{ (typeof(UMAWardrobeCollection)),(typeof(UMAWardrobeCollection)) },
{ (typeof(RuntimeAnimatorController)),(typeof(RuntimeAnimatorController)) },
#if UNITY_EDITOR
{ (typeof(AnimatorController)),(typeof(RuntimeAnimatorController)) },
#endif
{ typeof(TextAsset), typeof(TextAsset) },
{ (typeof(DynamicUMADnaAsset)), (typeof(DynamicUMADnaAsset)) }
};
// The names of the fully qualified types.
public List<string> IndexedTypeNames = new List<string>();
// These list is used so Unity will serialize the data
public List<AssetItem> SerializedItems = new List<AssetItem>();
// This is really where we keep the data.
private Dictionary<System.Type, Dictionary<string, AssetItem>> TypeLookup = new Dictionary<System.Type, Dictionary<string, AssetItem>>();
// This list tracks the types for use in iterating through the dictionaries
private System.Type[] Types =
{
(typeof(SlotDataAsset)),
(typeof(OverlayDataAsset)),
(typeof(RaceData)),
(typeof(UMATextRecipe)),
(typeof(UMAWardrobeRecipe)),
(typeof(UMAWardrobeCollection)),
(typeof(RuntimeAnimatorController)),
#if UNITY_EDITOR
(typeof(AnimatorController)),
#endif
(typeof(DynamicUMADnaAsset)),
(typeof(TextAsset))
};
#endregion
#region Static Fields
static GameObject theIndex = null;
static UMAAssetIndexer theIndexer = null;
#endregion
public static System.Diagnostics.Stopwatch StartTimer()
{
#if TIMEINDEXER
Debug.Log("Timer started at " + Time.realtimeSinceStartup + " Sec");
System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
st.Start();
return st;
#else
return null;
#endif
}
public static void StopTimer(System.Diagnostics.Stopwatch st, string Status)
{
#if TIMEINDEXER
st.Stop();
Debug.Log(Status + " Completed " + st.ElapsedMilliseconds + "ms");
return;
#endif
}
public static UMAAssetIndexer Instance
{
get
{
if (theIndex == null || theIndexer == null)
{
#if UNITY_EDITOR
var st = StartTimer();
theIndex = Resources.Load("AssetIndexer") as GameObject;
if (theIndex == null)
{
return null;
}
theIndexer = theIndex.GetComponent<UMAAssetIndexer>();
if (theIndexer == null)
{
return null;
}
StopTimer(st,"Asset index load");
#else
theIndex = GameObject.Instantiate(Resources.Load<GameObject>("AssetIndexer")) as GameObject;
theIndex.hideFlags = HideFlags.HideAndDontSave;
theIndexer = theIndex.GetComponent<UMAAssetIndexer>();
#endif
}
return theIndexer;
}
}
#if UNITY_EDITOR
public void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
if (!AutoUpdate)
{
return;
}
bool changed = false;
// Build a dictionary of the items by path.
Dictionary<string, AssetItem> ItemsByPath = new Dictionary<string, AssetItem>();
UpdateSerializedList();
foreach (AssetItem ai in SerializedItems)
{
if (ItemsByPath.ContainsKey(ai._Path))
{
Debug.Log("Duplicate path for item: " + ai._Path);
continue;
}
ItemsByPath.Add(ai._Path, ai);
}
// see if they moved it in the editor.
for (int i = 0; i < movedAssets.Length; i++)
{
string NewPath = movedAssets[i];
string OldPath = movedFromAssetPaths[i];
// Check to see if this is an indexed asset.
if (ItemsByPath.ContainsKey(OldPath))
{
changed = true;
// If they moved it into an Asset Bundle folder, then we need to "unindex" it.
if (InAssetBundleFolder(NewPath))
{
// Null it out, so we don't add it to the index...
ItemsByPath[OldPath] = null;
continue;
}
//
ItemsByPath[OldPath]._Path = NewPath;
}
}
// Rebuild the tables
SerializedItems.Clear();
foreach (AssetItem ai in ItemsByPath.Values)
{
// We null things out when we want to delete them. This prevents it from going back into
// the dictionary when rebuilt.
if (ai == null)
continue;
SerializedItems.Add(ai);
}
UpdateSerializedDictionaryItems();
if (changed)
{
ForceSave();
}
}
/// <summary>
/// Force the Index to save and reload
/// </summary>
public void ForceSave()
{
var st = StartTimer();
EditorUtility.SetDirty(this.gameObject);
AssetDatabase.SaveAssets();
StopTimer(st, "ForceSave");
}
#endif
#region Manage Types
/// <summary>
/// Returns a list of all types that we know about.
/// </summary>
/// <returns></returns>
public System.Type[] GetTypes()
{
return Types;
}
public bool IsIndexedType(System.Type type)
{
foreach (System.Type check in TypeToLookup.Keys)
{
if (check == type)
return true;
}
return false;
}
public bool IsAdditionalIndexedType(string QualifiedName)
{
foreach (string s in IndexedTypeNames)
{
if (s == QualifiedName)
return true;
}
return false;
}
/// <summary>
/// Add a type to the types tracked
/// </summary>
/// <param name="sType"></param>
public void AddType(System.Type sType)
{
string QualifiedName = sType.AssemblyQualifiedName;
if (IsAdditionalIndexedType(QualifiedName)) return;
List<System.Type> newTypes = new List<System.Type>();
newTypes.AddRange(Types);
newTypes.Add(sType);
Types = newTypes.ToArray();
TypeToLookup.Add(sType, sType);
IndexedTypeNames.Add(sType.AssemblyQualifiedName);
BuildStringTypes();
}
public void RemoveType(System.Type sType)
{
string QualifiedName = sType.AssemblyQualifiedName;
if (!IsAdditionalIndexedType(QualifiedName)) return;
TypeToLookup.Remove(sType);
List<System.Type> newTypes = new List<System.Type>();
newTypes.AddRange(Types);
newTypes.Remove(sType);
Types = newTypes.ToArray();
TypeLookup.Remove(sType);
IndexedTypeNames.Remove(sType.AssemblyQualifiedName);
BuildStringTypes();
}
#endregion
#region Access the index
/// <summary>
/// Return the asset specified, if it exists.
/// if it can't be found by name, then we do a scan of the assets to see if
/// we can find the name directly on the object, and return that.
/// We then rebuild the index to make sure it's up to date.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Name"></param>
/// <returns></returns>
public AssetItem GetAssetItem<T>(string Name)
{
System.Type ot = typeof(T);
System.Type theType = TypeToLookup[ot];
Dictionary<string, AssetItem> TypeDic = GetAssetDictionary(theType);
if (TypeDic.ContainsKey(Name))
{
return TypeDic[Name];
}
/*
foreach (AssetItem ai in TypeDic.Values)
{
if (Name == ai.EvilName)
{
RebuildIndex();
return ai;
}
}*/
return null;
}
/// <summary>
/// Gets the asset hash and name for the given object
/// </summary>
private void GetEvilAssetNameAndHash(System.Type type, Object o, ref string assetName, int assetHash)
{
if (o is SlotDataAsset)
{
SlotDataAsset sd = o as SlotDataAsset;
assetName = sd.slotName;
assetHash = sd.nameHash;
}
else if (o is OverlayDataAsset)
{
OverlayDataAsset od = o as OverlayDataAsset;
assetName = od.overlayName;
assetHash = od.nameHash;
}
else if (o is RaceData)
{
RaceData rd = o as RaceData;
assetName = rd.raceName;
assetHash = UMAUtils.StringToHash(assetName);
}
else
{
assetName = o.name;
assetHash = UMAUtils.StringToHash(assetName);
}
}
public List<T> GetAllAssets<T>(string[] foldersToSearch = null) where T : UnityEngine.Object
{
var st = StartTimer();
var ret = new List<T>();
System.Type ot = typeof(T);
System.Type theType = TypeToLookup[ot];
Dictionary<string, AssetItem> TypeDic = GetAssetDictionary(theType);
foreach (KeyValuePair<string, AssetItem> kp in TypeDic)
{
if (AssetFolderCheck(kp.Value, foldersToSearch))
ret.Add((kp.Value.Item as T));
}
StopTimer(st, "GetAllAssets type=" + typeof(T).Name);
return ret;
}
public T GetAsset<T>(int nameHash, string[] foldersToSearch = null) where T : UnityEngine.Object
{
System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
st.Start();
System.Type ot = typeof(T);
Dictionary<string, AssetItem> TypeDic = (Dictionary<string, AssetItem>)TypeLookup[ot];
string assetName = "";
int assetHash = -1;
foreach (KeyValuePair<string, AssetItem> kp in TypeDic)
{
assetName = "";
assetHash = -1;
GetEvilAssetNameAndHash(typeof(T), kp.Value.Item, ref assetName, assetHash);
if (assetHash == nameHash)
{
if (AssetFolderCheck(kp.Value, foldersToSearch))
{
st.Stop();
if (st.ElapsedMilliseconds > 2)
{
Debug.Log("GetAsset 0 for type "+typeof(T).Name+" completed in " + st.ElapsedMilliseconds + "ms");
}
return (kp.Value.Item as T);
}
else
{
st.Stop();
if (st.ElapsedMilliseconds > 2)
{
Debug.Log("GetAsset 1 for type " + typeof(T).Name + " completed in " + st.ElapsedMilliseconds + "ms");
}
return null;
}
}
}
st.Stop();
if (st.ElapsedMilliseconds > 2)
{
Debug.Log("GetAsset 2 for type " + typeof(T).Name + " completed in " + st.ElapsedMilliseconds + "ms");
}
return null;
}
public T GetAsset<T>(string name, string[] foldersToSearch = null) where T : UnityEngine.Object
{
var thisAssetItem = GetAssetItem<T>(name);
if (thisAssetItem != null)
{
if (AssetFolderCheck(thisAssetItem, foldersToSearch))
return (thisAssetItem.Item as T);
else
return null;
}
else
{
return null;
}
}
/// <summary>
/// Checks if the given asset path resides in one of the given folder paths. Returns true if foldersToSearch is null or empty and no check is required
/// </summary>
private bool AssetFolderCheck(AssetItem itemToCheck, string[] foldersToSearch = null)
{
if (foldersToSearch == null)
return true;
if (foldersToSearch.Length == 0)
return true;
for (int i = 0; i < foldersToSearch.Length; i++)
{
if (itemToCheck._Path.IndexOf(foldersToSearch[i]) > -1)
return true;
}
return false;
}
#if UNITY_EDITOR
/// <summary>
/// Check to see if something is an an assetbundle. If so, don't add it
/// </summary>
/// <param name="path"></param>
/// <param name="assetName"></param>
/// <returns></returns>
public bool InAssetBundle(string path)
{
// path = System.IO.Path.GetDirectoryName(path);
string[] assetBundleNames = AssetDatabase.GetAllAssetBundleNames();
List<string> pathsInBundle;
for (int i = 0; i < assetBundleNames.Length; i++)
{
pathsInBundle = new List<string>(AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleNames[i]));
if (pathsInBundle.Contains(path))
return true;
}
return false;
}
public bool InAssetBundleFolder(string path)
{
path = System.IO.Path.GetDirectoryName(path);
string[] assetBundleNames = AssetDatabase.GetAllAssetBundleNames();
List<string> pathsInBundle;
for (int i = 0; i < assetBundleNames.Length; i++)
{
pathsInBundle = new List<string>(AssetDatabase.GetAssetPathsFromAssetBundle(assetBundleNames[i]));
foreach (string s in pathsInBundle)
{
if (System.IO.Path.GetDirectoryName(s) == path)
return true;
}
}
return false;
}
#endif
#endregion
#region Add Remove Assets
/// <summary>
/// Adds an asset to the index. Does NOT save the asset! you must do that separately.
/// </summary>
/// <param name="type"></param>
/// <param name="o"></param>
public void AddAsset(System.Type type, string name, string path, Object o, bool skipBundleCheck = false)
{
if (o == null)
{
Debug.Log("Skipping null item");
return;
}
if (type == null)
{
type = o.GetType();
}
AssetItem ai = new AssetItem(type, name, path, o);
AddAssetItem(ai, skipBundleCheck);
}
/// <summary>
/// Adds an asset to the index. If the name already exists, it is not added. (Should we do this, or replace it?)
/// </summary>
/// <param name="ai"></param>
private void AddAssetItem(AssetItem ai, bool SkipBundleCheck = false)
{
try
{
System.Type theType = TypeToLookup[ai._Type];
Dictionary<string, AssetItem> TypeDic = GetAssetDictionary(theType);
// Get out if we already have it.
if (TypeDic.ContainsKey(ai._Name))
{
Debug.Log("Duplicate asset " + ai._Name + " was ignored.");
return;
}
if (ai._Name.ToLower().Contains((ai._Type.Name + "placeholder").ToLower()))
{
Debug.Log("Placeholder asset " + ai._Name + " was ignored. Placeholders are not indexed.");
return;
}
#if UNITY_EDITOR
if (!SkipBundleCheck)
{
string Path = AssetDatabase.GetAssetPath(ai.Item.GetInstanceID());
if (InAssetBundle(Path))
{
Debug.Log("Asset " + ai._Name + "is in Asset Bundle, and was not added to the index.");
return;
}
}
#endif
TypeDic.Add(ai._Name, ai);
}
catch (System.Exception ex)
{
UnityEngine.Debug.LogWarning("Exception in UMAAssetIndexer.AddAssetItem: " + ex);
}
}
#if UNITY_EDITOR
/// <summary>
/// This is the evil version of AddAsset. This version cares not for the good of the project, nor
/// does it care about readability, expandibility, and indeed, hates goodness with every beat of it's
/// tiny evil shrivelled heart.
/// I started going down the good path - I created an interface to get the name info, added it to all the
/// classes. Then we ran into RuntimeAnimatorController. I would have had to wrap it. And Visual Studio kept
/// complaining about the interface, even though Unity thought it was OK.
///
/// So in the end, good was defeated. And would never raise it's sword in the pursuit of chivalry again.
///
/// And EvilAddAsset doesn't save either. You have to do that manually.
/// </summary>
/// <param name="type"></param>
/// <param name="Name"></param>
/// <param name="o"></param>
public void EvilAddAsset(System.Type type, Object o)
{
AssetItem ai = null;
ai = new AssetItem(type, o);
ai._Path = AssetDatabase.GetAssetPath(o.GetInstanceID());
AddAssetItem(ai);
}
/// <summary>
/// Removes an asset from the index
/// </summary>
/// <param name="type"></param>
/// <param name="Name"></param>
public void RemoveAsset(System.Type type, string Name)
{
System.Type theType = TypeToLookup[type];
Dictionary<string, AssetItem> TypeDic = GetAssetDictionary(theType);
TypeDic.Remove(Name);
}
#endif
#endregion
#region Maintenance
/// <summary>
/// Updates the dictionaries from this list.
/// Used when restoring items after modification, or after deserialization.
/// </summary>
private void UpdateSerializedDictionaryItems()
{
foreach (System.Type type in Types)
{
CreateLookupDictionary(type);
}
foreach (AssetItem ai in SerializedItems)
{
// We null things out when we want to delete them. This prevents it from going back into
// the dictionary when rebuilt.
if (ai == null)
continue;
AddAssetItem(ai, true);
}
}
/// <summary>
/// Creates a lookup dictionary for a list. Used when reloading after deserialization
/// </summary>
/// <param name="type"></param>
private void CreateLookupDictionary(System.Type type)
{
Dictionary<string, AssetItem> dic = new Dictionary<string, AssetItem>();
if (TypeLookup.ContainsKey(type))
{
TypeLookup[type] = dic;
}
else
{
TypeLookup.Add(type, dic);
}
}
/// <summary>
/// Updates the list so all items can be processed at once, or for
/// serialization.
/// </summary>
private void UpdateSerializedList()
{
SerializedItems.Clear();
foreach (System.Type type in TypeToLookup.Keys)
{
if (type == TypeToLookup[type])
{
Dictionary<string, AssetItem> TypeDic = GetAssetDictionary(type);
foreach (AssetItem ai in TypeDic.Values)
{
// Don't add asset bundle or resource items to index. They are loaded on demand.
if (ai.IsAssetBundle == false && ai.IsResource == false)
{
SerializedItems.Add(ai);
}
}
}
}
}
/// <summary>
/// Builds a list of types and a string to look them up.
/// </summary>
private void BuildStringTypes()
{
TypeFromString.Clear();
foreach (System.Type st in Types)
{
TypeFromString.Add(st.Name, st);
}
}
#if UNITY_EDITOR
public void RepairAndCleanup()
{
// Rebuild the tables
UpdateSerializedList();
for(int i=0;i<SerializedItems.Count;i++)
{
AssetItem ai = SerializedItems[i];
if (!ai.IsAssetBundle)
{
// If we already have a reference to the item, let's verify that everything is correct on it.
Object obj = ai.Item;
if (obj != null)
{
ai._Name = ai.EvilName;
ai._Path = AssetDatabase.GetAssetPath(obj.GetInstanceID());
ai._Guid = AssetDatabase.AssetPathToGUID(ai._Path);
}
else
{
// Clear out the item reference so we will attempt to fix it if it's broken.
ai._SerializedItem = null;
// This will attempt to load the item, using the path, guid or name (in that order).
// This is in case we didn't have a reference to the item, and it was moved
ai.CachSerializedItem();
// If an item can't be found and we didn't ahve a reference to it, then we need to delete it.
if (ai._SerializedItem == null)
{
// Can't be found or loaded
// null it out, so it doesn't get added back.
SerializedItems[i] = null;
}
}
}
}
UpdateSerializedDictionaryItems();
ForceSave();
}
public void AddEverything(bool includeText)
{
Clear(false);
foreach(string s in TypeFromString.Keys)
{
System.Type CurrentType = TypeFromString[s];
if (!includeText)
{
if (CurrentType == typeof(TextAsset))
{
continue;
}
}
if (s != "AnimatorController")
{
string[] guids = AssetDatabase.FindAssets("t:" + s);
foreach (string guid in guids)
{
string Path = AssetDatabase.GUIDToAssetPath(guid);
if (Path.ToLower().Contains(".shader"))
{
continue;
}
Object o = AssetDatabase.LoadAssetAtPath(Path, CurrentType);
if (o != null)
{
AssetItem ai = new AssetItem(CurrentType, o);
AddAssetItem(ai);
}
else
{
if (Path == null)
{
Debug.LogWarning("Cannot instantiate item " + guid);
}
else
{
Debug.LogWarning("Cannot instantiate item " + Path);
}
}
}
}
}
ForceSave();
}
/// <summary>
/// Clears the index
/// </summary>
public void Clear(bool forceSave = true)
{
// Rebuild the tables
ClearReferences();
SerializedItems.Clear();
UpdateSerializedDictionaryItems();
if (forceSave)
ForceSave();
}
/// <summary>
/// Adds references to all items by accessing the item property.
/// This forces Unity to load the item and return a reference to it.
/// When building, Unity needs the references to the items because we
/// cannot demand load them without the AssetDatabase.
/// </summary>
public void AddReferences()
{
// Rebuild the tables
UpdateSerializedList();
foreach (AssetItem ai in SerializedItems)
{
if (!ai.IsAssetBundle)
ai.CachSerializedItem();
}
UpdateSerializedDictionaryItems();
ForceSave();
}
/// <summary>
/// This releases items by dereferencing them so they can be
/// picked up by garbage collection.
/// This also makes working with the index much faster.
/// </summary>
public void ClearReferences()
{
// Rebuild the tables
UpdateSerializedList();
foreach (AssetItem ai in SerializedItems)
{
ai.ReleaseItem();
}
UpdateSerializedDictionaryItems();
ForceSave();
}
#endif
/// <summary>
/// returns the entire lookup dictionary for a specific type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Dictionary<string, AssetItem> GetAssetDictionary(System.Type type)
{
System.Type LookupType = TypeToLookup[type];
if (TypeLookup.ContainsKey(LookupType) == false)
{
TypeLookup[LookupType] = new Dictionary<string, AssetItem>();
}
return TypeLookup[LookupType];
}
/// <summary>
/// Rebuilds the name indexes by dumping everything back to the list, updating the name, and then rebuilding
/// the dictionaries.
/// </summary>
public void RebuildIndex()
{
UpdateSerializedList();
foreach (AssetItem ai in SerializedItems)
{
ai._Name = ai.EvilName;
}
UpdateSerializedDictionaryItems();
}
#endregion
#region Serialization
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
UpdateSerializedList();// this.SerializeAllObjects);
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
var st = StartTimer();
#region typestuff
List<System.Type> newTypes = new List<System.Type>()
{
(typeof(SlotDataAsset)),
(typeof(OverlayDataAsset)),
(typeof(RaceData)),
(typeof(UMATextRecipe)),
(typeof(UMAWardrobeRecipe)),
(typeof(UMAWardrobeCollection)),
(typeof(RuntimeAnimatorController)),
#if UNITY_EDITOR
(typeof(AnimatorController)),
#endif
(typeof(DynamicUMADnaAsset)),
(typeof(TextAsset))
};
TypeToLookup = new Dictionary<System.Type, System.Type>()
{
{ (typeof(SlotDataAsset)),(typeof(SlotDataAsset)) },
{ (typeof(OverlayDataAsset)),(typeof(OverlayDataAsset)) },
{ (typeof(RaceData)),(typeof(RaceData)) },
{ (typeof(UMATextRecipe)),(typeof(UMATextRecipe)) },
{ (typeof(UMAWardrobeRecipe)),(typeof(UMAWardrobeRecipe)) },
{ (typeof(UMAWardrobeCollection)),(typeof(UMAWardrobeCollection)) },
{ (typeof(RuntimeAnimatorController)),(typeof(RuntimeAnimatorController)) },
#if UNITY_EDITOR
{ (typeof(AnimatorController)),(typeof(RuntimeAnimatorController)) },
#endif
{ typeof(TextAsset), typeof(TextAsset) },
{ (typeof(DynamicUMADnaAsset)), (typeof(DynamicUMADnaAsset)) }
};
List<string> invalidTypeNames = new List<string>();
// Add the additional Types.
foreach (string s in IndexedTypeNames)
{
if (s == "")
continue;
System.Type sType = System.Type.GetType(s);
if (sType == null)
{
invalidTypeNames.Add(s);
Debug.LogWarning("Could not find type for " + s);
continue;
}
newTypes.Add(sType);
if (!TypeToLookup.ContainsKey(sType))
{
TypeToLookup.Add(sType, sType);
}
}
Types = newTypes.ToArray();
if (invalidTypeNames.Count > 0)
{
foreach (string ivs in invalidTypeNames)
{
IndexedTypeNames.Remove(ivs);
}
}
BuildStringTypes();
#endregion
UpdateSerializedDictionaryItems();
StopTimer(st, "Before Serialize");
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using NPOI.Util;
/**
* Describes the frozen and Unfozen panes.
* NOTE: This source Is automatically generated please do not modify this file. Either subclass or
* Remove the record in src/records/definitions.
* @author Glen Stampoultzis (glens at apache.org)
*/
internal class PaneRecord : StandardRecord
{
public const short sid = 0x41;
private short field_1_x;
private short field_2_y;
private short field_3_topRow;
private short field_4_leftColumn;
private short field_5_activePane;
public static short ACTIVE_PANE_LOWER_RIGHT = 0;
public static short ACTIVE_PANE_UPPER_RIGHT = 1;
public static short ACTIVE_PANE_LOWER_LEFT = 2;
// TODO - Remove obsolete field (it was deprecated May-2008 v3.1)
/** @deprecated use ACTIVE_PANE_UPPER_LEFT */
[Obsolete]
public static short ACTIVE_PANE_UPER_LEFT = 3;
public static short ACTIVE_PANE_UPPER_LEFT = 3;
public PaneRecord()
{
}
/**
* Constructs a Pane record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public PaneRecord(RecordInputStream in1)
{
field_1_x = in1.ReadShort();
field_2_y = in1.ReadShort();
field_3_topRow = in1.ReadShort();
field_4_leftColumn = in1.ReadShort();
field_5_activePane = in1.ReadShort();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[PANE]\n");
buffer.Append(" .x = ")
.Append("0x").Append(HexDump.ToHex(X))
.Append(" (").Append(X).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .y = ")
.Append("0x").Append(HexDump.ToHex(Y))
.Append(" (").Append(Y).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .topRow = ")
.Append("0x").Append(HexDump.ToHex(TopRow))
.Append(" (").Append(TopRow).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .leftColumn = ")
.Append("0x").Append(HexDump.ToHex(LeftColumn))
.Append(" (").Append(LeftColumn).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .activePane = ")
.Append("0x").Append(HexDump.ToHex(ActivePane))
.Append(" (").Append(ActivePane).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append("[/PANE]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(field_1_x);
out1.WriteShort(field_2_y);
out1.WriteShort(field_3_topRow);
out1.WriteShort(field_4_leftColumn);
out1.WriteShort(field_5_activePane);
}
protected override int DataSize
{
get
{
return 2 + 2 + 2 + 2 + 2;
}
}
public override short Sid
{
get { return sid; }
}
public override Object Clone()
{
PaneRecord rec = new PaneRecord();
rec.field_1_x = field_1_x;
rec.field_2_y = field_2_y;
rec.field_3_topRow = field_3_topRow;
rec.field_4_leftColumn = field_4_leftColumn;
rec.field_5_activePane = field_5_activePane;
return rec;
}
/**
* Get the x field for the Pane record.
*/
public short X
{
get
{
return field_1_x;
}
set
{
this.field_1_x = value;
}
}
/**
* Get the y field for the Pane record.
*/
public short Y
{
get
{
return field_2_y;
}
set
{
this.field_2_y = value;
}
}
/**
* Get the top row field for the Pane record.
*/
public short TopRow
{
get
{
return field_3_topRow;
}
set
{
this.field_3_topRow = value;
}
}
/**
* Get the left column field for the Pane record.
*/
public short LeftColumn
{
get
{
return field_4_leftColumn;
}
set
{
this.field_4_leftColumn = value;
}
}
/**
* Get the active pane field for the Pane record.
*
* @return One of
* ACTIVE_PANE_LOWER_RIGHT
* ACTIVE_PANE_UPPER_RIGHT
* ACTIVE_PANE_LOWER_LEFT
* ACTIVE_PANE_UPPER_LEFT
*/
public short ActivePane
{
get
{
return field_5_activePane;
}
set
{
this.field_5_activePane = value;
}
}
}
}
| |
using System;
using System.Collections.Immutable;
using System.Threading;
using CSharpGuidelinesAnalyzer.Extensions;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace CSharpGuidelinesAnalyzer.Rules.MiscellaneousDesign
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class RaiseEventFromProtectedVirtualMethodAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Method that raises an event should be protected virtual and be named 'On' followed by event name";
private const string KindMessageFormat = "Event '{0}' should be raised from a regular method";
private const string ModifiersMessageFormat = "Method '{0}' raises event '{1}', so it should be protected and virtual";
private const string NameMessageFormat = "Method '{0}' raises event '{1}', so it should be named '{2}'";
private const string Description = "Use a protected virtual method to raise each event.";
public const string DiagnosticId = "AV1225";
[NotNull]
private static readonly AnalyzerCategory Category = AnalyzerCategory.MiscellaneousDesign;
[NotNull]
private static readonly DiagnosticDescriptor KindRule = new DiagnosticDescriptor(DiagnosticId, Title, KindMessageFormat, Category.DisplayName,
DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId));
[NotNull]
private static readonly DiagnosticDescriptor ModifiersRule = new DiagnosticDescriptor(DiagnosticId, Title, ModifiersMessageFormat, Category.DisplayName,
DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId));
[NotNull]
private static readonly DiagnosticDescriptor NameRule = new DiagnosticDescriptor(DiagnosticId, Title, NameMessageFormat, Category.DisplayName,
DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId));
private static readonly ImmutableArray<MethodKind> RegularMethodKinds = new[]
{
MethodKind.Ordinary,
MethodKind.ExplicitInterfaceImplementation
}.ToImmutableArray();
[NotNull]
private static readonly Action<OperationAnalysisContext> AnalyzeInvocationAction = context => context.SkipInvalid(AnalyzeInvocation);
[ItemNotNull]
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(KindRule, ModifiersRule, NameRule);
public override void Initialize([NotNull] AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterOperationAction(AnalyzeInvocationAction, OperationKind.Invocation);
}
private static void AnalyzeInvocation(OperationAnalysisContext context)
{
var invocation = (IInvocationOperation)context.Operation;
if (invocation.TargetMethod.MethodKind == MethodKind.DelegateInvoke)
{
AnalyzeEventInvocation(context, invocation);
}
}
private static void AnalyzeEventInvocation(OperationAnalysisContext context, [NotNull] IInvocationOperation invocation)
{
IEventSymbol @event = TryGetEvent(invocation.Instance, context.ContainingSymbol as IMethodSymbol, context);
if (@event != null)
{
IMethodSymbol containingMethod = invocation.TryGetContainingMethod(context.Compilation);
AnalyzeContainingMethod(containingMethod, @event, context);
}
}
[CanBeNull]
private static IEventSymbol TryGetEvent([NotNull] IOperation operation, [CanBeNull] IMethodSymbol containingMethod, OperationAnalysisContext context)
{
return TryGetEventForInvocation(operation) ??
TryGetEventForNullConditionalAccessInvocation(operation, context.Compilation, context.CancellationToken) ??
TryGetEventForLocalCopy(operation, containingMethod, context);
}
[CanBeNull]
private static IEventSymbol TryGetEventForInvocation([NotNull] IOperation operation)
{
var eventReference = operation as IEventReferenceOperation;
return eventReference?.Event;
}
[CanBeNull]
private static IEventSymbol TryGetEventForNullConditionalAccessInvocation([NotNull] IOperation operation, [NotNull] Compilation compilation,
CancellationToken cancellationToken)
{
if (operation is IConditionalAccessInstanceOperation)
{
SemanticModel model = compilation.GetSemanticModel(operation.Syntax.SyntaxTree);
return model.GetSymbolInfo(operation.Syntax, cancellationToken).Symbol as IEventSymbol;
}
return null;
}
[CanBeNull]
private static IEventSymbol TryGetEventForLocalCopy([NotNull] IOperation operation, [CanBeNull] IMethodSymbol containingMethod,
OperationAnalysisContext context)
{
return operation is ILocalReferenceOperation local && containingMethod != null
? TryGetEventFromMethodStatements(containingMethod, local.Local, context)
: null;
}
[CanBeNull]
private static IEventSymbol TryGetEventFromMethodStatements([NotNull] IMethodSymbol containingMethod, [NotNull] ILocalSymbol local,
OperationAnalysisContext context)
{
IOperation body = containingMethod.TryGetOperationBlockForMethod(context.Compilation, context.CancellationToken);
if (body != null)
{
var walker = new LocalAssignmentWalker(local);
walker.Visit(body);
return walker.Event;
}
return null;
}
private static void AnalyzeContainingMethod([CanBeNull] IMethodSymbol method, [NotNull] IEventSymbol @event, OperationAnalysisContext context)
{
if (method == null || !RegularMethodKinds.Contains(method.MethodKind))
{
Location location = method != null && !method.IsSynthesized() ? method.Locations[0] : context.Operation.Syntax.GetLocation();
context.ReportDiagnostic(Diagnostic.Create(KindRule, location, @event.Name));
}
else
{
if (!method.IsSynthesized())
{
if (!AnalyzeMethodName(method, @event, context))
{
AnalyzeMethodSignature(method, @event, context);
}
}
}
}
private static bool AnalyzeMethodName([NotNull] IMethodSymbol method, [NotNull] IEventSymbol @event, OperationAnalysisContext context)
{
string nameExpected = string.Concat("On", @event.Name);
string nameActual = method.MemberNameWithoutExplicitInterfacePrefix();
if (nameActual != nameExpected)
{
context.ReportDiagnostic(Diagnostic.Create(NameRule, method.Locations[0], method.Name, @event.Name, nameExpected));
return true;
}
return false;
}
private static void AnalyzeMethodSignature([NotNull] IMethodSymbol method, [NotNull] IEventSymbol @event, OperationAnalysisContext context)
{
if (!method.ContainingType.IsSealed && !method.IsStatic && method.MethodKind != MethodKind.ExplicitInterfaceImplementation)
{
if (!method.IsVirtual || !IsProtected(method))
{
context.ReportDiagnostic(Diagnostic.Create(ModifiersRule, method.Locations[0], method.Name, @event.Name));
}
}
}
private static bool IsProtected([NotNull] IMethodSymbol method)
{
return method.DeclaredAccessibility == Accessibility.Protected || method.DeclaredAccessibility == Accessibility.ProtectedAndInternal;
}
private sealed class LocalAssignmentWalker : ExplicitOperationWalker
{
[NotNull]
private readonly ILocalSymbol local;
[CanBeNull]
public IEventSymbol Event { get; private set; }
public LocalAssignmentWalker([NotNull] ILocalSymbol local)
{
Guard.NotNull(local, nameof(local));
this.local = local;
}
public override void VisitSimpleAssignment([NotNull] ISimpleAssignmentOperation operation)
{
if (operation.Target is ILocalReferenceOperation targetLocal && local.IsEqualTo(targetLocal.Local))
{
TrySetEvent(operation.Value);
}
base.VisitSimpleAssignment(operation);
}
public override void VisitVariableDeclarator([NotNull] IVariableDeclaratorOperation operation)
{
if (local.IsEqualTo(operation.Symbol))
{
IVariableInitializerOperation initializer = operation.GetVariableInitializer();
if (initializer != null)
{
TrySetEvent(initializer.Value);
}
}
base.VisitVariableDeclarator(operation);
}
private void TrySetEvent([CanBeNull] IOperation assignedValue)
{
if (assignedValue is IEventReferenceOperation eventReference)
{
Event = eventReference.Event;
}
}
}
}
}
| |
namespace PokerTell.Statistics.Tests.Analyzation
{
using System.Collections.Generic;
using System.Linq;
using Infrastructure.Services;
using Machine.Specifications;
using Moq;
using PokerTell.Infrastructure.Enumerations.PokerHand;
using PokerTell.Infrastructure.Interfaces.PokerHand;
using PokerTell.PokerHand.Analyzation;
using PokerTell.Statistics.Analyzation;
using PokerTell.Statistics.Interfaces;
using It = Machine.Specifications.It;
// Resharper disable InconsistentNaming
public abstract class PreFlopHandStrengthStatisticsSpecs
{
protected static double[] _unraisedPotCallingRatios;
protected static double[] _raisedPotCallingRatios;
protected static double[] _raiseSizeKeys;
protected static IPreFlopHandStrengthStatistics _sut;
protected static Mock<IAnalyzablePokerPlayer> _hero1;
protected static Mock<IAnalyzablePokerPlayer> _hero2;
protected static Mock<IAnalyzablePokerPlayer> _hero3;
protected static IEnumerable<IAnalyzablePokerPlayer> _analyzablePokerPlayers;
protected static ActionSequences _validActionSequence;
protected static string _validHoleCards;
protected static Mock<IValuedHoleCards> _valuedHoleCardsMock;
protected static Mock<IValuedHoleCardsAverage> _valuedHoleCardsAverageMock;
Establish specContext = () => {
_validHoleCards = "As Ah";
_validActionSequence = ActionSequences.HeroC;
_unraisedPotCallingRatios = new[] { 0.1, 0.2 };
_raisedPotCallingRatios = new[] { 0.3, 0.4 };
_raiseSizeKeys = new[] { 1.0, 2.0, 3.0 };
_valuedHoleCardsMock = new Mock<IValuedHoleCards>();
_valuedHoleCardsMock.Setup(h => h.InitializeWith(Moq.It.IsAny<string>())).Returns(_valuedHoleCardsMock.Object);
_valuedHoleCardsAverageMock = new Mock<IValuedHoleCardsAverage>();
_hero1 = new Mock<IAnalyzablePokerPlayer>();
_hero2 = new Mock<IAnalyzablePokerPlayer>();
_hero3 = new Mock<IAnalyzablePokerPlayer>();
_hero1.SetupGet(h => h.Position).Returns(1);
_hero2.SetupGet(h => h.Position).Returns(2);
_hero3.SetupGet(h => h.Position).Returns(3);
_analyzablePokerPlayers = new[] { _hero1.Object, _hero2.Object, _hero3.Object };
_sut = new PreFlopHandStrengthStatistics(new Constructor<IValuedHoleCards>(() => _valuedHoleCardsMock.Object),
_valuedHoleCardsAverageMock.Object)
.InitializeWith(_unraisedPotCallingRatios,
_raisedPotCallingRatios,
_raiseSizeKeys);
};
public abstract class Ctx_AllPlayersWith_HeroC_Ratio_is_First_Column_ValuedHoleCards_AreValid :
PreFlopHandStrengthStatisticsSpecs
{
Establish context = () => {
_hero1.SetupGet(h => h.Sequences).Returns(new[] { "[1]C0.1".ToConvertedPokerRound() });
_hero2.SetupGet(h => h.Sequences).Returns(new[] { "[2]C0.1".ToConvertedPokerRound() });
_hero3.SetupGet(h => h.Sequences).Returns(new[] { "[3]C0.1".ToConvertedPokerRound() });
_valuedHoleCardsMock.SetupGet(v => v.AreValid).Returns(true);
};
}
[Subject(typeof(PreFlopHandStrengthStatistics), "BuildStatisticsFor, if valued holecards are always valid")]
public class given_hero1_has_known_cards_hero2_has_unknown_cards_and_hero3_has_empty_string :
Ctx_AllPlayersWith_HeroC_Ratio_is_First_Column_ValuedHoleCards_AreValid
{
Establish context = () => {
_hero1.SetupGet(h => h.Holecards).Returns(_validHoleCards);
_hero2.SetupGet(h => h.Holecards).Returns("?? ??");
_hero3.SetupGet(h => h.Holecards).Returns(string.Empty);
};
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, _validActionSequence);
It AnalyzablePlayersWithKnownCards_should_contain_hero1 =
() => _sut.AnalyzablePlayersWithKnownCards.ShouldContain(_hero1.Object);
It AnalyzablePlayersWithKnownCards_should_not_contain_hero2 =
() => _sut.AnalyzablePlayersWithKnownCards.ShouldNotContain(_hero2.Object);
It AnalyzablePlayersWithKnownCards_should_not_contain_hero3 =
() => _sut.AnalyzablePlayersWithKnownCards.ShouldNotContain(_hero3.Object);
}
[Subject(typeof(PreFlopHandStrengthStatistics), "BuildStatisticsFor, if valued holecards are always valid")]
public class given_hero1_and_hero2_have_known_cards_hero3_has_empty_string :
Ctx_AllPlayersWith_HeroC_Ratio_is_First_Column_ValuedHoleCards_AreValid
{
Establish context = () =>
{
_hero1.SetupGet(h => h.Holecards).Returns(_validHoleCards);
_hero2.SetupGet(h => h.Holecards).Returns(_validHoleCards);
_hero3.SetupGet(h => h.Holecards).Returns(string.Empty);
};
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, _validActionSequence);
It KnownCards_in_col_0_should_have_count_2 = () => _sut.KnownCards[0].Count().ShouldEqual(2);
It KnownCards_in_col_1_should_have_count_0 = () => _sut.KnownCards[1].Count().ShouldEqual(0);
}
[Subject(typeof(PreFlopHandStrengthStatistics), "BuildStatisticsFor")]
public class given_HeroC_as_ActionSequence : PreFlopHandStrengthStatisticsSpecs
{
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, ActionSequences.HeroC);
It RatiosUsed_should_equal_unraised_pot_calling_ratios = () => _sut.RatiosUsed.ShouldEqual(_unraisedPotCallingRatios);
}
[Subject(typeof(PreFlopHandStrengthStatistics), "BuildStatisticsFor")]
public class given_OppRHeroC_as_ActionSequence : PreFlopHandStrengthStatisticsSpecs
{
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, ActionSequences.OppRHeroC);
It RatiosUsed_should_equal_raised_pot_calling_ratios = () => _sut.RatiosUsed.ShouldEqual(_raisedPotCallingRatios);
}
[Subject(typeof(PreFlopHandStrengthStatistics), "BuildStatisticsFor")]
public class given_HeroR_as_ActionSequence : PreFlopHandStrengthStatisticsSpecs
{
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, ActionSequences.HeroR);
It RatiosUsed_should_equal_raise_size_keys = () => _sut.RatiosUsed.ShouldEqual(_raiseSizeKeys);
}
public abstract class Ctx_all_have_known_cards : PreFlopHandStrengthStatisticsSpecs
{
Establish context = () => {
_hero1.SetupGet(h => h.Holecards).Returns(_validHoleCards);
_hero2.SetupGet(h => h.Holecards).Returns(_validHoleCards);
_hero3.SetupGet(h => h.Holecards).Returns(_validHoleCards);
};
}
[Subject(typeof(PreFlopHandStrengthStatistics),
"BuildStatisticsFor, all have known cards and ActionSequence is HeroC, given 2 ratios for unraised pot")]
public class given_hero1_has_calling_ratio1_hero2_has_calling_ratio2_and_hero_3_has_calling_ratio_larger_than_the_last_one :
Ctx_all_have_known_cards
{
Establish context = () => {
_hero1.SetupGet(h => h.Sequences).Returns(new[] { "[1]C0.1".ToConvertedPokerRound() });
_hero2.SetupGet(h => h.Sequences).Returns(new[] { "[2]C0.2".ToConvertedPokerRound() });
// Hero3 has other players actions in his sequence, but it will still be found using his position as id
_hero3.SetupGet(h => h.Sequences).Returns(new[] { "[0]F,[1]C0.1,[2]C0.2,[3]C0.9".ToConvertedPokerRound() });
};
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, ActionSequences.HeroC);
It SortedAnalyzablePokerPlayers_should_have_same_length_as_there_are_items_in_unraised_pot_calling_ratios
= () => _sut.SortedAnalyzablePokerPlayersWithKnownCards.Length.ShouldEqual(_unraisedPotCallingRatios.Length);
It SortedAnalyzablePokerPlayers_at_col_0_should_contain_only_hero1
= () => _sut.SortedAnalyzablePokerPlayersWithKnownCards[0].ShouldContainOnly(_hero1.Object);
It SortedAnalyzablePokerPlayers_at_col_1_should_contain_only_hero2_and_hero3
= () => _sut.SortedAnalyzablePokerPlayersWithKnownCards[1].ShouldContainOnly(_hero2.Object, _hero3.Object);
}
[Subject(typeof(PreFlopHandStrengthStatistics), "BuildStatisticsFor")]
public class given_hero1_with_HeroC_has_cards_AsKs_ValuedHoleCards_AreValid : PreFlopHandStrengthStatisticsSpecs
{
const string HoleCards = "As Ks";
const int AverageChenValue = 1;
const int AverageSklanskyMalmuthGrouping = 11;
Establish context = () => {
_hero1.SetupGet(h => h.Holecards).Returns(HoleCards);
_hero1.SetupGet(h => h.Sequences).Returns(new[] { "[1]C0.1".ToConvertedPokerRound() });
_analyzablePokerPlayers = new[] { _hero1.Object };
_valuedHoleCardsMock.SetupGet(h => h.AreValid).Returns(true);
_valuedHoleCardsAverageMock.SetupGet(v => v.IsValid).Returns(true);
_valuedHoleCardsAverageMock.SetupGet(v => v.ChenValue).Returns(AverageChenValue);
_valuedHoleCardsAverageMock.SetupGet(v => v.SklanskyMalmuthGrouping).Returns(AverageSklanskyMalmuthGrouping);
};
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, ActionSequences.HeroC);
It should_initialize_valuedHoleCards_with_his_holecards = () => _valuedHoleCardsMock.Verify(h => h.InitializeWith(HoleCards));
It KnownCards_should_have_same_length_as_unraisedPotCallingRatios = () => _sut.KnownCards.Length.ShouldEqual(_unraisedPotCallingRatios.Length);
It should_add_valued_hole_cards_to_col_0_of_KnownCards = () => _sut.KnownCards[0].ShouldContain(_valuedHoleCardsMock.Object);
It should_initialize_the_average_valued_hole_cards_with_a_list_containing_the_valued_hole_cards = () =>
_valuedHoleCardsAverageMock.Verify(a => a.InitializeWith(Moq.It.Is<IEnumerable<IValuedHoleCards>>(l => l.Contains(_valuedHoleCardsMock.Object))));
It should_set_the_AverageChenValue_at_col_0_to_the_one_returned_by_the_valued_hole_cards_average
= () => _sut.AverageChenValues[0].ShouldEqual(AverageChenValue.ToString());
It should_set_the_AverageSklanskyMalmuthGrouping_at_col_0_to_the_one_returned_by_the_valued_hole_cards_average
= () => _sut.AverageSklanskyMalmuthGroupings[0].ShouldEqual(AverageSklanskyMalmuthGrouping.ToString());
}
[Subject(typeof(PreFlopHandStrengthStatistics), "BuildStatisticsFor")]
public class given_hero1_with_HeroC_has_cards_AsKs_ValuedHoleCards_AreInValid : PreFlopHandStrengthStatisticsSpecs
{
const string HoleCards = "As Ks";
Establish context = () => {
_hero1.SetupGet(h => h.Holecards).Returns(HoleCards);
_hero1.SetupGet(h => h.Sequences).Returns(new[] { "[1]C0.1".ToConvertedPokerRound() });
_analyzablePokerPlayers = new[] { _hero1.Object };
_valuedHoleCardsMock.SetupGet(h => h.AreValid).Returns(false);
_valuedHoleCardsAverageMock.SetupGet(v => v.IsValid).Returns(false);
};
Because of = () => _sut.BuildStatisticsFor(_analyzablePokerPlayers, ActionSequences.HeroC);
It should_not_add_valued_hole_cards_to_col_0_of_KnownCards = () => _sut.KnownCards[0].ShouldNotContain(_valuedHoleCardsMock.Object);
It should_initialize_the_average_valued_hole_cards_with_an_empty_list = () =>
_valuedHoleCardsAverageMock.Verify(a => a.InitializeWith(Moq.It.Is<IEnumerable<IValuedHoleCards>>(l => l.Count() == 0)));
It should_set_the_AverageChenValue_at_col_0_to_not_available
= () => _sut.AverageChenValues[0].ShouldEqual("na");
It should_set_the_AverageSklanskyMalmuthGrouping_at_col_0_to_not_available
= () => _sut.AverageSklanskyMalmuthGroupings[0].ShouldEqual("na");
}
}
public static class PreFlopHandStrengthStatisticsSpecsUtils
{
public static IConvertedPokerRound ToConvertedPokerRound(this string round)
{
return new PokerHandStringConverter().ConvertedRoundFrom(round);
}
}
}
| |
// Copyright (c) 2011 Morten Bakkedal
// This code is published under the MIT License.
using System;
using System.Diagnostics;
using FuncLib.Mathematics;
namespace FuncLib.DualNumbers
{
[Serializable]
[DebuggerStepThrough]
[DebuggerDisplay("{ToString(),nq}")]
public sealed class DualVector
{
private DualMatrix inner;
private DualVector(DualMatrix inner)
{
if (inner.Columns != 1)
{
throw new ArgumentException();
}
this.inner = inner;
}
public DualVector(DualNumber[] entries)
{
int n = entries.Length;
DualNumber[,] a = new DualNumber[n, 1];
for (int i = 0; i < n; i++)
{
a[i, 0] = entries[i];
}
inner = new DualMatrix(a);
}
public DualVector(Vector values)
: this(values, null)
{
}
public DualVector(Vector values, Vector[] gradients)
: this(values, gradients, null)
{
}
public DualVector(Vector values, Vector[] gradients, Vector[,] hessians)
{
int n = 0;
Matrix[] matrixGradients = null;
if (gradients != null)
{
n = gradients.Length;
matrixGradients = new Matrix[n];
for (int i = 0; i < n; i++)
{
if (gradients[i] == null)
{
throw new ArgumentNullException("gradients", "The gradients must be fully specified.");
}
matrixGradients[i] = (Matrix)gradients[i];
}
}
Matrix[,] matrixHessians = null;
if (hessians != null)
{
if (hessians.GetLength(0) != n || hessians.GetLength(1) != n)
{
throw new ArgumentException("Inconsistent number of derivatives.");
}
matrixHessians = new Matrix[n, n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (hessians[i, j] == null)
{
throw new ArgumentNullException("hessians", "The Hessians must be fully specified.");
}
matrixHessians[i, j] = (Matrix)hessians[i, j];
}
}
}
inner = new DualMatrix((Matrix)values, matrixGradients, matrixHessians);
}
public DualVector SetEntry(int index, DualNumber entry)
{
return new DualVector(inner.SetEntry(index, 0, entry));
}
public DualVector SetVector(int index, DualVector vector)
{
return new DualVector(inner.SetMatrix(index, 0, vector.inner));
}
public DualVector GetVector(int index, int length)
{
return new DualVector(inner.GetMatrix(index, 0, length, 1));
}
public Vector GetValues()
{
return new Vector(inner.GetValues());
}
public Vector GetGradients(int index)
{
return new Vector(inner.GetGradients(index));
}
public Vector GetHessians(int index1, int index2)
{
return new Vector(inner.GetHessians(index1, index2));
}
public DualNumber[] ToArray()
{
int n = Length;
DualNumber[] a = new DualNumber[n];
for (int i = 0; i < n; i++)
{
a[i] = inner[i, 0];
}
return a;
}
public override string ToString()
{
return inner.ToString();
}
public string ToString(string format)
{
return inner.ToString(format);
}
public static DualVector Zero(int length)
{
return new DualVector(DualMatrix.Zero(length, 1));
}
public static DualVector Basis(int length, int index)
{
return new DualVector(DualMatrix.Basis(length, 1, index, 0));
}
public static implicit operator DualVector(Vector a)
{
return new DualVector(a);
}
public static implicit operator DualMatrix(DualVector a)
{
return a.inner;
}
public static explicit operator DualVector(DualMatrix a)
{
if (a.Columns == 1)
{
return new DualVector(a);
}
if (a.Rows == 1)
{
// Requires copying of the references to DualNumber entries.
return new DualVector(DualMatrix.Transpose(a));
}
throw new InvalidCastException("The matrix has no vector representation.");
}
public static DualVector operator +(DualVector a, DualVector b)
{
return new DualVector(a.inner + b.inner);
}
public static DualVector operator +(DualVector a, DualNumber b)
{
return new DualVector(a.inner + b);
}
public static DualVector operator +(DualNumber a, DualVector b)
{
return b + a;
}
public static DualVector operator -(DualVector a, DualVector b)
{
return new DualVector(a.inner - b.inner);
}
public static DualVector operator -(DualVector a, DualNumber b)
{
return a + (-b);
}
public static DualVector operator -(DualNumber a, DualVector b)
{
return new DualVector(a - b.inner);
}
public static DualVector operator -(DualVector a)
{
return a * -1.0;
}
public static DualVector operator *(DualMatrix a, DualVector b)
{
return new DualVector(a * b.inner);
}
public static DualVector operator *(DualVector a, DualNumber b)
{
return new DualVector(a.inner * b);
}
public static DualVector operator *(DualNumber a, DualVector b)
{
return b * a;
}
public static DualVector operator /(DualVector vector, DualNumber scalar)
{
return vector * (1.0 / scalar);
}
public DualNumber this[int index]
{
get
{
return inner[index, 0];
}
}
public int Length
{
get
{
return inner.Rows;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace XNAGameOfLife
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// Resources
// Dynamic
SpriteFont _spriteFont;
Texture2D _pixel;
Texture2D _cellTextureBlack;
Texture2D _cellTextureRed;
Texture2D _cellTextureGrey;
// Static
Texture2D _frame;
Texture2D _pauseButton;
Texture2D _pauseButtonOver;
Texture2D _playButton;
Texture2D _playButtonOver;
Texture2D _zoomOutOver;
Texture2D _zoomInOver;
Texture2D _speedDownOver;
Texture2D _speedUpOver;
Texture2D _newOver;
// State
KeyboardState _keyboardStatePrevious;
MouseState _mouseStatePrevious;
PlayerIndex _currentPlayer;
int _minUpdate = 150;
double _lastUpdate = 0;
bool _paused = true;
// Data
Vector2 gameSize = new Vector2(800, 480);
// The number of times each pixel in the game is larger than a pixel on the screen
// Make sure this is always divisible by both the window width and height or the game will refuse to start
int pixelScale = 8;
// A pixelScale^2 2D array to hold the current game of life
Queue<int[,]> currentGame;
int setValue;
int blackBlocks = 0;
int redBlocks = 0;
int maxBlocks = 151;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = 1024;
graphics.PreferredBackBufferHeight = 480;
Content.RootDirectory = "Content";
TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 10);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
_currentPlayer = PlayerIndex.One;
if ((int)gameSize.X % pixelScale != 0 || (int)gameSize.Y % pixelScale != 0)
this.Exit();
this.IsMouseVisible = true;
currentGame = new Queue<int[,]>();
for (int i = 0; i < 10; i++)
currentGame.Enqueue(new int[(int)gameSize.X / pixelScale, (int)gameSize.Y / pixelScale]);
//currentGame = new int[((int)gameSize.X * (int)gameSize.Y) / (pixelScale * pixelScale)];
//oldGame = new int[(int)gameSize.X / pixelScale, (int)gameSize.Y / pixelScale];
//for (int y = 0; y < currentGame.GetLength(1); y++)
//{
// for (int x = 0; x < currentGame.GetLength(0); x++)
// {
// currentGame[x, y] = 1;
// }
//}
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
_spriteFont = Content.Load<SpriteFont>("SpriteFont1");
// Create black, singe pixel texture for drawing and such
_pixel = new Texture2D(GraphicsDevice, 1, 1);
_pixel.SetData<int>(new int[] { Color.Black.GetHashCode() });
// Generate our pixelScale * pixelScale cell texture
_cellTextureBlack = CreateTexture(Color.Black);
_cellTextureRed = CreateTexture(Color.Red);
_cellTextureGrey = CreateTexture(Color.LightGray);
// TODO: use this.Content to load your game content here
_frame = Content.Load<Texture2D>("frame");
_pauseButton = Content.Load<Texture2D>("pausebutton");
_pauseButtonOver = Content.Load<Texture2D>("pausebuttonover");
_playButton = Content.Load<Texture2D>("playbutton");
_playButtonOver = Content.Load<Texture2D>("playbuttonover");
_zoomOutOver = Content.Load<Texture2D>("zoomoutover");
_zoomInOver = Content.Load<Texture2D>("zoominover");
_speedDownOver = Content.Load<Texture2D>("speeddownover");
_speedUpOver = Content.Load<Texture2D>("speedupover");
_newOver = Content.Load<Texture2D>("newover");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
_lastUpdate += gameTime.ElapsedGameTime.TotalMilliseconds;
// Allows the game to exit
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
this.Exit();
}
else if (Mouse.GetState().LeftButton != ButtonState.Pressed)
{
if (Keyboard.GetState().IsKeyDown(Keys.Left))
_currentPlayer = PlayerIndex.One;
else if (Keyboard.GetState().IsKeyDown(Keys.Right))
_currentPlayer = PlayerIndex.Two;
}
if (this.IsActive)
{
if ((Keyboard.GetState().IsKeyDown(Keys.P) && !_keyboardStatePrevious.IsKeyDown(Keys.P))
|| ((Mouse.GetState().LeftButton == ButtonState.Released && _mouseStatePrevious.LeftButton == ButtonState.Pressed)
&& Mouse.GetState().X > gameSize.X && Mouse.GetState().Y > 0 && Mouse.GetState().Y <= 100))
_paused = !_paused;
int mouseX = Mouse.GetState().X;
int mouseY = Mouse.GetState().Y;
if (_paused &&
((Keyboard.GetState().IsKeyDown(Keys.OemPlus) && !_keyboardStatePrevious.IsKeyDown(Keys.OemPlus))
|| (Keyboard.GetState().IsKeyDown(Keys.OemMinus) && !_keyboardStatePrevious.IsKeyDown(Keys.OemMinus))
|| ((Mouse.GetState().LeftButton == ButtonState.Released && _mouseStatePrevious.LeftButton == ButtonState.Pressed)
&& Mouse.GetState().X > gameSize.X && Mouse.GetState().Y > 100 && Mouse.GetState().Y <= 200)))
{
int oldPixelScale = pixelScale;
int modifier = 1;
if (Mouse.GetState().LeftButton == ButtonState.Released && _mouseStatePrevious.LeftButton == ButtonState.Pressed)
{
if (Mouse.GetState().X < gameSize.X + 112)
{
modifier = -1;
}
}
else if (!Keyboard.GetState().IsKeyDown(Keys.OemPlus))
{
modifier = -1;
}
// This is the most confusing for loop that I've ever written
// Future me: Consider throwing yourself off a bridge if you need to understand this
for (int i = pixelScale + modifier; i > 0 && i * 2 < (int)gameSize.X && i * 2 < (int)gameSize.Y; i += modifier)
{
if ((int)gameSize.X % i == 0 && (int)gameSize.Y % i == 0)
{
pixelScale = i;
break;
}
}
if (pixelScale != oldPixelScale)
{
Rectangle newRect = new Rectangle();
newRect.X = 0;
newRect.Y = 0;
// If the number of cells on screen has gone down
if (pixelScale > oldPixelScale)
{
// Only copy the new amount of cells
newRect.Width = (int)gameSize.X / pixelScale;
newRect.Height = (int)gameSize.Y / pixelScale;
}
else
{
// Copy all cells
newRect.Width = currentGame.Last().GetLength(0);
newRect.Height = currentGame.Last().GetLength(1);
}
for (int i = 0; i < currentGame.Count; i++)
{
currentGame.Enqueue(ResizeArray(currentGame.Dequeue(), newRect, new Rectangle(0, 0, (int)gameSize.X / pixelScale, (int)gameSize.Y / pixelScale)));
}
_cellTextureBlack = CreateTexture(Color.Black);
_cellTextureRed = CreateTexture(Color.Red);
_cellTextureGrey = CreateTexture(Color.LightGray);
}
}
else if (Mouse.GetState().LeftButton == ButtonState.Pressed && _paused)
{
if ((_currentPlayer == PlayerIndex.One && mouseX < (gameSize.X / 2))
|| (_currentPlayer == PlayerIndex.Two && mouseX >= (gameSize.X / 2)))
{
if (mouseX > 0 && mouseX < (int)gameSize.X && mouseY > 0 && mouseY < (int)gameSize.Y)
{
int currentCellX = (int)(Mouse.GetState().X / pixelScale);
int currentCellY = (int)(Mouse.GetState().Y / pixelScale);
if (Mouse.GetState().LeftButton != _mouseStatePrevious.LeftButton)
{
setValue = (currentGame.Last()[currentCellX, currentCellY] == 0 ? (_currentPlayer == PlayerIndex.One ? 1 : 2) : 0);
}
if (currentGame.Last()[currentCellX, currentCellY] != setValue)
{
if (currentGame.Last()[currentCellX, currentCellY] == 0 || (_currentPlayer == PlayerIndex.One ? 1 : 2) == currentGame.Last()[currentCellX, currentCellY])
{
if (setValue == 0)
{
if (currentGame.Last()[currentCellX, currentCellY] == 1)
blackBlocks--;
else
redBlocks--;
}
else
{
if (setValue == 1)
blackBlocks++;
else
redBlocks++;
}
if (setValue == 0)
{
currentGame.Last()[currentCellX, currentCellY] = setValue;
}
else
{
if (setValue == 1)
{
if (blackBlocks < maxBlocks)
currentGame.Last()[currentCellX, currentCellY] = setValue;
else
blackBlocks--;
}
else
{
if (redBlocks < maxBlocks)
currentGame.Last()[currentCellX, currentCellY] = setValue;
else
redBlocks--;
}
}
}
}
}
}
}
else if (!_paused && _lastUpdate > _minUpdate)
{
_lastUpdate = 0;
blackBlocks = 0;
redBlocks = 0;
int width = currentGame.Last().GetLength(0);
int height = currentGame.Last().GetLength(1);
int[,] nextFrame = currentGame.Dequeue();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
nextFrame[x, y] = GetColour(currentGame.Last(), x, y);
if (nextFrame[x, y] == 1)
blackBlocks++;
else if (nextFrame[x, y] == 2)
redBlocks++;
}
}
currentGame.Enqueue(nextFrame);
//if (_lastTime + 10 < gameTime.TotalGameTime.TotalSeconds)
//{
// if (_lastValues.X == blackBlocks && _lastValues.Y == redBlocks)
// {
// this.Exit();
// }
// else
// {
// _lastValues.X = blackBlocks;
// _lastValues.Y = redBlocks;
// _lastTime = (int)gameTime.TotalGameTime.TotalSeconds;
// }
//}
}
if (Mouse.GetState().LeftButton == ButtonState.Released && _mouseStatePrevious.LeftButton == ButtonState.Pressed)
{
if (Mouse.GetState().X > gameSize.X && Mouse.GetState().X < graphics.PreferredBackBufferWidth)
{
if (Mouse.GetState().Y > 300 && Mouse.GetState().Y <= 400)
{
_paused = true;
redBlocks = 0;
blackBlocks = 0;
foreach (int[,] game in currentGame)
{
for (int y = 0; y < game.GetLength(1); y++)
{
for (int x = 0; x < game.GetLength(0); x++)
{
game[x, y] = 0;
}
}
}
}
else if (Mouse.GetState().Y > 200 && Mouse.GetState().Y <= 300)
{
if (Mouse.GetState().X < gameSize.X + 112)
{
_minUpdate += 50;
if (_minUpdate > 500)
_minUpdate = 500;
}
else
{
_minUpdate -= 50;
if (_minUpdate < 50)
_minUpdate = 50;
}
}
else if (Mouse.GetState().Y > 400 && Mouse.GetState().Y <= 480)
{
if (Mouse.GetState().X < gameSize.X + 112)
{
_currentPlayer = PlayerIndex.One;
}
else
{
_currentPlayer = PlayerIndex.Two;
}
}
}
}
_keyboardStatePrevious = Keyboard.GetState();
_mouseStatePrevious = Mouse.GetState();
}
for (int i = 0; i < currentGame.Count; i++)
{
for (int j = 0; j < currentGame.Count; j++)
{
if (i != j)
{
if (currentGame.ElementAt(i).Equals(currentGame.ElementAt(j)))
this.Exit();
}
}
}
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
if (!_paused && Mouse.GetState().X > 0 && Mouse.GetState().X < gameSize.X && Mouse.GetState().Y > 0
&& Mouse.GetState().Y < gameSize.Y && Mouse.GetState().LeftButton == ButtonState.Pressed)
GraphicsDevice.Clear(Color.Orange);
spriteBatch.Begin();
// Draw interface
// Draw GOL
for (int y = 0; y < currentGame.Last().GetLength(1); y++)
{
for (int x = 0; x < currentGame.Last().GetLength(0); x++)
{
if (currentGame.Last()[x, y] == 0 && (x % 2) == y % 2)
spriteBatch.Draw(_cellTextureGrey, new Vector2(x * pixelScale, y * pixelScale), Color.White);
if (currentGame.Last()[x, y] == 1)
spriteBatch.Draw(_cellTextureBlack, new Vector2(x * pixelScale, y * pixelScale), Color.White);
else if (currentGame.Last()[x, y] != 0)
spriteBatch.Draw(_cellTextureRed, new Vector2(x * pixelScale, y * pixelScale), Color.White);
}
}
spriteBatch.Draw(_frame, new Vector2(0, 0), Color.White);
if (_paused)
{
spriteBatch.Draw(_playButton, new Vector2(gameSize.X, 0), Color.White);
}
else
{
spriteBatch.Draw(_pauseButton, new Vector2(gameSize.X, 0), Color.White);
}
if (_mouseStatePrevious.LeftButton == ButtonState.Pressed)
{
if (_mouseStatePrevious.X > gameSize.X && _mouseStatePrevious.X < graphics.PreferredBackBufferWidth)
{
if (_mouseStatePrevious.Y > 0 && _mouseStatePrevious.Y <= 100)
{
if (_paused)
{
spriteBatch.Draw(_playButtonOver, new Vector2(gameSize.X, 0), Color.White);
}
else
{
spriteBatch.Draw(_pauseButtonOver, new Vector2(gameSize.X, 0), Color.White);
}
}
else if (_mouseStatePrevious.Y > 100 && _mouseStatePrevious.Y < 200)
{
if (_mouseStatePrevious.X - gameSize.X < 112)
spriteBatch.Draw(_zoomOutOver, new Vector2(gameSize.X, 100), Color.White);
else
spriteBatch.Draw(_zoomInOver, new Vector2(gameSize.X + 112, 100), Color.White);
}
else if (_mouseStatePrevious.Y > 200 && _mouseStatePrevious.Y < 300)
{
if (_mouseStatePrevious.X - gameSize.X < 112)
spriteBatch.Draw(_speedDownOver, new Vector2(gameSize.X, 200), Color.White);
else
spriteBatch.Draw(_speedUpOver, new Vector2(gameSize.X + 112, 200), Color.White);
}
else if (_mouseStatePrevious.Y > 300 && _mouseStatePrevious.Y < 400)
{
spriteBatch.Draw(_newOver, new Vector2(gameSize.X, 300), Color.White);
}
else if (_mouseStatePrevious.Y > 400 && _mouseStatePrevious.Y < 480 && _paused)
{
if (_mouseStatePrevious.X - gameSize.X < 112)
GraphicsDevice.Clear(Color.Black);
else
GraphicsDevice.Clear(Color.Red);
}
}
}
if (_paused)
{
spriteBatch.Draw(_cellTextureGrey, new Rectangle((int)gameSize.X + (_currentPlayer == PlayerIndex.One ? 0 : 112), 400, 112, 80), new Color(0, 128, 0, 50));
spriteBatch.Draw(_cellTextureGrey, new Rectangle((_currentPlayer == PlayerIndex.One ? 400 : 0), 0, 400, 480), new Color(10, 10, 10, 100));
if (Mouse.GetState().Y > 400 && Mouse.GetState().Y <= 480)
{
if (Mouse.GetState().X < gameSize.X + 112)
spriteBatch.Draw(_cellTextureGrey, new Rectangle((int)gameSize.X, 400, 112, 80), new Color(0, 128, 0, 70));
else
spriteBatch.Draw(_cellTextureGrey, new Rectangle((int)gameSize.X + 112, 400, 112, 80), new Color(0, 128, 0, 70));
}
}
spriteBatch.DrawString(_spriteFont, blackBlocks.ToString(), new Vector2(gameSize.X + 50, 425), Color.Black);
spriteBatch.DrawString(_spriteFont, redBlocks.ToString(), new Vector2(gameSize.X + 162, 425), Color.Red);
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
/*
* GetColour
* Previously GetNeighbours
* Calculates the number of neighbours for a cell
* and returns the new colour for it
*/
private int GetColour(int[,] array, int x, int y)
{
int cellNeighbours = 0;
int blackNeighbours = 0;
int redNeighbours = 0;
if (x > 0 && array[x - 1, y] != 0)
{
if (array[x - 1, y] == 1)
blackNeighbours++;
else
redNeighbours++;
}
if (x < array.GetLength(0) - 1 && array[x + 1, y] != 0)
{
if (array[x + 1, y] == 1)
blackNeighbours++;
else
redNeighbours++;
}
if (y > 0)
{
if (array[x, y - 1] != 0)
{
if (array[x, y - 1] == 1)
blackNeighbours++;
else
redNeighbours++;
}
if (x > 0 && array[x - 1, y - 1] != 0)
{
if (array[x - 1, y - 1] == 1)
blackNeighbours++;
else
redNeighbours++;
}
if (x < array.GetLength(0) - 1 && array[x + 1, y - 1] != 0)
{
if (array[x + 1, y - 1] == 1)
blackNeighbours++;
else
redNeighbours++;
}
}
if (y < array.GetLength(1) - 1)
{
if (array[x, y + 1] != 0)
{
if (array[x, y + 1] == 1)
blackNeighbours++;
else
redNeighbours++;
}
if (x > 0 && array[x - 1, y + 1] != 0)
{
if (array[x - 1, y + 1] == 1)
blackNeighbours++;
else
redNeighbours++;
}
if (x < array.GetLength(0) - 1 && array[x + 1, y + 1] != 0)
{
if (array[x + 1, y + 1] == 1)
blackNeighbours++;
else
redNeighbours++;
}
}
cellNeighbours = redNeighbours + blackNeighbours;
//if (current == 0)
//{
// if (cellNeighbours == 3)
// return 1;
// else
// return 0;
//}
//else
//{
// if (cellNeighbours < 2)
// return 0;
// else if (cellNeighbours < 4)
// return 1;
// else
// return 0;
//}
if (array[x, y] == 0)
{
if (cellNeighbours == 3)
{
return (blackNeighbours == redNeighbours ? 0 : (blackNeighbours > redNeighbours ? 1 : 2));
}
//else
//{
// return 0;
//}
}
else
{
if (cellNeighbours < 2)
{
return 0;
}
else if (cellNeighbours < 4)
{
return (blackNeighbours == redNeighbours ? 0 : (blackNeighbours > redNeighbours ? 1 : 2));
}
//else
//{
// return 0;
//}
}
return 0;
}
/*
* CreateTexture
* Returns the texture2D to use for each GoL cell
* can be any size, but is pixelScale * pixelScale by default
*/
private Texture2D CreateTexture(Color colour)
{
Texture2D newTexture = new Texture2D(GraphicsDevice, pixelScale, pixelScale);
int[] pixelTexture = new int[pixelScale * pixelScale];
int whiteColour = colour.GetHashCode();
for (int i = 0; i < pixelScale * pixelScale; i++)
{
pixelTexture[i] = whiteColour;
}
newTexture.SetData<int>(pixelTexture);
return newTexture;
}
/*
* DrawLine
* Scales a pixel square texture to create a line between point a and point b
*/
private void DrawLine(Vector2 a, Vector2 b)
{
}
/*
* ResizeArray
* Resizes a 2D int array
*/
private int[,] ResizeArray(int[,] source, Rectangle sourceRect, Rectangle destinationRect)
{
int[,] destination = new int[destinationRect.Width, destinationRect.Height];
for (int y = 0; y < sourceRect.Height; y++)
{
for (int x = 0; x < sourceRect.Width; x++)
{
destination[x, y] = source[x + sourceRect.X, y + sourceRect.Y];
}
}
return destination;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApi2.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
using NUnit.Framework;
using ClosedXML_Tests.Utils;
namespace ClosedXML_Tests.Excel
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestFixture]
public class ColumnTests
{
[Test]
public void ColumnUsed()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Cell(2, 1).SetValue("Test");
ws.Cell(3, 1).SetValue("Test");
IXLRangeColumn fromColumn = ws.Column(1).ColumnUsed();
Assert.AreEqual("A2:A3", fromColumn.RangeAddress.ToStringRelative());
IXLRangeColumn fromRange = ws.Range("A1:A5").FirstColumn().ColumnUsed();
Assert.AreEqual("A2:A3", fromRange.RangeAddress.ToStringRelative());
}
[Test]
public void CopyColumn()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().SetValue("Test").Style.Font.SetBold();
ws.FirstColumn().CopyTo(ws.Column(2));
Assert.IsTrue(ws.Cell("B1").Style.Font.Bold);
}
[Test]
public void InsertingColumnsBefore1()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Columns("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Column(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLColumn column1 = ws.Column(1);
IXLColumn column2 = ws.Column(2);
IXLColumn column3 = ws.Column(3);
IXLColumn columnIns = ws.Column(1).InsertColumnsBefore(1).First();
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Column(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Column(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, ws.Column(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Column(3).Cell(2).GetString());
Assert.AreEqual(ws.Style.Fill.BackgroundColor, columnIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, columnIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(ws.Style.Fill.BackgroundColor, columnIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, column2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", column2.Cell(2).GetString());
}
[Test]
public void InsertingColumnsBefore2()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Columns("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Column(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLColumn column1 = ws.Column(1);
IXLColumn column2 = ws.Column(2);
IXLColumn column3 = ws.Column(3);
IXLColumn columnIns = ws.Column(2).InsertColumnsBefore(1).First();
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Column(3).Cell(2).GetString());
Assert.AreEqual(XLColor.Red, columnIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, columnIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, columnIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, column2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", column2.Cell(2).GetString());
}
[Test]
public void InsertingColumnsBefore3()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
ws.Columns("1,3").Style.Fill.SetBackgroundColor(XLColor.Red);
ws.Column(2).Style.Fill.SetBackgroundColor(XLColor.Yellow);
ws.Cell(2, 2).SetValue("X").Style.Fill.SetBackgroundColor(XLColor.Green);
IXLColumn column1 = ws.Column(1);
IXLColumn column2 = ws.Column(2);
IXLColumn column3 = ws.Column(3);
IXLColumn columnIns = ws.Column(3).InsertColumnsBefore(1).First();
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(1).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(2).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(2).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(2).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, ws.Column(3).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, ws.Column(3).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, ws.Column(4).Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", ws.Column(2).Cell(2).GetString());
Assert.AreEqual(XLColor.Yellow, columnIns.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, columnIns.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, columnIns.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column1.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Green, column2.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Yellow, column2.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(1).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(2).Style.Fill.BackgroundColor);
Assert.AreEqual(XLColor.Red, column3.Cell(3).Style.Fill.BackgroundColor);
Assert.AreEqual("X", column2.Cell(2).GetString());
}
[Test]
public void NoColumnsUsed()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
Int32 count = 0;
foreach (IXLColumn row in ws.ColumnsUsed())
count++;
foreach (IXLRangeColumn row in ws.Range("A1:C3").ColumnsUsed())
count++;
Assert.AreEqual(0, count);
}
[Test]
public void UngroupFromAll()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Columns(1, 2).Group();
ws.Columns(1, 2).Ungroup(true);
}
[Test]
public void LastColumnUsed()
{
IXLWorksheet ws = new XLWorkbook().AddWorksheet("Sheet1");
ws.Cell("A1").Value = "A1";
ws.Cell("B1").Value = "B1";
ws.Cell("A2").Value = "A2";
var lastCoUsed = ws.LastColumnUsed().ColumnNumber();
Assert.AreEqual(2, lastCoUsed);
}
[Test]
public void NegativeColumnNumberIsInvalid()
{
var ws = new XLWorkbook().AddWorksheet("Sheet1") as XLWorksheet;
var column = new XLColumn(ws, -1);
Assert.IsFalse(column.RangeAddress.IsValid);
}
}
}
| |
// 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.Runtime.Serialization;
using System.Xml.Serialization;
namespace SerializationTestTypes
{
[DataContract]
public class ObjectContainer
{
[DataMember]
private object _data;
[DataMember]
private object _data2;
public ObjectContainer(object input)
{
_data = input;
_data2 = _data;
}
public object Data
{
get { return _data; }
}
public object Data2
{
get { return _data2; }
}
}
[DataContract(Name = "EmptyDCType", Namespace = "http://www.Default.com")]
public class EmptyDCType
{
}
[KnownType(typeof(EmptyDCType))]
public class POCOObjectContainer
{
public POCOObjectContainer() { Data = new EmptyDCType(); }
public object Data;
[IgnoreDataMember]
public object NonSerializedData;
public POCOObjectContainer(object input)
{
Data = input;
}
}
[DataContract]
public class Alpha
{
[DataMember]
public Person person = new Person();
}
[DataContract]
[KnownType(typeof(CharClass))]
public class Beta
{
[DataMember]
public object unknown1 = new CharClass();
}
[DataContract]
public class Charlie
{
[DataMember]
public object unknown2 = new SerializationTestTypes.Employee();
}
[DataContract(Namespace = "NonExistNamespace")]
public class Employee
{
[DataMember]
public DateTime dateHired;
[DataMember]
public decimal salary;
[DataMember]
public Individual individual;
}
public class Individual
{
public string firstName;
public string lastName;
public int age;
public object data;
public object data1;
public Individual() { }
}
[DataContract]
public class Wireformat1
{
[DataMember]
public Alpha alpha = new Alpha();
[DataMember]
public Beta beta = new Beta();
[DataMember]
public Charlie charlie = new Charlie();
}
[DataContract]
public class Wireformat2
{
[DataMember]
public Beta beta1 = new Beta();
[DataMember]
public Charlie charlie = new Charlie();
[DataMember]
public Beta beta2 = new Beta();
}
[DataContract]
public class Wireformat3
{
[DataMember]
public Charlie charlie1 = new Charlie();
[DataMember]
public Beta beta = new Beta();
[DataMember]
public Charlie charlie2 = new Charlie();
}
[DataContract]
public class DCRVariations
{
[DataMember]
public object unknownType1;
[DataMember]
public object unknownType2;
}
[DataContract]
public class CustomClass
{
[DataMember()]
private object[] knownTypes;
[DataMember()]
private object[] dataContractResolverTypes;
[DataMember()]
public virtual object[] KnownTypes
{
get { return knownTypes; }
set { knownTypes = value; }
}
[DataMember()]
public virtual object[] DataContractResolverTypes
{
get { return dataContractResolverTypes; }
set { dataContractResolverTypes = value; }
}
}
[DataContract]
public class DefaultCollections
{
[DataMember]
private ArrayList _arrayList = new ArrayList() { new Person() };
[DataMember]
private Dictionary<int, object> _dictionary = new Dictionary<int, object>() { { 001, new CharClass() } };
[DataMember]
private Hashtable _hashtable = new Hashtable() { { "one", new Version1() } };
[DataMember]
private object[] _singleDimArray = new object[] { new Employee() };
}
[DataContract(Name = "Car", Namespace = "TestingVersionTolerance")]
public class Version1
{
[DataMember]
public object make;
public Version1()
{
make = "Chevrolet";
}
}
public class TypeNotFound { };
public class TypeLibraryManager
{
private List<Type> _primitiveTypeList = new List<Type>();
private List<Type> _collectionTypeList = new List<Type>();
private List<Type> _selfRefAndCyclesTypeList = new List<Type>();
private List<Type> _iobjectRefTypeList = new List<Type>();
private List<Type> _sampleTypeList = new List<Type>();
private List<Type> _isReferenceTypeList = new List<Type>();
private List<Type> _allTypesList = new List<Type>();
private List<Type> _fxPrimitivesInCollectionList = new List<Type>();
private Hashtable _allTypeHashTable = new Hashtable();
public Hashtable AllTypesHashtable
{
get
{
if (_allTypeHashTable.Count == 0)
{
_allTypeHashTable = new Hashtable();
foreach (Type t in AllTypesList)
{
_allTypeHashTable.Add(t.FullName, t);
}
}
return _allTypeHashTable;
}
}
public List<Type> FxPrimitivesInCollectionList
{
get
{
if (_fxPrimitivesInCollectionList.Count == 0)
{
_fxPrimitivesInCollectionList.Add(typeof(List<bool>));
_fxPrimitivesInCollectionList.Add(typeof(List<byte>));
_fxPrimitivesInCollectionList.Add(typeof(List<byte[]>));
_fxPrimitivesInCollectionList.Add(typeof(List<char>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.DateTime>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.DBNull>));
_fxPrimitivesInCollectionList.Add(typeof(List<decimal>));
_fxPrimitivesInCollectionList.Add(typeof(List<double>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Guid>));
_fxPrimitivesInCollectionList.Add(typeof(List<short>));
_fxPrimitivesInCollectionList.Add(typeof(List<int>));
_fxPrimitivesInCollectionList.Add(typeof(List<long>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Boolean>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Byte>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Char>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.DateTime>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Decimal>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Double>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Guid>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Int16>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Int32>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Int64>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.SByte>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.Single>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.TimeSpan>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.UInt16>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.UInt32>>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.UInt64>>));
_fxPrimitivesInCollectionList.Add(typeof(List<sbyte>));
_fxPrimitivesInCollectionList.Add(typeof(List<float>));
_fxPrimitivesInCollectionList.Add(typeof(List<string>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.TimeSpan>));
_fxPrimitivesInCollectionList.Add(typeof(List<ushort>));
_fxPrimitivesInCollectionList.Add(typeof(List<uint>));
_fxPrimitivesInCollectionList.Add(typeof(List<ulong>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Xml.XmlElement>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Xml.XmlNode[]>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.DateTimeOffset>));
_fxPrimitivesInCollectionList.Add(typeof(List<System.Nullable<System.DateTimeOffset>>));
}
return _fxPrimitivesInCollectionList;
}
}
public List<Type> AllTypesList
{
get
{
if (_allTypesList.Count == 0)
{
_allTypesList.AddRange(this.FxPrimitivesInCollectionList);
_allTypesList.AddRange(this.EnumsStructList);
_allTypesList.AddRange(this.SelfRefAndCyclesTypeList);
_allTypesList.AddRange(this.IsReferenceTypeList);
_allTypesList.AddRange(this.IObjectRefTypeList);
_allTypesList.AddRange(this.CollectionsTypeList);
_allTypesList.AddRange(this.SampleTypeList);
}
return _allTypesList;
}
}
public List<Type> IsReferenceTypeList
{
get
{
if (_isReferenceTypeList.Count == 0)
{
_isReferenceTypeList.Add(typeof(TestInheritence9));
_isReferenceTypeList.Add(typeof(SimpleDC));
_isReferenceTypeList.Add(typeof(SimpleDCWithSimpleDMRef));
_isReferenceTypeList.Add(typeof(SimpleDCWithRef));
_isReferenceTypeList.Add(typeof(ContainsSimpleDCWithRef));
_isReferenceTypeList.Add(typeof(SimpleDCWithIsRequiredFalse));
_isReferenceTypeList.Add(typeof(Mixed1));
_isReferenceTypeList.Add(typeof(SerIser));
_isReferenceTypeList.Add(typeof(DCVersioned1));
_isReferenceTypeList.Add(typeof(DCVersioned2));
_isReferenceTypeList.Add(typeof(DCVersionedContainer1));
_isReferenceTypeList.Add(typeof(DCVersionedContainerVersion1));
_isReferenceTypeList.Add(typeof(DCVersionedContainerVersion2));
_isReferenceTypeList.Add(typeof(DCVersionedContainerVersion3));
_isReferenceTypeList.Add(typeof(BaseDC));
_isReferenceTypeList.Add(typeof(BaseSerializable));
_isReferenceTypeList.Add(typeof(DerivedDC));
_isReferenceTypeList.Add(typeof(DerivedSerializable));
_isReferenceTypeList.Add(typeof(DerivedDCIsRefBaseSerializable));
_isReferenceTypeList.Add(typeof(DerivedDCBaseSerializable));
_isReferenceTypeList.Add(typeof(Derived2DC));
_isReferenceTypeList.Add(typeof(BaseDCNoIsRef));
_isReferenceTypeList.Add(typeof(DerivedPOCOBaseDCNOISRef));
_isReferenceTypeList.Add(typeof(DerivedIXmlSerializable_POCOBaseDCNOISRef));
_isReferenceTypeList.Add(typeof(DerivedCDCFromBaseDC));
_isReferenceTypeList.Add(typeof(Derived2Serializable));
_isReferenceTypeList.Add(typeof(Derived2SerializablePositive));
_isReferenceTypeList.Add(typeof(Derived2Derived2Serializable));
_isReferenceTypeList.Add(typeof(Derived3Derived2Serializable));
_isReferenceTypeList.Add(typeof(Derived31Derived2SerializablePOCO));
_isReferenceTypeList.Add(typeof(Derived4Derived2Serializable));
_isReferenceTypeList.Add(typeof(Derived5Derived2Serializable));
_isReferenceTypeList.Add(typeof(Derived6Derived2SerializablePOCO));
_isReferenceTypeList.Add(typeof(BaseWithIsRefTrue));
_isReferenceTypeList.Add(typeof(DerivedNoIsRef));
_isReferenceTypeList.Add(typeof(DerivedNoIsRef2));
_isReferenceTypeList.Add(typeof(DerivedNoIsRef3));
_isReferenceTypeList.Add(typeof(DerivedNoIsRef4));
_isReferenceTypeList.Add(typeof(DerivedNoIsRef5));
_isReferenceTypeList.Add(typeof(DerivedNoIsRefWithIsRefTrue6));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefFalse));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefFalse2));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefFalse3));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefFalse4));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefFalse5));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefTrue6));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefTrueExplicit));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefTrueExplicit2));
_isReferenceTypeList.Add(typeof(BaseNoIsRef));
_isReferenceTypeList.Add(typeof(DerivedWithIsRefFalseExplicit));
_isReferenceTypeList.Add(typeof(TestInheritence));
_isReferenceTypeList.Add(typeof(TestInheritence91));
_isReferenceTypeList.Add(typeof(TestInheritence5));
_isReferenceTypeList.Add(typeof(TestInheritence10));
_isReferenceTypeList.Add(typeof(TestInheritence2));
_isReferenceTypeList.Add(typeof(TestInheritence11));
_isReferenceTypeList.Add(typeof(TestInheritence3));
_isReferenceTypeList.Add(typeof(TestInheritence16));
_isReferenceTypeList.Add(typeof(TestInheritence4));
_isReferenceTypeList.Add(typeof(TestInheritence12));
_isReferenceTypeList.Add(typeof(TestInheritence6));
_isReferenceTypeList.Add(typeof(TestInheritence7));
_isReferenceTypeList.Add(typeof(TestInheritence14));
_isReferenceTypeList.Add(typeof(TestInheritence8));
}
return _isReferenceTypeList;
}
}
public List<Type> SelfRefAndCyclesTypeList
{
get
{
if (_selfRefAndCyclesTypeList.Count == 0)
{
_selfRefAndCyclesTypeList.Add(typeof(SelfRef1));
_selfRefAndCyclesTypeList.Add(typeof(SelfRef1DoubleDM));
_selfRefAndCyclesTypeList.Add(typeof(SelfRef2));
_selfRefAndCyclesTypeList.Add(typeof(SelfRef3));
_selfRefAndCyclesTypeList.Add(typeof(Cyclic1));
_selfRefAndCyclesTypeList.Add(typeof(Cyclic2));
_selfRefAndCyclesTypeList.Add(typeof(CyclicA));
_selfRefAndCyclesTypeList.Add(typeof(CyclicB));
_selfRefAndCyclesTypeList.Add(typeof(CyclicC));
_selfRefAndCyclesTypeList.Add(typeof(CyclicD));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD1));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD2));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD3));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD4));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD5));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD6));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD7));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCD8));
_selfRefAndCyclesTypeList.Add(typeof(CyclicABCDNoCycles));
_selfRefAndCyclesTypeList.Add(typeof(A1));
_selfRefAndCyclesTypeList.Add(typeof(B1));
_selfRefAndCyclesTypeList.Add(typeof(C1));
_selfRefAndCyclesTypeList.Add(typeof(BB1));
_selfRefAndCyclesTypeList.Add(typeof(BBB1));
}
return _selfRefAndCyclesTypeList;
}
}
public List<Type> IObjectRefTypeList
{
get
{
if (_iobjectRefTypeList.Count == 0)
{
_iobjectRefTypeList.Add(typeof(DCExplicitInterfaceIObjRef));
_iobjectRefTypeList.Add(typeof(DCIObjRef));
_iobjectRefTypeList.Add(typeof(SerExplicitInterfaceIObjRefReturnsPrivate));
_iobjectRefTypeList.Add(typeof(SerIObjRefReturnsPrivate));
_iobjectRefTypeList.Add(typeof(DCExplicitInterfaceIObjRefReturnsPrivate));
_iobjectRefTypeList.Add(typeof(DCIObjRefReturnsPrivate));
}
return _iobjectRefTypeList;
}
}
public List<Type> EnumsStructList
{
get
{
if (_primitiveTypeList.Count == 0)
{
_primitiveTypeList.Add(typeof(Person));
_primitiveTypeList.Add(typeof(CharClass));
_primitiveTypeList.Add(typeof(AllTypes));
_primitiveTypeList.Add(typeof(AllTypes2));
_primitiveTypeList.Add(typeof(DictContainer));
_primitiveTypeList.Add(typeof(ListContainer));
_primitiveTypeList.Add(typeof(ArrayContainer));
_primitiveTypeList.Add(typeof(EnumContainer1));
_primitiveTypeList.Add(typeof(EnumContainer2));
_primitiveTypeList.Add(typeof(EnumContainer3));
_primitiveTypeList.Add(typeof(WithStatic));
_primitiveTypeList.Add(typeof(DerivedFromPriC));
_primitiveTypeList.Add(typeof(EmptyDC));
_primitiveTypeList.Add(typeof(Base));
_primitiveTypeList.Add(typeof(Derived));
_primitiveTypeList.Add(typeof(list));
_primitiveTypeList.Add(typeof(Arrays));
_primitiveTypeList.Add(typeof(Array3));
_primitiveTypeList.Add(typeof(Properties));
_primitiveTypeList.Add(typeof(HaveNS));
_primitiveTypeList.Add(typeof(OutClass));
_primitiveTypeList.Add(typeof(Temp));
_primitiveTypeList.Add(typeof(Array22));
_primitiveTypeList.Add(typeof(Person2));
_primitiveTypeList.Add(typeof(BoxedPrim));
_primitiveTypeList.Add(typeof(MyEnum));
_primitiveTypeList.Add(typeof(MyPrivateEnum1));
_primitiveTypeList.Add(typeof(MyPrivateEnum2));
_primitiveTypeList.Add(typeof(MyPrivateEnum3));
_primitiveTypeList.Add(typeof(MyEnum1));
_primitiveTypeList.Add(typeof(MyEnum2));
_primitiveTypeList.Add(typeof(MyEnum3));
_primitiveTypeList.Add(typeof(MyEnum4));
_primitiveTypeList.Add(typeof(MyEnum7));
_primitiveTypeList.Add(typeof(MyEnum8));
_primitiveTypeList.Add(typeof(SeasonsEnumContainer));
}
return _primitiveTypeList;
}
}
public List<Type> CollectionsTypeList
{
get
{
if (_collectionTypeList.Count == 0)
{
_collectionTypeList = new List<Type>();
_collectionTypeList.Add(typeof(ContainsLinkedList));
_collectionTypeList.Add(typeof(SimpleCDC));
_collectionTypeList.Add(typeof(SimpleCDC2));
_collectionTypeList.Add(typeof(ContainsSimpleCDC));
_collectionTypeList.Add(typeof(DMInCollection1));
_collectionTypeList.Add(typeof(DMInCollection2));
_collectionTypeList.Add(typeof(DMInDict1));
_collectionTypeList.Add(typeof(DMWithRefInCollection1));
_collectionTypeList.Add(typeof(DMWithRefInCollection2));
_collectionTypeList.Add(typeof(DMWithRefInDict1));
}
return _collectionTypeList;
}
}
public List<Type> SampleTypeList
{
get
{
if (_sampleTypeList.Count == 0)
{
_sampleTypeList = new List<Type>();
_sampleTypeList.Add(typeof(TypeNotFound));
_sampleTypeList.Add(typeof(EmptyDCType));
_sampleTypeList.Add(typeof(ObjectContainer));
_sampleTypeList.Add(typeof(POCOObjectContainer));
_sampleTypeList.Add(typeof(CircularLink));
_sampleTypeList.Add(typeof(CircularLinkDerived));
_sampleTypeList.Add(typeof(KT1Base));
_sampleTypeList.Add(typeof(KT1Derived));
_sampleTypeList.Add(typeof(KT2Base));
_sampleTypeList.Add(typeof(KT3BaseKTMReturnsPrivateType));
_sampleTypeList.Add(typeof(KT2Derived));
_sampleTypeList.Add(typeof(CB1));
_sampleTypeList.Add(typeof(ArrayListWithCDCFilledPublicTypes));
_sampleTypeList.Add(typeof(ArrayListWithCDCFilledWithMixedTypes));
_sampleTypeList.Add(typeof(CollectionBaseWithCDCFilledPublicTypes));
_sampleTypeList.Add(typeof(CollectionBaseWithCDCFilledWithMixedTypes));
_sampleTypeList.Add(typeof(DCHashtableContainerPublic));
_sampleTypeList.Add(typeof(DCHashtableContainerMixedTypes));
_sampleTypeList.Add(typeof(CustomGenericContainerPrivateType1));
_sampleTypeList.Add(typeof(CustomGenericContainerPrivateType2));
_sampleTypeList.Add(typeof(CustomGenericContainerPrivateType3));
_sampleTypeList.Add(typeof(CustomGenericContainerPrivateType4));
_sampleTypeList.Add(typeof(CustomGenericContainerPublicType1));
_sampleTypeList.Add(typeof(CustomGenericContainerPublicType2));
_sampleTypeList.Add(typeof(CustomGenericContainerPublicType3));
_sampleTypeList.Add(typeof(CustomGenericContainerPublicType4));
_sampleTypeList.Add(typeof(CustomGeneric1<KT1Base>));
_sampleTypeList.Add(typeof(CustomGeneric2<KT1Base, NonDCPerson>));
_sampleTypeList.Add(typeof(GenericContainer));
_sampleTypeList.Add(typeof(GenericBase<NonDCPerson>));
_sampleTypeList.Add(typeof(GenericBase2<KT1Base, NonDCPerson>));
_sampleTypeList.Add(typeof(SimpleBase));
_sampleTypeList.Add(typeof(SimpleBaseDerived));
_sampleTypeList.Add(typeof(SimpleBaseDerived2));
_sampleTypeList.Add(typeof(SimpleBaseContainer));
_sampleTypeList.Add(typeof(DCListPrivateTContainer2));
_sampleTypeList.Add(typeof(DCListPrivateTContainer));
_sampleTypeList.Add(typeof(DCListPublicTContainer));
_sampleTypeList.Add(typeof(DCListMixedTContainer));
_sampleTypeList.Add(typeof(SampleListImplicitWithDC));
_sampleTypeList.Add(typeof(SampleListImplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleListImplicitWithCDC));
_sampleTypeList.Add(typeof(SampleListExplicitWithDC));
_sampleTypeList.Add(typeof(SampleListExplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleListExplicitWithCDC));
_sampleTypeList.Add(typeof(SampleListExplicitWithCDCContainsPrivateDC));
_sampleTypeList.Add(typeof(SampleListTImplicitWithDC));
_sampleTypeList.Add(typeof(SampleListTImplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleListTImplicitWithCDC));
_sampleTypeList.Add(typeof(SampleListTExplicitWithDC));
_sampleTypeList.Add(typeof(SampleListTExplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleListTExplicitWithCDC));
_sampleTypeList.Add(typeof(SampleListTExplicitWithCDCContainsPublicDCClassPrivateDM));
_sampleTypeList.Add(typeof(SampleListTExplicitWithCDCContainsPrivateDC));
_sampleTypeList.Add(typeof(SampleICollectionTImplicitWithDC));
_sampleTypeList.Add(typeof(SampleICollectionTImplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleICollectionTImplicitWithCDC));
_sampleTypeList.Add(typeof(SampleICollectionTExplicitWithDC));
_sampleTypeList.Add(typeof(SampleICollectionTExplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleICollectionTExplicitWithCDC));
_sampleTypeList.Add(typeof(SampleICollectionTExplicitWithCDCContainsPrivateDC));
_sampleTypeList.Add(typeof(SampleIEnumerableTImplicitWithDC));
_sampleTypeList.Add(typeof(SampleIEnumerableTImplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleIEnumerableTImplicitWithCDC));
_sampleTypeList.Add(typeof(SampleIEnumerableTExplicitWithDC));
_sampleTypeList.Add(typeof(SampleIEnumerableTExplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleIEnumerableTExplicitWithCDC));
_sampleTypeList.Add(typeof(SampleIEnumerableTExplicitWithCDCContainsPrivateDC));
_sampleTypeList.Add(typeof(SampleICollectionImplicitWithDC));
_sampleTypeList.Add(typeof(SampleICollectionImplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleICollectionImplicitWithCDC));
_sampleTypeList.Add(typeof(SampleICollectionExplicitWithDC));
_sampleTypeList.Add(typeof(SampleICollectionExplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleICollectionExplicitWithCDC));
_sampleTypeList.Add(typeof(SampleICollectionExplicitWithCDCContainsPrivateDC));
_sampleTypeList.Add(typeof(SampleIEnumerableImplicitWithDC));
_sampleTypeList.Add(typeof(SampleIEnumerableImplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleIEnumerableImplicitWithCDC));
_sampleTypeList.Add(typeof(SampleIEnumerableExplicitWithDC));
_sampleTypeList.Add(typeof(SampleIEnumerableExplicitWithoutDC));
_sampleTypeList.Add(typeof(SampleIEnumerableExplicitWithCDC));
_sampleTypeList.Add(typeof(SampleIEnumerableExplicitWithCDCContainsPrivateDC));
_sampleTypeList.Add(typeof(MyIDictionaryContainsPublicDC));
_sampleTypeList.Add(typeof(MyIDictionaryContainsPublicDCExplicit));
_sampleTypeList.Add(typeof(MyIDictionaryContainsPrivateDC));
_sampleTypeList.Add(typeof(MyGenericIDictionaryKVContainsPublicDC));
_sampleTypeList.Add(typeof(MyGenericIDictionaryKVContainsPublicDCExplicit));
_sampleTypeList.Add(typeof(MyGenericIDictionaryKVContainsPrivateDC));
_sampleTypeList.Add(typeof(DCDictionaryPrivateKTContainer));
_sampleTypeList.Add(typeof(DCDictionaryPublicKTContainer));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer1));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer2));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer3));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer4));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer5));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer6));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer7));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer8));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer9));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer10));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer11));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer12));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer13));
_sampleTypeList.Add(typeof(DCDictionaryMixedKTContainer14));
_sampleTypeList.Add(typeof(PublicDC));
_sampleTypeList.Add(typeof(PublicDCDerivedPublic));
_sampleTypeList.Add(typeof(DC));
_sampleTypeList.Add(typeof(DCWithReadOnlyField));
_sampleTypeList.Add(typeof(IReadWriteXmlWriteBinHex_EqualityDefined));
_sampleTypeList.Add(typeof(PrivateDefaultCtorIXmlSerializables));
_sampleTypeList.Add(typeof(PublicIXmlSerializablesWithPublicSchemaProvider));
_sampleTypeList.Add(typeof(PublicExplicitIXmlSerializablesWithPublicSchemaProvider));
_sampleTypeList.Add(typeof(PublicIXmlSerializablesWithPrivateSchemaProvider));
_sampleTypeList.Add(typeof(PublicDCClassPublicDM));
_sampleTypeList.Add(typeof(PublicDCClassPrivateDM));
_sampleTypeList.Add(typeof(PublicDCClassInternalDM));
_sampleTypeList.Add(typeof(PublicDCClassMixedDM));
_sampleTypeList.Add(typeof(PublicDCClassPublicDM_DerivedDCClassPublic));
_sampleTypeList.Add(typeof(PublicDCClassPrivateDM_DerivedDCClassPublic));
_sampleTypeList.Add(typeof(PublicDCClassPublicDM_DerivedDCClassPublicContainsPrivateDM));
_sampleTypeList.Add(typeof(Prop_PublicDCClassPublicDM_PublicDCClassPrivateDM));
_sampleTypeList.Add(typeof(Prop_SetPrivate_PublicDCClassPublicDM_PublicDCClassPrivateDM));
_sampleTypeList.Add(typeof(Prop_GetPrivate_PublicDCClassPublicDM_PublicDCClassPrivateDM));
_sampleTypeList.Add(typeof(Prop_PublicDCClassPublicDM));
_sampleTypeList.Add(typeof(Prop_PublicDCClassPrivateDM));
_sampleTypeList.Add(typeof(Prop_PublicDCClassInternalDM));
_sampleTypeList.Add(typeof(Prop_PublicDCClassMixedDM));
_sampleTypeList.Add(typeof(Prop_PublicDCClassPublicDM_DerivedDCClassPublic));
_sampleTypeList.Add(typeof(Prop_PublicDCClassPrivateDM_DerivedDCClassPublic));
_sampleTypeList.Add(typeof(Prop_PublicDCClassPublicDM_DerivedDCClassPublicContainsPrivateDM));
_sampleTypeList.Add(typeof(Prop_SetPrivate_PublicDCClassPublicDM));
_sampleTypeList.Add(typeof(Prop_GetPrivate_PublicDCClassPublicDM));
_sampleTypeList.Add(typeof(Derived_Override_Prop_All_Public));
_sampleTypeList.Add(typeof(Derived_Override_Prop_Private));
_sampleTypeList.Add(typeof(Derived_Override_Prop_GetPrivate_All_Public));
_sampleTypeList.Add(typeof(Derived_Override_Prop_GetPrivate_Private));
_sampleTypeList.Add(typeof(DC1_Version1));
_sampleTypeList.Add(typeof(DC2_Version1));
_sampleTypeList.Add(typeof(DC2_Version4));
_sampleTypeList.Add(typeof(DC2_Version5));
_sampleTypeList.Add(typeof(DC3_Version1));
_sampleTypeList.Add(typeof(DC3_Version2));
_sampleTypeList.Add(typeof(DC3_Version3));
_sampleTypeList.Add(typeof(CallBackSample_OnSerializing_Public));
_sampleTypeList.Add(typeof(CallBackSample_OnSerialized_Public));
_sampleTypeList.Add(typeof(CallBackSample_OnDeserializing_Public));
_sampleTypeList.Add(typeof(CallBackSample_OnDeserialized_Public));
_sampleTypeList.Add(typeof(CallBackSample_OnSerializing));
_sampleTypeList.Add(typeof(CallBackSample_OnSerialized));
_sampleTypeList.Add(typeof(CallBackSample_OnDeserializing));
_sampleTypeList.Add(typeof(CallBackSample_OnDeserialized));
_sampleTypeList.Add(typeof(CallBackSample_IDeserializationCallback));
_sampleTypeList.Add(typeof(CallBackSample_IDeserializationCallback_Explicit));
_sampleTypeList.Add(typeof(CallBackSample_OnDeserialized_Private_Base));
_sampleTypeList.Add(typeof(CallBackSample_OnDeserialized_Public_Derived));
_sampleTypeList.Add(typeof(CDC_Possitive));
_sampleTypeList.Add(typeof(CDC_PrivateAdd));
_sampleTypeList.Add(typeof(Base_Possitive_VirtualAdd));
_sampleTypeList.Add(typeof(CDC_NewAddToPrivate));
_sampleTypeList.Add(typeof(CDC_PrivateDefaultCtor));
_sampleTypeList.Add(typeof(NonDCPerson));
_sampleTypeList.Add(typeof(PersonSurrogated));
_sampleTypeList.Add(typeof(DCSurrogate));
_sampleTypeList.Add(typeof(SerSurrogate));
_sampleTypeList.Add(typeof(DCSurrogateExplicit));
_sampleTypeList.Add(typeof(SerSurrogateExplicit));
_sampleTypeList.Add(typeof(DCSurrogateReturnPrivate));
_sampleTypeList.Add(typeof(SerSurrogateReturnPrivate));
_sampleTypeList.Add(typeof(NullableContainerContainsValue));
_sampleTypeList.Add(typeof(NullableContainerContainsNull));
_sampleTypeList.Add(typeof(NullablePrivateContainerContainsValue));
_sampleTypeList.Add(typeof(NullablePrivateContainerContainsNull));
_sampleTypeList.Add(typeof(NullablePrivateDataInDMContainerContainsValue));
_sampleTypeList.Add(typeof(NullablePrivateDataInDMContainerContainsNull));
_sampleTypeList.Add(typeof(DCPublicDatasetPublic));
_sampleTypeList.Add(typeof(DCPublicDatasetPrivate));
_sampleTypeList.Add(typeof(SerPublicDatasetPublic));
_sampleTypeList.Add(typeof(SerPublicDatasetPrivate));
_sampleTypeList.Add(typeof(CustomGeneric2<NonDCPerson>));
_sampleTypeList.Add(typeof(DTOContainer));
}
return _sampleTypeList;
}
}
}
public static class DCRUtils
{
public static bool CompareIObjectRefTypes(object serialized, object deSerialized)
{
Dictionary<DataContract, List<RefData>> alreadyRefdValues = ObjectRefUtil.GetReferenceCounts(serialized);
Dictionary<DataContract, List<RefData>> alreadyRefdValues2 = ObjectRefUtil.GetReferenceCounts(deSerialized);
if (!ObjectRefUtil.IsEqual(alreadyRefdValues, alreadyRefdValues2))
{
return false;
}
return true;
}
}
public class RefData
{
public object Data;
public int RefCount = 0;
public RefData(object data)
{
Data = data;
}
public override bool Equals(object obj)
{
RefData other = obj as RefData;
if (other == null) return false;
return (object.ReferenceEquals(this.Data, other.Data));
}
public override int GetHashCode()
{
if (Data != null)
{
return Data.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
}
public class ObjectRefUtil
{
public static Dictionary<DataContract, List<RefData>> GetReferenceCounts(object data)
{
Dictionary<DataContract, List<RefData>> nonRefdValues = new Dictionary<DataContract, List<RefData>>();
return GetReferenceCounts(data, ref nonRefdValues);
}
public static Dictionary<DataContract, List<RefData>> GetReferenceCounts(object data, ref Dictionary<DataContract, List<RefData>> nonRefdValues)
{
Dictionary<DataContract, List<RefData>> alreadyRefdValues = new Dictionary<DataContract, List<RefData>>();
Type type = data.GetType();
DataContract dataContract = DataContract.GetDataContract(type, supportCollectionDataContract);
s_refStack.Clear();
FindAndAddRefd(data, dataContract, ref alreadyRefdValues, ref nonRefdValues);
return alreadyRefdValues;
}
public static bool IsEqual(Dictionary<DataContract, List<RefData>> alreadyRefdValues1, Dictionary<DataContract, List<RefData>> alreadyRefdValues2)
{
if (alreadyRefdValues1.Count != alreadyRefdValues2.Count) return false;
foreach (KeyValuePair<DataContract, List<RefData>> kp in alreadyRefdValues1)
{
if (alreadyRefdValues2.ContainsKey(kp.Key))
{
if (alreadyRefdValues2[kp.Key].Count != kp.Value.Count)
{
return false;
}
for (int i = 0; i < kp.Value.Count; i++)
{
if (alreadyRefdValues2[kp.Key][i].RefCount != kp.Value[i].RefCount)
{
return false;
}
}
}
else
{
return false;
}
}
return true;
}
private static Stack<RefData> s_refStack = new Stack<RefData>();
/// <summary>
/// </summary>
/// <param name="data"></param>
/// <param name="dataContract"></param>
/// <param name="alreadyRefdValues"></param>
/// <param name="nonRefdValues"></param>
private static void FindAndAddRefd(object data, DataContract dataContract, ref Dictionary<DataContract, List<RefData>> alreadyRefdValues
, ref Dictionary<DataContract, List<RefData>> nonRefdValues)
{
RefData refData = new RefData(data);
FindRefUpdateRef(refData, dataContract, ref alreadyRefdValues, ref nonRefdValues);
if (s_refStack.Contains(refData))
{
return;
}
else
{
s_refStack.Push(refData);
}
FindRefHandleMembers(data, dataContract, ref alreadyRefdValues, ref nonRefdValues);
s_refStack.Pop();
}
public static bool supportCollectionDataContract = true;
private static void FindRefUpdateRef(RefData refData, DataContract dataContract, ref Dictionary<DataContract, List<RefData>> alreadyRefdValues, ref Dictionary<DataContract, List<RefData>> nonRefdValues)
{
if (dataContract.IsReference)
{
if (alreadyRefdValues.ContainsKey(dataContract))
{
if (!alreadyRefdValues[dataContract].Contains(refData))
{
alreadyRefdValues[dataContract].Add(refData);
}
else
{
alreadyRefdValues[dataContract][alreadyRefdValues[dataContract].IndexOf(refData)].RefCount++;
}
}
else
{
List<RefData> list = new List<RefData>();
list.Add(refData);
alreadyRefdValues.Add(dataContract, list);
}
}
else if (!(dataContract is PrimitiveDataContract))
{
if (nonRefdValues.ContainsKey(dataContract))
{
if (!nonRefdValues[dataContract].Contains(refData))
{
nonRefdValues[dataContract].Add(refData);
}
else
{
nonRefdValues[dataContract][nonRefdValues[dataContract].IndexOf(refData)].RefCount++;
}
}
else
{
List<RefData> list = new List<RefData>();
list.Add(refData);
nonRefdValues.Add(dataContract, list);
}
}
}
private static void FindRefHandleMembers(object data, DataContract dataContract, ref Dictionary<DataContract, List<RefData>> alreadyRefdValues, ref Dictionary<DataContract, List<RefData>> nonRefdValues)
{
if (dataContract is ClassDataContract)
{
ClassDataContract classContract = dataContract as ClassDataContract;
foreach (DataMember member in classContract.Members)
{
object memberData = member.GetMemberValue(data);
if (memberData != null)
{
FindAndAddRefd(memberData, DataContract.GetDataContract(memberData.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
}
}
}
else if (dataContract is ArrayDataContract)
{
ArrayDataContract arrayContract = dataContract as ArrayDataContract;
foreach (object obj in (IEnumerable)data)
{
if (obj != null)
{
FindAndAddRefd(obj, DataContract.GetDataContract(obj.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
}
}
}
else if (dataContract is CollectionDataContract)
{
FindRefHandleCollectionDataContractMembers(data, dataContract, ref alreadyRefdValues, ref nonRefdValues);
}
else if (dataContract is EnumDataContract || dataContract is PrimitiveDataContract)
{
//Nothing to do
}
else
{
throw new Exception("TestDriver Exception: Type Not Supported");
}
}
private static void FindRefHandleCollectionDataContractMembers(object data, DataContract dataContract, ref Dictionary<DataContract, List<RefData>> alreadyRefdValues, ref Dictionary<DataContract, List<RefData>> nonRefdValues)
{
CollectionDataContract collectionContract = dataContract as CollectionDataContract;
if (!collectionContract.IsDictionary)
{
foreach (object obj in (IEnumerable)data)
{
if (obj != null)
{
FindAndAddRefd(obj, DataContract.GetDataContract(obj.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
}
}
}
else
{
IDictionary dictionary = data as IDictionary;
if (dictionary != null)
{
foreach (object key in dictionary.Keys)
{
if (key != null)
{
FindAndAddRefd(key, DataContract.GetDataContract(key.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
}
}
foreach (object value in dictionary.Values)
{
if (value != null)
{
FindAndAddRefd(value, DataContract.GetDataContract(value.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
}
}
}
else
{
if (collectionContract.GetEnumeratorMethod != null)
{
object dictEnumObj = null;
try
{
dictEnumObj = collectionContract.GetEnumeratorMethod.Invoke(data, new object[] { });
}
catch (Exception) { }
IDictionaryEnumerator dictEnum = dictEnumObj as IDictionaryEnumerator;
if (dictEnum != null)
{
while (dictEnum.MoveNext())
{
FindAndAddRefd(dictEnum.Key, DataContract.GetDataContract(dictEnum.Key.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
}
dictEnum.Reset();
while (dictEnum.MoveNext())
{
if (dictEnum.Value != null)
{
FindAndAddRefd(dictEnum.Value, DataContract.GetDataContract(dictEnum.Value.GetType(), supportCollectionDataContract), ref alreadyRefdValues, ref nonRefdValues);
}
}
}
}
else
{
throw new Exception("TestDriver Exception: Dictionary CollectionDataCotnract Type Not Supported");
}
}
}
}
}
}
| |
using System.Globalization;
using System.Numerics;
using Fractions;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace k8s.Models
{
/// <summary>
/// port https://github.com/kubernetes/apimachinery/blob/master/pkg/api/resource/quantity.go to c#
/// Quantity is a fixed-point representation of a number.
/// It provides convenient marshaling/unmarshaling in JSON and YAML,
/// in addition to String() and Int64() accessors.
/// The serialization format is:
/// quantity ::= signedNumber suffix
/// (Note that suffix may be empty, from the "" case in decimalSI.)
/// digit ::= 0 | 1 | ... | 9
/// digits ::= digit | digitdigits
/// number ::= digits | digits.digits | digits. | .digits
/// sign ::= "+" | "-"
/// signedNumber ::= number | signnumber
/// suffix ::= binarySI | decimalExponent | decimalSI
/// binarySI ::= Ki | Mi | Gi | Ti | Pi | Ei
/// (International System of units; See: http:///physics.nist.gov/cuu/Units/binary.html)
/// decimalSI ::= m | "" | k | M | G | T | P | E
/// (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
/// decimalExponent ::= "e" signedNumber | "E" signedNumber
/// No matter which of the three exponent forms is used, no quantity may represent
/// a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal
/// places. Numbers larger or more precise will be capped or rounded up.
/// (E.g.: 0.1m will rounded up to 1m.)
/// This may be extended in the future if we require larger or smaller quantities.
/// When a Quantity is parsed from a string, it will remember the type of suffix
/// it had, and will use the same type again when it is serialized.
/// Before serializing, Quantity will be put in "canonical form".
/// This means that Exponent/suffix will be adjusted up or down (with a
/// corresponding increase or decrease in Mantissa) such that:
/// a. No precision is lost
/// b. No fractional digits will be emitted
/// c. The exponent (or suffix) is as large as possible.
/// The sign will be omitted unless the number is negative.
/// Examples:
/// 1.5 will be serialized as "1500m"
/// 1.5Gi will be serialized as "1536Mi"
/// NOTE: We reserve the right to amend this canonical format, perhaps to
/// allow 1.5 to be canonical.
/// TODO: Remove above disclaimer after all bikeshedding about format is over,
/// or after March 2015.
/// Note that the quantity will NEVER be internally represented by a
/// floating point number. That is the whole point of this exercise.
/// Non-canonical values will still parse as long as they are well formed,
/// but will be re-emitted in their canonical form. (So always use canonical
/// form, or don't diff.)
/// This format is intended to make it difficult to use these numbers without
/// writing some sort of special handling code in the hopes that that will
/// cause implementors to also use a fixed point implementation.
/// </summary>
[JsonConverter(typeof(QuantityConverter))]
public partial class ResourceQuantity : IYamlConvertible
{
public enum SuffixFormat
{
/// <summary>
/// e.g., 12e6
/// </summary>
DecimalExponent,
/// <summary>
/// e.g., 12Mi (12 * 2^20)
/// </summary>
BinarySI,
/// <summary>
/// e.g., 12M (12 * 10^6)
/// </summary>
DecimalSI,
}
public static readonly decimal MaxAllowed = (decimal)BigInteger.Pow(2, 63) - 1;
private static readonly char[] SuffixChars = "eEinumkKMGTP".ToCharArray();
private Fraction _unitlessValue;
public ResourceQuantity(decimal n, int exp, SuffixFormat format)
{
_unitlessValue = Fraction.FromDecimal(n) * Fraction.Pow(10, exp);
Format = format;
}
public SuffixFormat Format { get; private set; }
public string CanonicalizeString()
{
return CanonicalizeString(Format);
}
public override string ToString()
{
return CanonicalizeString();
}
protected bool Equals(ResourceQuantity other)
{
return Format == other?.Format && _unitlessValue.Equals(other._unitlessValue);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((ResourceQuantity)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int)Format * 397) ^ _unitlessValue.GetHashCode();
}
}
//
// CanonicalizeString = go version CanonicalizeBytes
// CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity).
//
// Note about BinarySI:
// * If q.Format is set to BinarySI and q.Amount represents a non-zero value between
// -1 and +1, it will be emitted as if q.Format were DecimalSI.
// * Otherwise, if q.Format is set to BinarySI, fractional parts of q.Amount will be
// rounded up. (1.1i becomes 2i.)
public string CanonicalizeString(SuffixFormat suffixFormat)
{
if (suffixFormat == SuffixFormat.BinarySI)
{
if (_unitlessValue > -1024 && _unitlessValue < 1024)
{
return Suffixer.AppendMaxSuffix(_unitlessValue, SuffixFormat.DecimalSI);
}
if (HasMantissa(_unitlessValue))
{
return Suffixer.AppendMaxSuffix(_unitlessValue, SuffixFormat.DecimalSI);
}
}
return Suffixer.AppendMaxSuffix(_unitlessValue, suffixFormat);
}
// ctor
partial void CustomInit()
{
if (Value == null)
{
// No value has been defined, initialize to 0.
_unitlessValue = new Fraction(0);
Format = SuffixFormat.BinarySI;
return;
}
var value = Value.Trim();
var si = value.IndexOfAny(SuffixChars);
if (si == -1)
{
si = value.Length;
}
var literal = Fraction.FromString(value.Substring(0, si), CultureInfo.InvariantCulture);
var suffixer = new Suffixer(value.Substring(si));
_unitlessValue = literal.Multiply(Fraction.Pow(suffixer.Base, suffixer.Exponent));
Format = suffixer.Format;
if (Format == SuffixFormat.BinarySI && _unitlessValue > Fraction.FromDecimal(MaxAllowed))
{
_unitlessValue = Fraction.FromDecimal(MaxAllowed);
}
}
private static bool HasMantissa(Fraction value)
{
if (value.IsZero)
{
return false;
}
return BigInteger.Remainder(value.Numerator, value.Denominator) > 0;
}
/// <inheritdoc/>
public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer)
{
if (expectedType != typeof(ResourceQuantity))
{
throw new ArgumentOutOfRangeException(nameof(expectedType));
}
if (parser?.Current is Scalar)
{
Value = ((Scalar)parser.Current).Value;
parser.MoveNext();
CustomInit();
}
}
/// <inheritdoc/>
public void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
{
emitter?.Emit(new Scalar(ToString()));
}
public static implicit operator decimal(ResourceQuantity v)
{
return v?.ToDecimal() ?? 0;
}
public static implicit operator ResourceQuantity(decimal v)
{
return new ResourceQuantity(v, 0, SuffixFormat.DecimalExponent);
}
private sealed class Suffixer
{
private static readonly IReadOnlyDictionary<string, (int, int)> BinSuffixes =
new Dictionary<string, (int, int)>
{
// Don't emit an error when trying to produce
// a suffix for 2^0.
{ "", (2, 0) },
{ "Ki", (2, 10) },
{ "Mi", (2, 20) },
{ "Gi", (2, 30) },
{ "Ti", (2, 40) },
{ "Pi", (2, 50) },
{ "Ei", (2, 60) },
};
private static readonly IReadOnlyDictionary<string, (int, int)> DecSuffixes =
new Dictionary<string, (int, int)>
{
{ "n", (10, -9) },
{ "u", (10, -6) },
{ "m", (10, -3) },
{ "", (10, 0) },
{ "k", (10, 3) },
{ "M", (10, 6) },
{ "G", (10, 9) },
{ "T", (10, 12) },
{ "P", (10, 15) },
{ "E", (10, 18) },
};
public Suffixer(string suffix)
{
// looked up
{
if (DecSuffixes.TryGetValue(suffix, out var be))
{
(Base, Exponent) = be;
Format = SuffixFormat.DecimalSI;
return;
}
}
{
if (BinSuffixes.TryGetValue(suffix, out var be))
{
(Base, Exponent) = be;
Format = SuffixFormat.BinarySI;
return;
}
}
if (char.ToLower(suffix[0]) == 'e')
{
Base = 10;
Exponent = int.Parse(suffix.Substring(1));
Format = SuffixFormat.DecimalExponent;
return;
}
throw new ArgumentException("unable to parse quantity's suffix");
}
public SuffixFormat Format { get; }
public int Base { get; }
public int Exponent { get; }
public static string AppendMaxSuffix(Fraction value, SuffixFormat format)
{
if (value.IsZero)
{
return "0";
}
switch (format)
{
case SuffixFormat.DecimalExponent:
{
var minE = -9;
var lastv = Roundup(value * Fraction.Pow(10, -minE));
for (var exp = minE; ; exp += 3)
{
var v = value * Fraction.Pow(10, -exp);
if (HasMantissa(v))
{
break;
}
minE = exp;
lastv = v;
}
if (minE == 0)
{
return $"{(decimal)lastv}";
}
return $"{(decimal)lastv}e{minE}";
}
case SuffixFormat.BinarySI:
return AppendMaxSuffix(value, BinSuffixes);
case SuffixFormat.DecimalSI:
return AppendMaxSuffix(value, DecSuffixes);
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
private static string AppendMaxSuffix(Fraction value, IReadOnlyDictionary<string, (int, int)> suffixes)
{
var min = suffixes.First();
var suffix = min.Key;
var lastv = Roundup(value * Fraction.Pow(min.Value.Item1, -min.Value.Item2));
foreach (var kv in suffixes.Skip(1))
{
var v = value * Fraction.Pow(kv.Value.Item1, -kv.Value.Item2);
if (HasMantissa(v))
{
break;
}
suffix = kv.Key;
lastv = v;
}
return $"{(decimal)lastv}{suffix}";
}
private static Fraction Roundup(Fraction lastv)
{
var round = BigInteger.DivRem(lastv.Numerator, lastv.Denominator, out var remainder);
if (!remainder.IsZero)
{
lastv = round + 1;
}
return lastv;
}
}
public int ToInt32()
{
return _unitlessValue.ToInt32();
}
public long ToInt64()
{
return _unitlessValue.ToInt64();
}
public uint ToUInt32()
{
return _unitlessValue.ToUInt32();
}
public ulong ToUInt64()
{
return _unitlessValue.ToUInt64();
}
public BigInteger ToBigInteger()
{
return _unitlessValue.ToBigInteger();
}
public decimal ToDecimal()
{
return _unitlessValue.ToDecimal();
}
public double ToDouble()
{
return _unitlessValue.ToDouble();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using CoreAnimation;
using CoreGraphics;
using Foundation;
using UIKit;
namespace FilterDemoFramework {
public partial class FilterView : UIView {
public static readonly float DefaultMinHertz = 12f;
public static readonly float DefaultMaxHertz = 22050f;
const int logBase = 2;
const float leftMargin = 54f;
const float rightMargin = 10f;
const float bottomMargin = 40f;
const int numDBLines = 4;
const int defaultGain = 20;
const int gridLineCount = 11;
const float labelWidth = 40f;
const int maxNumberOfResponseFrequencies = 1024;
CGPoint editPoint = CGPoint.Empty;
bool touchDown;
CAShapeLayer curveLayer;
List<double> frequencies;
readonly List <CATextLayer> dbLabels = new List <CATextLayer> ();
readonly List <CATextLayer> frequencyLabels = new List<CATextLayer> ();
readonly List <CALayer> dbLines = new List <CALayer> ();
readonly List <CALayer> freqLines = new List<CALayer> ();
readonly List <CALayer> controls = new List<CALayer> ();
readonly CALayer containerLayer = new CALayer ();
readonly CALayer graphLayer = new CALayer ();
public IFilterViewDelegate Delegate { get; set;}
float resonance;
public float Resonance {
get {
return resonance;
}
set {
resonance = value;
// Clamp the resonance to min/max values.
if (resonance > defaultGain)
resonance = defaultGain;
else if (resonance < -defaultGain)
resonance = -defaultGain;
editPoint.Y = NMath.Floor (GetLocationForDbValue (Resonance));
}
}
float frequency = DefaultMinHertz;
public float Frequency {
get {
return frequency;
}
set {
frequency = value;
if (value > DefaultMaxHertz)
frequency = DefaultMaxHertz;
else if (value < DefaultMinHertz)
frequency = DefaultMinHertz;
editPoint.X = NMath.Floor (GetLocationForFrequencyValue (Frequency));
}
}
public FilterView (IntPtr handle) : base (handle)
{
}
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
base.TouchesEnded (touches, evt);
var firstTouch = touches.Cast<UITouch> ().FirstOrDefault ();
if (firstTouch == null)
return;
var pointOfTouch = firstTouch.LocationInView (this);
pointOfTouch.Y += bottomMargin;
if (graphLayer.Contains (pointOfTouch))
editPoint = ProcessTouch (pointOfTouch);
touchDown = false;
UpdateFrequenciesAndResonance ();
}
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
base.TouchesMoved (touches, evt);
var firstTouch = touches.Cast<UITouch> ().FirstOrDefault ();
if (firstTouch == null)
return;
var pointOfTouch = firstTouch.LocationInView (this);
pointOfTouch.Y += bottomMargin;
if (graphLayer.Contains (pointOfTouch)) {
touchDown = true;
editPoint = pointOfTouch;
UpdateFrequenciesAndResonance ();
}
}
public override void AwakeFromNib ()
{
base.AwakeFromNib ();
var scale = UIScreen.MainScreen.Scale;
containerLayer.Name = "container";
containerLayer.AnchorPoint = CGPoint.Empty;
containerLayer.Frame = new CGRect (CGPoint.Empty, Layer.Bounds.Size);
containerLayer.Bounds = containerLayer.Frame;
containerLayer.ContentsScale = scale;
Layer.AddSublayer (containerLayer);
graphLayer.Name = "graph background";
graphLayer.BorderColor = UIColor.DarkGray.CGColor;
graphLayer.BorderWidth = 1f;
graphLayer.BackgroundColor = UIColor.FromWhiteAlpha (0.88f, 1f).CGColor;
graphLayer.Bounds = new CGRect (0, 0, Layer.Frame.Width - leftMargin, Layer.Frame.Height - bottomMargin);
graphLayer.Position = new CGPoint (leftMargin, 0);
graphLayer.AnchorPoint = CGPoint.Empty;
graphLayer.ContentsScale = scale;
containerLayer.AddSublayer (graphLayer);
Layer.ContentsScale = scale;
CreateDbLabelsAndLines ();
CreateFrequencyLabelsAndLines ();
CreateControlPoint ();
}
public override void TouchesCancelled (NSSet touches, UIEvent evt)
{
base.TouchesCancelled (touches, evt);
touchDown = false;
}
public double [] GetFrequencyData ()
{
if (frequencies != null)
return frequencies.ToArray ();
var width = graphLayer.Bounds.Width;
var rightEdge = width + leftMargin;
var pixelRatio = (int)Math.Ceiling (width / maxNumberOfResponseFrequencies);
nfloat location = leftMargin;
var locationsCount = maxNumberOfResponseFrequencies;
if (pixelRatio <= 1) {
pixelRatio = 1;
locationsCount = (int)width;
}
frequencies = new List <double> ();
for (int i = 0; i < locationsCount; i++) {
if (location > rightEdge)
frequencies.Add (DefaultMaxHertz);
else {
var frequencyTmp = GetFrequencyValue (location);
if (frequencyTmp > DefaultMaxHertz)
frequencyTmp = DefaultMaxHertz;
location += (nfloat)pixelRatio;
frequencies.Add (frequencyTmp);
}
}
return frequencies.ToArray ();
}
public void SetMagnitudes (double [] magnitudeData)
{
if (curveLayer == null) {
curveLayer = new CAShapeLayer ();
curveLayer.FillColor = UIColor.FromRGBA (0.31f, 0.37f, 0.73f, 0.8f).CGColor;
graphLayer.AddSublayer (curveLayer);
}
var bezierPath = new CGPath ();
var width = graphLayer.Bounds.Width;
bezierPath.MoveToPoint (leftMargin, graphLayer.Frame.Height + bottomMargin);
float lastDbPos = 0f;
float location = leftMargin;
var frequencyCount = frequencies?.Count ?? 0;
var pixelRatio = (int)(Math.Ceiling (width / frequencyCount));
for (int i = 0; i < frequencyCount; i++) {
var dbValue = 20 * Math.Log10 (magnitudeData [i]);
float dbPos;
if (dbValue < -defaultGain)
dbPos = GetLocationForDbValue (-defaultGain);
else if (dbValue > defaultGain)
dbPos = GetLocationForDbValue (defaultGain);
else
dbPos = GetLocationForDbValue ((float)dbValue);
if (Math.Abs (lastDbPos - dbPos) >= 0.1)
bezierPath.AddLineToPoint (location, dbPos);
lastDbPos = dbPos;
location += pixelRatio;
if (location > width + graphLayer.Frame.X) {
location = (float)width + (float)graphLayer.Frame.X;
break;
}
}
bezierPath.AddLineToPoint (location, graphLayer.Frame.Y + graphLayer.Frame.Height + bottomMargin);
bezierPath.CloseSubpath ();
CATransaction.Begin ();
CATransaction.DisableActions = true;
curveLayer.Path = bezierPath;
CATransaction.Commit ();
UpdateControls (true);
}
public float GetLocationForDbValue (float value)
{
var step = graphLayer.Frame.Height / (defaultGain * 2);
var location = (value + defaultGain) * step;
return (float)(graphLayer.Frame.Height - location + bottomMargin);
}
float GetLocationForFrequencyValue (float value)
{
var pixelIncrement = graphLayer.Frame.Width / gridLineCount;
var number = value / DefaultMinHertz;
var location = GetLogValue (number, logBase) * pixelIncrement;
return (float)Math.Floor (location + graphLayer.Frame.X) + 0.5f;
}
float GetDbValue (nfloat location)
{
var step = graphLayer.Frame.Height / (defaultGain * 2);
return (float)(-(((location - bottomMargin) / step) - defaultGain));
}
void CreateDbLabelsAndLines ()
{
int value;
var scale = Layer.ContentsScale;
for (int index = -numDBLines; index <= numDBLines; index++) {
value = index * (defaultGain / numDBLines);
if (index >= -numDBLines && index <= numDBLines) {
var labelLayer = new CATextLayer {
String = string.Format ("{0} db", value),
Name = index.ToString (),
FontSize = 14,
ContentsScale = scale,
ForegroundColor = UIColor.FromWhiteAlpha (0.1f, 1f).CGColor,
AlignmentMode = CATextLayer.AlignmentRight
};
labelLayer.SetFont (UIFont.SystemFontOfSize (14).Name);
dbLabels.Add (labelLayer);
containerLayer.AddSublayer (labelLayer);
var lineLayer = new CALayer {
BackgroundColor = index == 0 ?
UIColor.FromWhiteAlpha (0.65f, 1f).CGColor : UIColor.FromWhiteAlpha (0.8f, 1f).CGColor
};
dbLines.Add (lineLayer);
graphLayer.AddSublayer (lineLayer);
}
}
}
void CreateFrequencyLabelsAndLines ()
{
float value;
bool firstK = true;
var scale = Layer.ContentsScale;
for (int index = 0; index <= gridLineCount; index++) {
value = GetValue ((float)index);
var labelLayer = new CATextLayer {
ForegroundColor = UIColor.FromWhiteAlpha (0.1f, 1f).CGColor,
FontSize = 14,
AlignmentMode = CATextLayer.AlignmentCenter,
ContentsScale = scale,
AnchorPoint = CGPoint.Empty
};
labelLayer.SetFont (UIFont.SystemFontOfSize (14).Name);
frequencyLabels.Add (labelLayer);
if (index > 0 && index < gridLineCount) {
var lineLayer = new CALayer {
BackgroundColor = UIColor.FromWhiteAlpha (0.8f, 1f).CGColor
};
freqLines.Add (lineLayer);
graphLayer.AddSublayer (lineLayer);
var s = GetString (value);
if (value >= 1000 && firstK) {
s += "K";
firstK = false;
}
labelLayer.String = s;
} else if (index == 0)
labelLayer.String = string.Format ("{0} Hz", GetString (value));
else
labelLayer.String = string.Format ("{0} K", GetString (DefaultMaxHertz));
containerLayer.AddSublayer (labelLayer);
}
}
void CreateControlPoint ()
{
var controlColor = touchDown ? TintColor.CGColor : UIColor.DarkGray.CGColor;
var lineLayer = new CALayer {
BackgroundColor = controlColor,
Name = "x"
};
controls.Add (lineLayer);
graphLayer.AddSublayer (lineLayer);
lineLayer = new CALayer {
BackgroundColor = controlColor,
Name = "y"
};
controls.Add (lineLayer);
graphLayer.AddSublayer (lineLayer);
var circleLayer = new CALayer {
BorderColor = controlColor,
BorderWidth = 2f,
CornerRadius = 3f,
Name = "point"
};
controls.Add (circleLayer);
graphLayer.AddSublayer (circleLayer);
}
void UpdateControls (bool refreshColor)
{
var color = touchDown ? TintColor.CGColor : UIColor.DarkGray.CGColor;
CATransaction.Begin ();
CATransaction.DisableActions = true;
foreach (var layer in controls) {
switch (layer.Name) {
case "point":
layer.Frame = new CGRect (editPoint.X - 3, editPoint.Y - 3, 7f, 7f).Integral ();
layer.Position = editPoint;
if (refreshColor)
layer.BorderColor = color;
break;
case "x":
layer.Frame = new CGRect (graphLayer.Frame.X, NMath.Floor (editPoint.Y + 0.5f), graphLayer.Frame.Width, 1f);
if (refreshColor)
layer.BackgroundColor = color;
break;
case "y":
layer.Frame = new CGRect (NMath.Floor (editPoint.X) + 0.5f, bottomMargin, 1f, graphLayer.Frame.Height);
if (refreshColor)
layer.BackgroundColor = color;
break;
default:
layer.Frame = CGRect.Empty;
break;
}
}
CATransaction.Commit ();
}
void UpdateDbLayers ()
{
for (int index = -numDBLines; index <= numDBLines; index++) {
var location = Math.Floor (GetLocationForDbValue (index * defaultGain / numDBLines));
if (index >= -numDBLines && index <= numDBLines) {
dbLines [index + 4].Frame = new CGRect (graphLayer.Frame.X, location, graphLayer.Frame.Width, 1f);
dbLabels [index + 4].Frame = new CGRect (0f, location - bottomMargin - 8, leftMargin - 7f, 16f);
}
}
}
void UpdateFrequencyLayers ()
{
for (int index = 0; index <= gridLineCount; index++) {
var value = GetValue (index);
var location = Math.Floor (GetLocationForFrequencyValue (value));
if (index > 0 && index < gridLineCount) {
freqLines [index - 1].Frame = new CGRect (location, bottomMargin, 1f, graphLayer.Frame.Height);
frequencyLabels [index].Frame = new CGRect (location - labelWidth / 2f, graphLayer.Frame.Height, labelWidth, 16f);
}
frequencyLabels [index].Frame = new CGRect (location - labelWidth / 2f, graphLayer.Frame.Height + 6, labelWidth + rightMargin, 16f);
}
}
[Export ("layoutSublayersOfLayer:")]
public void LayoutSublayersOfLayer (CALayer layer)
{
if (layer == Layer) {
CATransaction.Begin ();
CATransaction.DisableActions = true;
containerLayer.Bounds = layer.Bounds;
graphLayer.Bounds = new CGRect (
leftMargin,
bottomMargin,
layer.Bounds.Width - leftMargin - rightMargin,
layer.Bounds.Height - bottomMargin - 10);
UpdateDbLayers ();
UpdateFrequencyLayers ();
editPoint = new CGPoint (GetLocationForFrequencyValue (Frequency), GetLocationForDbValue (Resonance));
if (curveLayer != null) {
curveLayer.Bounds = graphLayer.Bounds;
curveLayer.Frame = new CGRect (
graphLayer.Frame.X,
graphLayer.Frame.Y + bottomMargin,
graphLayer.Frame.Width,
graphLayer.Frame.Height);
}
CATransaction.Commit ();
}
UpdateControls (false);
frequencies = null;
Delegate?.DataChanged (this);
}
void UpdateFrequenciesAndResonance ()
{
var del = Delegate;
var lastFrequency = GetFrequencyValue (editPoint.X);
if (Math.Abs (lastFrequency - Frequency) > float.Epsilon) {
Frequency = lastFrequency;
if (del != null)
del.FrequencyChanged (this, Frequency);
}
var lastResonance = GetDbValue (editPoint.Y);
if (Math.Abs (lastResonance - Resonance) > float.Epsilon) {
Resonance = lastResonance;
if(del != null)
del.ResonanceChanged (this, Resonance);
}
}
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
base.TouchesBegan (touches, evt);
var pointOfTouch = ((UITouch)touches.FirstOrDefault ()).LocationInView (this);
pointOfTouch.Y += bottomMargin;
if (graphLayer.Contains (pointOfTouch)) {
touchDown = true;
editPoint = pointOfTouch;
UpdateFrequenciesAndResonance ();
}
}
CGPoint ProcessTouch (CGPoint touchPoint)
{
nfloat x = NMath.Max (0, touchPoint.X);
x = NMath.Min (x, graphLayer.Frame.Width + leftMargin);
nfloat y = NMath.Max (0, touchPoint.Y);
y = NMath.Min (y, graphLayer.Frame.Height + bottomMargin);
return new CGPoint (x, y);
}
float GetFrequencyValue (nfloat location)
{
var pixelIncrement = graphLayer.Frame.Width / gridLineCount;
var index = (location - graphLayer.Frame.X) / pixelIncrement;
return GetValue (index);
}
static float GetValue (nfloat gridIndex)
{
return (float)(DefaultMinHertz * Math.Pow (logBase, gridIndex));
}
static float GetLogValue (float number, float baseNum)
{
return (float)(Math.Log (number) / Math.Log (baseNum));
}
static string GetString (float value)
{
var temp = value;
if (value >= 1000)
temp /= 1000;
temp = (float)Math.Floor (temp * 100 / 100);
bool tooSmall = Math.Abs ((float)Math.Floor (temp) - temp) < float.Epsilon;
return tooSmall ? temp.ToString ("F1") : temp.ToString ("0.#");
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Runspaces;
using System.Diagnostics.CodeAnalysis;
namespace System.Management.Automation.Host
{
/// <summary>
///
/// Defines the properties and facilities providing by an application hosting an MSH <see
/// cref="System.Management.Automation.Runspaces.Runspace"/>.
///
/// </summary>
/// <remarks>
///
/// A hosting application derives from this class and
/// overrides the abstract methods and properties. The hosting application creates an instance of its derived class and
/// passes it to the <see cref="System.Management.Automation.Runspaces.RunspaceFactory"/> CreateRunspace method.
///
/// From the moment that the instance of the derived class (the "host class") is passed to CreateRunspace, the MSH runtime
/// can call any of the methods of that class. The instance must not be destroyed until after the Runspace is closed.
///
/// There is a 1:1 relationship between the instance of the host class and the Runspace instance to which it is passed. In
/// other words, it is not legal to pass the same instance of the host class to more than one call to CreateRunspace. (It
/// is perfectly legal to call CreateRunspace more than once, as long as each call is supplied a unique instance of the host
/// class.)
///
/// Methods of the host class can be called by the Runspace or any cmdlet or script executed in that Runspace in any order
/// and from any thread. It is the responsibility of the hosting application to define the host class methods in a
/// threadsafe fashion. An implementation of the host class should not depend on method execution order.
///
/// The instance of the host class that is passed to a Runspace is exposed by the Runspace to the cmdlets, scripts, and
/// providers that are executed in that Runspace. Scripts access the host class via the $Host built-in variable. Cmdlets
/// access the host via the Host property of the Cmdlet base class.
///
/// </remarks>
/// <seealso cref="System.Management.Automation.Runspaces.Runspace"/>
/// <seealso cref="System.Management.Automation.Host.PSHostUserInterface"/>
/// <seealso cref="System.Management.Automation.Host.PSHostRawUserInterface"/>
public abstract class PSHost
{
/// <summary>
/// The powershell.exe spec states that 128 is the maximum nesting depth.
/// </summary>
internal const int MaximumNestedPromptLevel = 128;
internal static bool IsStdOutputRedirected;
/// <summary>
///
/// Protected constructor which does nothing. Provided per .Net design guidelines section 4.3.1
///
/// </summary>
protected PSHost()
{
// do nothing
}
/// <summary>
///
/// Gets the hosting application's identification in some user-friendly fashion. This name can be referenced by scripts and cmdlets
/// to identify the host that is executing them. The format of the value is not defined, but a short, simple string is
/// recommended.
///
/// </summary>
/// <remarks>
/// In implementing this member, you should return some sort of informative string describing the nature
/// your hosting application. For the default console host shipped by Microsoft this is ConsoleHost.
/// </remarks>
/// <value>
///
/// The name identifier of the hosting application.
///
/// </value>
/// <example>
/// <MSH>
/// if ($Host.Name -ieq "ConsoleHost") { write-host "I'm running in the Console Host" }
/// </MSH>
/// </example>
public abstract string Name
{
get;
}
/// <summary>
///
/// Gets the version of the hosting application. This value should remain invariant for a particular build of the
/// host. This value may be referenced by scripts and cmdlets.
///
/// </summary>
/// <remarks>
/// When implementing this member, it should return the product version number for the product
/// that is hosting the Monad engine.
/// </remarks>
/// <value>
///
/// The version number of the hosting application.
///
/// </value>
public abstract System.Version Version
{
get;
}
/// <summary>
///
/// Gets a GUID that uniquely identifies this instance of the host. The value should remain invariant for the lifetime of
/// this instance.
///
/// </summary>
public abstract System.Guid InstanceId
{
get;
}
/// <summary>
///
/// Gets the hosting application's implementation of the
/// <see cref="System.Management.Automation.Host.PSHostUserInterface"/> abstract base class. A host
/// that does not want to support user interaction should return null.
///
/// </summary>
/// <value>
///
/// A reference to an instance of the hosting application's implementation of a class derived from
/// <see cref="System.Management.Automation.Host.PSHostUserInterface"/>, or null to indicate that user
/// interaction is not supported.
///
/// </value>
/// <remarks>
/// The implementation of this routine should return an instance of the appropriate
/// implementation of PSHostUserInterface for this application. As an alternative,
/// for simple scenarios, just returning null is sufficient.
/// </remarks>
public abstract System.Management.Automation.Host.PSHostUserInterface UI
{
get;
}
/// <summary>
///
/// Gets the host's culture: the culture that the runspace should use to set the CurrentCulture on new threads
///
/// </summary>
/// <value>
///
/// A CultureInfo object representing the host's current culture. Returning null is not allowed.
///
/// </value>
/// <remarks>
///
/// The runspace will set the thread current culture to this value each time it starts a pipeline. Thus, cmdlets are
/// encouraged to use Thread.CurrentThread.CurrentCulture.
///
/// </remarks>
public abstract System.Globalization.CultureInfo CurrentCulture
{
get;
}
/// <summary>
///
/// Gets the host's UI culture: the culture that the runspace and cmdlets should use to do resource loading.
///
/// The runspace will set the thread current ui culture to this value each time it starts a pipeline.
///
/// </summary>
/// <value>
///
/// A CultureInfo object representing the host's current UI culture. Returning null is not allowed.
///
/// </value>
public abstract System.Globalization.CultureInfo CurrentUICulture
{
get;
}
/// <summary>
///
/// Request by the engine to end the current engine runspace (to shut down and terminate the host's root runspace).
///
/// </summary>
/// <remarks>
///
/// This method is called by the engine to request the host shutdown the engine. This is invoked by the exit keyword
/// or by any other facility by which a runspace instance wishes to be shut down.
///
/// To honor this request, the host should stop accepting and submitting commands to the engine and close the runspace.
///
/// </remarks>
/// <param name="exitCode">
///
/// The exit code accompanying the exit keyword. Typically, after exiting a runspace, a host will also terminate. The
/// exitCode parameter can be used to set the host's process exit code.
///
/// </param>
public abstract void SetShouldExit(int exitCode);
/// <summary>
///
/// Instructs the host to interrupt the currently running pipeline and start a new, "nested" input loop, where an input
/// loop is the cycle of prompt, input, execute.
///
/// </summary>
/// <remarks>
///
/// Typically called by the engine in response to some user action that suspends the currently executing pipeline, such
/// as choosing the "suspend" option of a ConfirmProcessing call. Before calling this method, the engine should set
/// various shell variables to the express the state of the interrupted input loop (current pipeline, current object in
/// pipeline, depth of nested input loops, etc.)
///
/// A non-interactive host may throw a "not implemented" exception here.
///
/// If the UI property returns null, the engine should not call this method.
///
///
/// <!--Was: ExecuteSubShell. "subshell" implies a new child engine, which is not the case here. This is called during the
/// interruption of a pipeline to allow nested pipeline(s) to be run as a way to the user to suspend execution while he
/// evaluates other commands. It does not create a truly new engine instance with new session state.-->
///
/// </remarks>
/// <seealso cref="System.Management.Automation.Host.PSHost.ExitNestedPrompt"/>
public abstract void EnterNestedPrompt();
/// <summary>
///
/// Causes the host to end the currently running input loop. If the input loop was created by a prior call to
/// EnterNestedPrompt, the enclosing pipeline will be resumed. If the current input loop is the top-most loop, then the
/// host will act as though SetShouldExit was called.
///
/// </summary>
/// <remarks>
///
/// Typically called by the engine in response to some user action that resumes a suspended pipeline, such as with the
/// 'continue-command' intrinsic cmdlet. Before calling this method, the engine should clear out the loop-specific
/// variables that were set when the loop was created.
///
/// If the UI Property returns a null, the engine should not call this method.
///
/// </remarks>
/// <seealso cref="EnterNestedPrompt"/>
public abstract void ExitNestedPrompt();
/// <summary>
///
/// Used to allow the host to pass private data through a Runspace to cmdlets running inside that Runspace's
/// runspace. The type and nature of that data is entirely defined by the host, but there are some caveats:
///
///
/// </summary>
/// <returns>
///
/// The default implementation returns null.
///
/// </returns>
/// <remarks>
///
/// If the host is using an out-of-process Runspace, then the value of this property is serialized when crossing
/// that process boundary in the same fashion as any object in a pipeline is serialized when crossing process boundaries.
/// In this case, the BaseObject property of the value will be null.
///
/// If the host is using an in-process Runspace, then the BaseObject property can be a non-null value a live object.
/// No guarantees are made as to the app domain or thread that the BaseObject is accessed if it is accessed in the
/// runspace. No guarantees of threadsafety or reentrancy are made. The object set in the BaseObject property of
/// the value returned by this method is responsible for ensuring its own threadsafety and re-entrance safety.
/// Note that thread(s) accessing that object may not necessarily be the same from one access to the next.
///
/// The return value should have value-semantics: that is, changes to the state of the instance returned are not
/// reflected across processes. Ex: if a cmdlet reads this property, then changes the state of the result, that
/// change will not be visible to the host if the host is in another process. Therefore, the implementation of
/// get for this property should always return a unique instance.
///
/// </remarks>
public virtual PSObject PrivateData
{
get
{
return null;
}
}
/// <summary>
///
/// Called by the engine to notify the host that it is about to execute a "legacy" command line application. A legacy
/// application is defined as a console-mode executable that may do one or more of the following:
/// . reads from stdin
/// . writes to stdout
/// . writes to stderr
/// . uses any of the win32 console APIs
///
/// </summary>
/// <remarks>
///
/// Notifying the host allows the host to do such things as save off any state that might need to be restored when the
/// legacy application terminates, set or remove break handler hooks, redirect stream handles, and so forth.
///
/// The engine will always call this method and the NotifyEndApplication method in matching pairs.
///
/// The engine may call this method several times in the course of a single pipeline. For instance, the pipeline:
///
/// foo.exe | bar-cmdlet | baz.exe
///
/// Will result in a sequence of calls similar to the following:
/// NotifyBeginApplication - called once when foo.exe is started
/// NotifyBeginApplication - called once when baz.exe is started
/// NotifyEndApplication - called once when baz.exe terminates
/// NotifyEndApplication - called once when foo.exe terminates
///
/// Note that the order in which the NotifyEndApplication call follows the corresponding call to NotifyBeginApplication
/// with respect to any other call to NotifyBeginApplication is not defined, and should not be depended upon. In other
/// words, NotifyBeginApplication may be called several times before NotifyEndApplication is called. The only thing
/// that is guaranteed is that there will be an equal number of calls to NotifyEndApplication as to
/// NotifyBeginApplication.
///
/// </remarks>
/// <seealso cref="System.Management.Automation.Host.PSHost.NotifyEndApplication"/>
public abstract void NotifyBeginApplication();
/// <summary>
///
/// Called by the engine to notify the host that the execution of a legacy command has completed.
///
/// </summary>
/// <seealso cref="System.Management.Automation.Host.PSHost.NotifyBeginApplication"/>
public abstract void NotifyEndApplication();
/// <summary>
/// Used by hosting applications to notify PowerShell engine that it is
/// being hosted in a console based application and the Pipeline execution
/// thread should call SetThreadUILanguage(0). This property is currently
/// used by ConsoleHost only and in future releases we may consider
/// exposing this publicly.
/// </summary>
internal bool ShouldSetThreadUILanguageToZero { get; set; }
/// <summary>
/// This property enables and disables the host debugger if debugging is supported.
/// </summary>
public virtual bool DebuggerEnabled
{
get { return false; }
set { throw new PSNotImplementedException(); }
}
}
/// <summary>
/// This interface needs to be implemented by PSHost objects that want to support the PushRunspace
/// and PopRunspace functionality.
/// </summary>
public interface IHostSupportsInteractiveSession
{
/// <summary>
/// Called by the engine to notify the host that a runspace push has been requested.
/// </summary>
/// <seealso cref="System.Management.Automation.Host.IHostSupportsInteractiveSession.PushRunspace"/>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "runspace")]
void PushRunspace(Runspace runspace);
/// <summary>
/// Called by the engine to notify the host that a runspace pop has been requested.
/// </summary>
/// <seealso cref="System.Management.Automation.Host.IHostSupportsInteractiveSession.PopRunspace"/>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")]
void PopRunspace();
/// <summary>
/// True if a runspace is pushed; false otherwise.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")]
bool IsRunspacePushed { get; }
/// <summary>
/// Returns the current runspace associated with this host.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")]
Runspace Runspace { get; }
}
} // namespace System.Management.Automation.Host
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Flavor;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.MockVsTests
{
public sealed class MockVsSolution : IVsSolution, IVsRegisterProjectTypes, IVsCreateAggregateProject, IVsHierarchy
{
private string _solutionFile;
private readonly Dictionary<Guid, ProjectInfo> _projects = new Dictionary<Guid, ProjectInfo>();
private readonly Dictionary<string, ProjectInfo> _projectByName = new Dictionary<string, ProjectInfo>();
private readonly Dictionary<Guid, IVsProjectFactory> _projectFactories = new Dictionary<Guid, IVsProjectFactory>();
private static Regex _projectRegex = new Regex(@"Project\(""({[0-9A-Fa-f\-]+})""\)\s*=\s*""([\w\d\s]+)"",\s*""([\.\\\w\d\s]+)"",\s*""({[0-9A-Fa-f\-]+})""");
private class ProjectInfo
{
public readonly Guid ProjectGuid;
public readonly Guid ProjectType;
public readonly IVsHierarchy Hierarchy;
public readonly string Name, Filename;
public ProjectInfo(Guid projectGuid, Guid typeGuid, IVsHierarchy hierarchy, string name, string filename)
{
ProjectGuid = projectGuid;
ProjectType = typeGuid;
Hierarchy = hierarchy;
Name = name;
Filename = filename;
}
}
public string SolutionFile
{
get
{
return _solutionFile;
}
}
public int AddVirtualProject(IVsHierarchy pHierarchy, uint grfAddVPFlags)
{
throw new NotImplementedException();
}
public int AddVirtualProjectEx(IVsHierarchy pHierarchy, uint grfAddVPFlags, ref Guid rguidProjectID)
{
throw new NotImplementedException();
}
public int AdviseSolutionEvents(IVsSolutionEvents pSink, out uint pdwCookie)
{
throw new NotImplementedException();
}
public int CanCreateNewProjectAtLocation(int fCreateNewSolution, string pszFullProjectFilePath, out int pfCanCreate)
{
throw new NotImplementedException();
}
public int CloseSolutionElement(uint grfCloseOpts, IVsHierarchy pHier, uint docCookie)
{
throw new NotImplementedException();
}
public int CreateNewProjectViaDlg(string pszExpand, string pszSelect, uint dwReserved)
{
throw new NotImplementedException();
}
public int CreateProject(ref Guid rguidProjectType, string lpszMoniker, string lpszLocation, string lpszName, uint grfCreateFlags, ref Guid iidProject, out IntPtr ppProject)
{
throw new NotImplementedException();
}
public int CreateSolution(string lpszLocation, string lpszName, uint grfCreateFlags)
{
throw new NotImplementedException();
}
public int GenerateNextDefaultProjectName(string pszBaseName, string pszLocation, out string pbstrProjectName)
{
throw new NotImplementedException();
}
public int GenerateUniqueProjectName(string lpszRoot, out string pbstrProjectName)
{
throw new NotImplementedException();
}
public int GetGuidOfProject(IVsHierarchy pHierarchy, out Guid pguidProjectID)
{
throw new NotImplementedException();
}
public int GetItemInfoOfProjref(string pszProjref, int propid, out object pvar)
{
throw new NotImplementedException();
}
public int GetItemOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out uint pitemid, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason)
{
var comps = pszProjref.Split('|');
if (comps.Length == 3)
{
foreach (var project in _projects.Values)
{
if (project.Filename == comps[1])
{
ppHierarchy = project.Hierarchy;
if (ErrorHandler.Succeeded(project.Hierarchy.ParseCanonicalName(comps[2], out pitemid)))
{
pbstrUpdatedProjref = pszProjref;
puprUpdateReason[0] = VSUPDATEPROJREFREASON.UPR_NoUpdate;
return VSConstants.S_OK;
}
}
}
}
ppHierarchy = null;
pitemid = 0;
pbstrUpdatedProjref = null;
return VSConstants.E_FAIL;
}
public int GetProjectEnum(uint grfEnumFlags, ref Guid rguidEnumOnlyThisType, out IEnumHierarchies ppenum)
{
__VSENUMPROJFLAGS flags = (__VSENUMPROJFLAGS)grfEnumFlags;
ProjectInfo[] projects;
if (flags.HasFlag(__VSENUMPROJFLAGS.EPF_MATCHTYPE))
{
var guid = rguidEnumOnlyThisType;
projects = _projects.Values.Where(x => x.ProjectGuid == guid).ToArray();
}
else if (flags.HasFlag(__VSENUMPROJFLAGS.EPF_ALLPROJECTS))
{
projects = _projects.Values.ToArray();
}
else
{
throw new NotImplementedException();
}
ppenum = new ProjectEnum(projects);
return VSConstants.S_OK;
}
private class ProjectEnum : IEnumHierarchies
{
private readonly ProjectInfo[] _projects;
private int _index;
public ProjectEnum(ProjectInfo[] projects)
{
_projects = projects;
}
public int Clone(out IEnumHierarchies ppenum)
{
ppenum = new ProjectEnum(_projects);
return VSConstants.S_OK;
}
public int Next(uint celt, IVsHierarchy[] rgelt, out uint pceltFetched)
{
pceltFetched = 0;
for (int i = 0; i < celt && _index < _projects.Length; i++)
{
rgelt[i] = _projects[++_index].Hierarchy;
pceltFetched++;
}
return VSConstants.S_OK;
}
public int Reset()
{
_index = 0;
return VSConstants.S_OK;
}
public int Skip(uint celt)
{
_index += (int)celt;
return VSConstants.S_OK;
}
}
public int GetProjectFactory(uint dwReserved, Guid[] pguidProjectType, string pszMkProject, out IVsProjectFactory ppProjectFactory)
{
throw new NotImplementedException();
}
public int GetProjectFilesInSolution(uint grfGetOpts, uint cProjects, string[] rgbstrProjectNames, out uint pcProjectsFetched)
{
throw new NotImplementedException();
}
public int GetProjectInfoOfProjref(string pszProjref, int propid, out object pvar)
{
throw new NotImplementedException();
}
public int GetProjectOfGuid(ref Guid rguidProjectID, out IVsHierarchy ppHierarchy)
{
ProjectInfo proj;
if (_projects.TryGetValue(rguidProjectID, out proj))
{
ppHierarchy = proj.Hierarchy;
return VSConstants.S_OK;
}
ppHierarchy = null;
return VSConstants.E_FAIL;
}
public int GetProjectOfProjref(string pszProjref, out IVsHierarchy ppHierarchy, out string pbstrUpdatedProjref, VSUPDATEPROJREFREASON[] puprUpdateReason)
{
throw new NotImplementedException();
}
public int GetProjectOfUniqueName(string pszUniqueName, out IVsHierarchy ppHierarchy)
{
ProjectInfo proj;
if (_projectByName.TryGetValue(pszUniqueName, out proj))
{
ppHierarchy = proj.Hierarchy;
return VSConstants.S_OK;
}
ppHierarchy = null;
return VSConstants.E_FAIL;
}
public int GetProjectTypeGuid(uint dwReserved, string pszMkProject, out Guid pguidProjectType)
{
throw new NotImplementedException();
}
public int GetProjrefOfItem(IVsHierarchy pHierarchy, uint itemid, out string pbstrProjref)
{
foreach (var project in _projects)
{
if (ComUtilities.IsSameComObject(pHierarchy, project.Value.Hierarchy))
{
string canonicalName;
ErrorHandler.ThrowOnFailure(project.Value.Hierarchy.GetCanonicalName(itemid, out canonicalName));
pbstrProjref = project.Value.ProjectGuid.ToString("B") + "|" + project.Value.Filename + "|" + canonicalName;
return VSConstants.S_OK;
}
}
pbstrProjref = null;
return VSConstants.E_FAIL;
}
public int GetProjrefOfProject(IVsHierarchy pHierarchy, out string pbstrProjref)
{
throw new NotImplementedException();
}
public int GetProperty(int propid, out object pvar)
{
throw new NotImplementedException();
}
public int GetSolutionInfo(out string pbstrSolutionDirectory, out string pbstrSolutionFile, out string pbstrUserOptsFile)
{
pbstrSolutionDirectory = Path.GetDirectoryName(_solutionFile);
pbstrSolutionFile = _solutionFile;
pbstrUserOptsFile = "";
return VSConstants.S_OK;
}
public int GetUniqueNameOfProject(IVsHierarchy pHierarchy, out string pbstrUniqueName)
{
throw new NotImplementedException();
}
public int GetVirtualProjectFlags(IVsHierarchy pHierarchy, out uint pgrfAddVPFlags)
{
throw new NotImplementedException();
}
public int OnAfterRenameProject(IVsProject pProject, string pszMkOldName, string pszMkNewName, uint dwReserved)
{
throw new NotImplementedException();
}
public int OpenSolutionFile(uint grfOpenOpts, string pszFilename)
{
_solutionFile = pszFilename;
_projects.Clear();
_projectByName.Clear();
var text = File.ReadAllText(pszFilename);
foreach (Match match in _projectRegex.Matches(text))
{
var typeGuid = Guid.Parse(match.Groups[1].Value);
var projectName = match.Groups[2].Value;
var filename = match.Groups[3].Value;
var projectGuid = Guid.Parse(match.Groups[4].Value);
IVsProjectFactory factory;
if (!_projectFactories.TryGetValue(typeGuid, out factory))
{
Console.WriteLine("Unregistered project type: {0} for project {1}", typeGuid, filename);
return VSConstants.E_FAIL;
}
IntPtr project = IntPtr.Zero;
int cancelled;
try
{
int hr = factory.CreateProject(
Path.Combine(Path.GetDirectoryName(pszFilename), filename),
"",
"",
(uint)__VSCREATEPROJFLAGS.CPF_OPENFILE,
ref projectGuid,
out project,
out cancelled
);
if (ErrorHandler.Failed(hr))
{
return hr;
}
var vsProj = (IVsProject)Marshal.GetObjectForIUnknown(project);
var projectInfo = new ProjectInfo(
projectGuid,
typeGuid,
(IVsHierarchy)vsProj,
projectName,
filename
);
ErrorHandler.ThrowOnFailure(projectInfo.Hierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ParentHierarchy, this));
_projects[projectGuid] = projectInfo;
_projectByName[projectName] = projectInfo;
}
finally
{
if (project != IntPtr.Zero)
{
Marshal.Release(project);
}
}
}
return VSConstants.S_OK;
}
public int OpenSolutionViaDlg(string pszStartDirectory, int fDefaultToAllProjectsFilter)
{
throw new NotImplementedException();
}
public int QueryEditSolutionFile(out uint pdwEditResult)
{
throw new NotImplementedException();
}
public int QueryRenameProject(IVsProject pProject, string pszMkOldName, string pszMkNewName, uint dwReserved, out int pfRenameCanContinue)
{
throw new NotImplementedException();
}
public int RemoveVirtualProject(IVsHierarchy pHierarchy, uint grfRemoveVPFlags)
{
throw new NotImplementedException();
}
public int SaveSolutionElement(uint grfSaveOpts, IVsHierarchy pHier, uint docCookie)
{
throw new NotImplementedException();
}
public int SetProperty(int propid, object var)
{
throw new NotImplementedException();
}
public int UnadviseSolutionEvents(uint dwCookie)
{
throw new NotImplementedException();
}
#region IVsRegisterProjectTypes
public int RegisterProjectType(ref Guid rguidProjType, IVsProjectFactory pVsPF, out uint pdwCookie)
{
_projectFactories[rguidProjType] = pVsPF;
pdwCookie = 1;
return VSConstants.S_OK;
}
public int UnregisterProjectType(uint dwCookie)
{
throw new NotImplementedException();
}
#endregion
#region IVsCreateAggregateProject
public int CreateAggregateProject(string pszProjectTypeGuids, string pszFilename, string pszLocation, string pszName, uint grfCreateFlags, ref Guid iidProject, out IntPtr ppvProject)
{
ppvProject = IntPtr.Zero;
Guid[] guids = pszProjectTypeGuids.Split(';').Select(x => Guid.Parse(x)).ToArray();
IntPtr outer = IntPtr.Zero;
for (int i = 0; i < guids.Length; i++)
{
IVsProjectFactory factory;
if (!_projectFactories.TryGetValue(guids[0], out factory))
{
Console.WriteLine("Unknown project factory during aggregate creation: {0}", guids[0]);
return VSConstants.E_FAIL;
}
var agg = (IVsAggregatableProjectFactoryCorrected)factory;
IntPtr punk = IntPtr.Zero;
try
{
int hr = agg.PreCreateForOuter(outer, out punk);
if (ErrorHandler.Failed(hr))
{
return hr;
}
Debug.Assert(guids.Length == 1, "We don't initialize for outer in the right order...");
outer = punk;
var guid = typeof(IVsAggregatableProject).GUID;
IntPtr obj;
hr = Marshal.QueryInterface(punk, ref guid, out obj);
var aggProj = (IVsAggregatableProject)Marshal.GetObjectForIUnknown(obj);
IntPtr project;
int cancelled;
var iunknown = VSConstants.IID_IUnknown;
hr = aggProj.InitializeForOuter(pszFilename, pszLocation, pszName, grfCreateFlags, ref iunknown, out project, out cancelled);
if (ErrorHandler.Failed(hr))
{
return hr;
}
ppvProject = project;
}
finally
{
if (punk != IntPtr.Zero)
{
Marshal.Release(punk);
}
}
}
return VSConstants.S_OK;
}
#endregion
public int AdviseHierarchyEvents(IVsHierarchyEvents pEventSink, out uint pdwCookie)
{
throw new NotImplementedException();
}
public int Close()
{
throw new NotImplementedException();
}
public int GetCanonicalName(uint itemid, out string pbstrName)
{
throw new NotImplementedException();
}
public int GetGuidProperty(uint itemid, int propid, out Guid pguid)
{
throw new NotImplementedException();
}
public int GetNestedHierarchy(uint itemid, ref Guid iidHierarchyNested, out IntPtr ppHierarchyNested, out uint pitemidNested)
{
throw new NotImplementedException();
}
public int GetProperty(uint itemid, int propid, out object pvar)
{
throw new NotImplementedException();
}
public int GetSite(out VisualStudio.OLE.Interop.IServiceProvider ppSP)
{
throw new NotImplementedException();
}
public int ParseCanonicalName(string pszName, out uint pitemid)
{
throw new NotImplementedException();
}
public int QueryClose(out int pfCanClose)
{
throw new NotImplementedException();
}
public int SetGuidProperty(uint itemid, int propid, ref Guid rguid)
{
throw new NotImplementedException();
}
public int SetProperty(uint itemid, int propid, object var)
{
throw new NotImplementedException();
}
public int SetSite(VisualStudio.OLE.Interop.IServiceProvider psp)
{
throw new NotImplementedException();
}
public int UnadviseHierarchyEvents(uint dwCookie)
{
throw new NotImplementedException();
}
public int Unused0()
{
throw new NotImplementedException();
}
public int Unused1()
{
throw new NotImplementedException();
}
public int Unused2()
{
throw new NotImplementedException();
}
public int Unused3()
{
throw new NotImplementedException();
}
public int Unused4()
{
throw new NotImplementedException();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace SiteProvisioningWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
// Soon to be dismissed
[Serializable]
public class ChildAgentDataUpdate
{
public Guid ActiveGroupID;
public Guid AgentID;
public bool alwaysrun;
public float AVHeight;
public Vector3 cameraPosition;
public float drawdistance;
public float godlevel;
public uint GroupAccess;
public Vector3 Position;
public ulong regionHandle;
public byte[] throttles;
public Vector3 Velocity;
public ChildAgentDataUpdate()
{
}
}
public interface IAgentData
{
UUID AgentID { get; set; }
OSDMap Pack();
void Unpack(OSDMap map);
}
/// <summary>
/// Replacement for ChildAgentDataUpdate. Used over RESTComms and LocalComms.
/// </summary>
public class AgentPosition : IAgentData
{
private UUID m_id;
public UUID AgentID
{
get { return m_id; }
set { m_id = value; }
}
public ulong RegionHandle;
public uint CircuitCode;
public UUID SessionID;
public float Far;
public Vector3 Position;
public Vector3 Velocity;
public Vector3 Center;
public Vector3 Size;
public Vector3 AtAxis;
public Vector3 LeftAxis;
public Vector3 UpAxis;
public bool ChangedGrid;
// This probably shouldn't be here
public byte[] Throttles;
public OSDMap Pack()
{
OSDMap args = new OSDMap();
args["message_type"] = OSD.FromString("AgentPosition");
args["region_handle"] = OSD.FromString(RegionHandle.ToString());
args["circuit_code"] = OSD.FromString(CircuitCode.ToString());
args["agent_uuid"] = OSD.FromUUID(AgentID);
args["session_uuid"] = OSD.FromUUID(SessionID);
args["position"] = OSD.FromString(Position.ToString());
args["velocity"] = OSD.FromString(Velocity.ToString());
args["center"] = OSD.FromString(Center.ToString());
args["size"] = OSD.FromString(Size.ToString());
args["at_axis"] = OSD.FromString(AtAxis.ToString());
args["left_axis"] = OSD.FromString(LeftAxis.ToString());
args["up_axis"] = OSD.FromString(UpAxis.ToString());
args["far"] = OSD.FromReal(Far);
args["changed_grid"] = OSD.FromBoolean(ChangedGrid);
if ((Throttles != null) && (Throttles.Length > 0))
args["throttles"] = OSD.FromBinary(Throttles);
return args;
}
public void Unpack(OSDMap args)
{
if (args.ContainsKey("region_handle"))
UInt64.TryParse(args["region_handle"].AsString(), out RegionHandle);
if (args["circuit_code"] != null)
UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);
if (args["agent_uuid"] != null)
AgentID = args["agent_uuid"].AsUUID();
if (args["session_uuid"] != null)
SessionID = args["session_uuid"].AsUUID();
if (args["position"] != null)
Vector3.TryParse(args["position"].AsString(), out Position);
if (args["velocity"] != null)
Vector3.TryParse(args["velocity"].AsString(), out Velocity);
if (args["center"] != null)
Vector3.TryParse(args["center"].AsString(), out Center);
if (args["size"] != null)
Vector3.TryParse(args["size"].AsString(), out Size);
if (args["at_axis"] != null)
Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);
if (args["left_axis"] != null)
Vector3.TryParse(args["left_axis"].AsString(), out AtAxis);
if (args["up_axis"] != null)
Vector3.TryParse(args["up_axis"].AsString(), out AtAxis);
if (args["changed_grid"] != null)
ChangedGrid = args["changed_grid"].AsBoolean();
if (args["far"] != null)
Far = (float)(args["far"].AsReal());
if (args["throttles"] != null)
Throttles = args["throttles"].AsBinary();
}
/// <summary>
/// Soon to be decommissioned
/// </summary>
/// <param name="cAgent"></param>
public void CopyFrom(ChildAgentDataUpdate cAgent)
{
AgentID = new UUID(cAgent.AgentID);
// next: ???
Size = new Vector3();
Size.Z = cAgent.AVHeight;
Center = cAgent.cameraPosition;
Far = cAgent.drawdistance;
Position = cAgent.Position;
RegionHandle = cAgent.regionHandle;
Throttles = cAgent.throttles;
Velocity = cAgent.Velocity;
}
}
public class AgentGroupData
{
public UUID GroupID;
public ulong GroupPowers;
public bool AcceptNotices;
public AgentGroupData(UUID id, ulong powers, bool notices)
{
GroupID = id;
GroupPowers = powers;
AcceptNotices = notices;
}
public AgentGroupData(OSDMap args)
{
UnpackUpdateMessage(args);
}
public OSDMap PackUpdateMessage()
{
OSDMap groupdata = new OSDMap();
groupdata["group_id"] = OSD.FromUUID(GroupID);
groupdata["group_powers"] = OSD.FromString(GroupPowers.ToString());
groupdata["accept_notices"] = OSD.FromBoolean(AcceptNotices);
return groupdata;
}
public void UnpackUpdateMessage(OSDMap args)
{
if (args["group_id"] != null)
GroupID = args["group_id"].AsUUID();
if (args["group_powers"] != null)
UInt64.TryParse((string)args["group_powers"].AsString(), out GroupPowers);
if (args["accept_notices"] != null)
AcceptNotices = args["accept_notices"].AsBoolean();
}
}
public class AttachmentData
{
public int AttachPoint;
public UUID ItemID;
public UUID AssetID;
public AttachmentData(int point, UUID item, UUID asset)
{
AttachPoint = point;
ItemID = item;
AssetID = asset;
}
public AttachmentData(OSDMap args)
{
UnpackUpdateMessage(args);
}
public OSDMap PackUpdateMessage()
{
OSDMap attachdata = new OSDMap();
attachdata["point"] = OSD.FromInteger(AttachPoint);
attachdata["item"] = OSD.FromUUID(ItemID);
attachdata["asset"] = OSD.FromUUID(AssetID);
return attachdata;
}
public void UnpackUpdateMessage(OSDMap args)
{
if (args["point"] != null)
AttachPoint = args["point"].AsInteger();
if (args["item"] != null)
ItemID = args["item"].AsUUID();
if (args["asset"] != null)
AssetID = args["asset"].AsUUID();
}
}
public class AgentData : IAgentData
{
private UUID m_id;
public UUID AgentID
{
get { return m_id; }
set { m_id = value; }
}
public UUID RegionID;
public uint CircuitCode;
public UUID SessionID;
public Vector3 Position;
public Vector3 Velocity;
public Vector3 Center;
public Vector3 Size;
public Vector3 AtAxis;
public Vector3 LeftAxis;
public Vector3 UpAxis;
public bool ChangedGrid;
public float Far;
public float Aspect;
//public int[] Throttles;
public byte[] Throttles;
public uint LocomotionState;
public Quaternion HeadRotation;
public Quaternion BodyRotation;
public uint ControlFlags;
public float EnergyLevel;
public Byte GodLevel;
public bool AlwaysRun;
public UUID PreyAgent;
public Byte AgentAccess;
public UUID ActiveGroupID;
public AgentGroupData[] Groups;
public Animation[] Anims;
public UUID GranterID;
// Appearance
public byte[] AgentTextures;
public byte[] VisualParams;
public UUID[] Wearables;
public AttachmentData[] Attachments;
public string CallbackURI;
public virtual OSDMap Pack()
{
OSDMap args = new OSDMap();
args["message_type"] = OSD.FromString("AgentData");
args["region_id"] = OSD.FromString(RegionID.ToString());
args["circuit_code"] = OSD.FromString(CircuitCode.ToString());
args["agent_uuid"] = OSD.FromUUID(AgentID);
args["session_uuid"] = OSD.FromUUID(SessionID);
args["position"] = OSD.FromString(Position.ToString());
args["velocity"] = OSD.FromString(Velocity.ToString());
args["center"] = OSD.FromString(Center.ToString());
args["size"] = OSD.FromString(Size.ToString());
args["at_axis"] = OSD.FromString(AtAxis.ToString());
args["left_axis"] = OSD.FromString(LeftAxis.ToString());
args["up_axis"] = OSD.FromString(UpAxis.ToString());
args["changed_grid"] = OSD.FromBoolean(ChangedGrid);
args["far"] = OSD.FromReal(Far);
args["aspect"] = OSD.FromReal(Aspect);
if ((Throttles != null) && (Throttles.Length > 0))
args["throttles"] = OSD.FromBinary(Throttles);
args["locomotion_state"] = OSD.FromString(LocomotionState.ToString());
args["head_rotation"] = OSD.FromString(HeadRotation.ToString());
args["body_rotation"] = OSD.FromString(BodyRotation.ToString());
args["control_flags"] = OSD.FromString(ControlFlags.ToString());
args["energy_level"] = OSD.FromReal(EnergyLevel);
args["god_level"] = OSD.FromString(GodLevel.ToString());
args["always_run"] = OSD.FromBoolean(AlwaysRun);
args["prey_agent"] = OSD.FromUUID(PreyAgent);
args["agent_access"] = OSD.FromString(AgentAccess.ToString());
args["active_group_id"] = OSD.FromUUID(ActiveGroupID);
if ((Groups != null) && (Groups.Length > 0))
{
OSDArray groups = new OSDArray(Groups.Length);
foreach (AgentGroupData agd in Groups)
groups.Add(agd.PackUpdateMessage());
args["groups"] = groups;
}
if ((Anims != null) && (Anims.Length > 0))
{
OSDArray anims = new OSDArray(Anims.Length);
foreach (Animation aanim in Anims)
anims.Add(aanim.PackUpdateMessage());
args["animations"] = anims;
}
//if ((AgentTextures != null) && (AgentTextures.Length > 0))
//{
// OSDArray textures = new OSDArray(AgentTextures.Length);
// foreach (UUID uuid in AgentTextures)
// textures.Add(OSD.FromUUID(uuid));
// args["agent_textures"] = textures;
//}
if ((AgentTextures != null) && (AgentTextures.Length > 0))
args["texture_entry"] = OSD.FromBinary(AgentTextures);
if ((VisualParams != null) && (VisualParams.Length > 0))
args["visual_params"] = OSD.FromBinary(VisualParams);
// We might not pass this in all cases...
if ((Wearables != null) && (Wearables.Length > 0))
{
OSDArray wears = new OSDArray(Wearables.Length);
foreach (UUID uuid in Wearables)
wears.Add(OSD.FromUUID(uuid));
args["wearables"] = wears;
}
if ((Attachments != null) && (Attachments.Length > 0))
{
OSDArray attachs = new OSDArray(Attachments.Length);
foreach (AttachmentData att in Attachments)
attachs.Add(att.PackUpdateMessage());
args["attachments"] = attachs;
}
if ((CallbackURI != null) && (!CallbackURI.Equals("")))
args["callback_uri"] = OSD.FromString(CallbackURI);
return args;
}
/// <summary>
/// Deserialization of agent data.
/// Avoiding reflection makes it painful to write, but that's the price!
/// </summary>
/// <param name="hash"></param>
public virtual void Unpack(OSDMap args)
{
if (args.ContainsKey("region_id"))
UUID.TryParse(args["region_id"].AsString(), out RegionID);
if (args["circuit_code"] != null)
UInt32.TryParse((string)args["circuit_code"].AsString(), out CircuitCode);
if (args["agent_uuid"] != null)
AgentID = args["agent_uuid"].AsUUID();
if (args["session_uuid"] != null)
SessionID = args["session_uuid"].AsUUID();
if (args["position"] != null)
Vector3.TryParse(args["position"].AsString(), out Position);
if (args["velocity"] != null)
Vector3.TryParse(args["velocity"].AsString(), out Velocity);
if (args["center"] != null)
Vector3.TryParse(args["center"].AsString(), out Center);
if (args["size"] != null)
Vector3.TryParse(args["size"].AsString(), out Size);
if (args["at_axis"] != null)
Vector3.TryParse(args["at_axis"].AsString(), out AtAxis);
if (args["left_axis"] != null)
Vector3.TryParse(args["left_axis"].AsString(), out AtAxis);
if (args["up_axis"] != null)
Vector3.TryParse(args["up_axis"].AsString(), out AtAxis);
if (args["changed_grid"] != null)
ChangedGrid = args["changed_grid"].AsBoolean();
if (args["far"] != null)
Far = (float)(args["far"].AsReal());
if (args["aspect"] != null)
Aspect = (float)args["aspect"].AsReal();
if (args["throttles"] != null)
Throttles = args["throttles"].AsBinary();
if (args["locomotion_state"] != null)
UInt32.TryParse(args["locomotion_state"].AsString(), out LocomotionState);
if (args["head_rotation"] != null)
Quaternion.TryParse(args["head_rotation"].AsString(), out HeadRotation);
if (args["body_rotation"] != null)
Quaternion.TryParse(args["body_rotation"].AsString(), out BodyRotation);
if (args["control_flags"] != null)
UInt32.TryParse(args["control_flags"].AsString(), out ControlFlags);
if (args["energy_level"] != null)
EnergyLevel = (float)(args["energy_level"].AsReal());
if (args["god_level"] != null)
Byte.TryParse(args["god_level"].AsString(), out GodLevel);
if (args["always_run"] != null)
AlwaysRun = args["always_run"].AsBoolean();
if (args["prey_agent"] != null)
PreyAgent = args["prey_agent"].AsUUID();
if (args["agent_access"] != null)
Byte.TryParse(args["agent_access"].AsString(), out AgentAccess);
if (args["active_group_id"] != null)
ActiveGroupID = args["active_group_id"].AsUUID();
if ((args["groups"] != null) && (args["groups"]).Type == OSDType.Array)
{
OSDArray groups = (OSDArray)(args["groups"]);
Groups = new AgentGroupData[groups.Count];
int i = 0;
foreach (OSD o in groups)
{
if (o.Type == OSDType.Map)
{
Groups[i++] = new AgentGroupData((OSDMap)o);
}
}
}
if ((args["animations"] != null) && (args["animations"]).Type == OSDType.Array)
{
OSDArray anims = (OSDArray)(args["animations"]);
Anims = new Animation[anims.Count];
int i = 0;
foreach (OSD o in anims)
{
if (o.Type == OSDType.Map)
{
Anims[i++] = new Animation((OSDMap)o);
}
}
}
//if ((args["agent_textures"] != null) && (args["agent_textures"]).Type == OSDType.Array)
//{
// OSDArray textures = (OSDArray)(args["agent_textures"]);
// AgentTextures = new UUID[textures.Count];
// int i = 0;
// foreach (OSD o in textures)
// AgentTextures[i++] = o.AsUUID();
//}
if (args["texture_entry"] != null)
AgentTextures = args["texture_entry"].AsBinary();
if (args["visual_params"] != null)
VisualParams = args["visual_params"].AsBinary();
if ((args["wearables"] != null) && (args["wearables"]).Type == OSDType.Array)
{
OSDArray wears = (OSDArray)(args["wearables"]);
Wearables = new UUID[wears.Count];
int i = 0;
foreach (OSD o in wears)
Wearables[i++] = o.AsUUID();
}
if ((args["attachments"] != null) && (args["attachments"]).Type == OSDType.Array)
{
OSDArray attachs = (OSDArray)(args["attachments"]);
Attachments = new AttachmentData[attachs.Count];
int i = 0;
foreach (OSD o in attachs)
{
if (o.Type == OSDType.Map)
{
Attachments[i++] = new AttachmentData((OSDMap)o);
}
}
}
if (args["callback_uri"] != null)
CallbackURI = args["callback_uri"].AsString();
}
public AgentData()
{
}
public AgentData(Hashtable hash)
{
//UnpackUpdateMessage(hash);
}
public void Dump()
{
System.Console.WriteLine("------------ AgentData ------------");
System.Console.WriteLine("UUID: " + AgentID);
System.Console.WriteLine("Region: " + RegionID);
System.Console.WriteLine("Position: " + Position);
}
}
public class CompleteAgentData : AgentData
{
public override OSDMap Pack()
{
return base.Pack();
}
public override void Unpack(OSDMap map)
{
base.Unpack(map);
}
}
}
| |
#if ENABLE_UNET
namespace UnityEngine.Networking
{
[AddComponentMenu("Network/NetworkManagerHUD")]
[RequireComponent(typeof(NetworkManager))]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class NetworkManagerHUD : MonoBehaviour
{
public NetworkManager manager;
[SerializeField] public bool showGUI = true;
[SerializeField] public int offsetX;
[SerializeField] public int offsetY;
// Runtime variable
bool showServer = false;
void Awake()
{
manager = GetComponent<NetworkManager>();
}
void Update()
{
if (!showGUI)
return;
if (!NetworkClient.active && !NetworkServer.active && manager.matchMaker == null)
{
if (Input.GetKeyDown(KeyCode.S))
{
manager.StartServer();
}
if (Input.GetKeyDown(KeyCode.H))
{
manager.StartHost();
}
if (Input.GetKeyDown(KeyCode.C))
{
manager.StartClient();
}
}
if (NetworkServer.active && NetworkClient.active)
{
if (Input.GetKeyDown(KeyCode.X))
{
manager.StopHost();
}
}
}
void OnGUI()
{
if (!showGUI)
return;
int xpos = 10 + offsetX;
int ypos = 40 + offsetY;
int spacing = 48;
if (!NetworkClient.active && !NetworkServer.active && manager.matchMaker == null)
{
if (GUI.Button(new Rect(xpos, ypos, 200, 40), "LAN Host(H)"))
{
manager.StartHost();
}
ypos += spacing;
if (GUI.Button(new Rect(xpos, ypos, 105, 40), "LAN Client(C)"))
{
manager.StartClient();
}
manager.networkAddress = GUI.TextField(new Rect(xpos + 100, ypos, 95, 40), manager.networkAddress);
ypos += spacing;
if (GUI.Button(new Rect(xpos, ypos, 200, 40), "LAN Server Only(S)"))
{
manager.StartServer();
}
ypos += spacing;
}
else
{
if (NetworkServer.active)
{
GUI.Label(new Rect(xpos, ypos, 300, 40), "Server: port=" + manager.networkPort);
ypos += spacing;
}
if (NetworkClient.active)
{
GUI.Label(new Rect(xpos, ypos, 300, 40), "Client: address=" + manager.networkAddress + " port=" + manager.networkPort);
ypos += spacing;
}
}
if (NetworkClient.active && !ClientScene.ready)
{
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Client Ready"))
{
ClientScene.Ready(manager.client.connection);
if (ClientScene.localPlayers.Count == 0)
{
ClientScene.AddPlayer(0);
}
}
ypos += spacing;
}
if (NetworkServer.active || NetworkClient.active)
{
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Stop (X)"))
{
manager.StopHost();
}
ypos += spacing;
}
if (!NetworkServer.active && !NetworkClient.active)
{
ypos += 10;
if (manager.matchMaker == null)
{
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Enable Match Maker (M)"))
{
manager.StartMatchMaker();
}
ypos += spacing;
}
else
{
if (manager.matchInfo == null)
{
if (manager.matches == null)
{
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Create Internet Match"))
{
manager.matchMaker.CreateMatch(manager.matchName, manager.matchSize, true, "", manager.OnMatchCreate);
}
ypos += spacing;
GUI.Label(new Rect(xpos, ypos, 100, 20), "Room Name:");
manager.matchName = GUI.TextField(new Rect(xpos+100, ypos, 100, 20), manager.matchName);
ypos += spacing;
ypos += 10;
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Find Internet Match"))
{
manager.matchMaker.ListMatches(0,20, "", manager.OnMatchList);
}
ypos += spacing;
}
else
{
foreach (var match in manager.matches)
{
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Join Match:" + match.name))
{
manager.matchName = match.name;
manager.matchSize = (uint)match.currentSize;
manager.matchMaker.JoinMatch(match.networkId, "", manager.OnMatchJoined);
}
ypos += spacing;
}
}
}
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Change MM server"))
{
showServer = !showServer;
}
if (showServer)
{
ypos += spacing;
if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Local"))
{
manager.SetMatchHost("localhost", 1337, false);
showServer = false;
}
ypos += spacing;
if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Internet"))
{
manager.SetMatchHost("mm.unet.unity3d.com", 443, true);
showServer = false;
}
ypos += spacing;
if (GUI.Button(new Rect(xpos, ypos, 100, 20), "Staging"))
{
manager.SetMatchHost("staging-mm.unet.unity3d.com", 443, true);
showServer = false;
}
}
ypos += spacing;
GUI.Label(new Rect(xpos, ypos, 300, 20), "MM Uri: " + manager.matchMaker.baseUri);
ypos += spacing;
if (GUI.Button(new Rect(xpos, ypos, 200, 20), "Disable Match Maker"))
{
manager.StopMatchMaker();
}
ypos += spacing;
}
}
}
}
};
#endif //ENABLE_UNET
| |
// 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.ComponentModel.Composition.Primitives;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.ReflectionModel
{
internal class ReflectionComposablePart : ComposablePart, ICompositionElement
{
private readonly ReflectionComposablePartDefinition _definition;
private volatile Dictionary<ImportDefinition, object> _importValues = null;
private volatile Dictionary<ImportDefinition, ImportingItem> _importsCache = null;
private volatile Dictionary<int, ExportingMember> _exportsCache = null;
private volatile bool _invokeImportsSatisfied = true;
private bool _initialCompositionComplete = false;
private volatile object _cachedInstance;
private object _lock = new object();
public ReflectionComposablePart(ReflectionComposablePartDefinition definition)
{
Requires.NotNull(definition, nameof(definition));
_definition = definition;
}
public ReflectionComposablePart(ReflectionComposablePartDefinition definition, object attributedPart)
{
Requires.NotNull(definition, nameof(definition));
Requires.NotNull(attributedPart, nameof(attributedPart));
_definition = definition;
if (attributedPart is ValueType)
{
throw new ArgumentException(SR.ArgumentValueType, "attributedPart");
}
_cachedInstance = attributedPart;
}
protected virtual void EnsureRunning()
{
}
protected void RequiresRunning()
{
EnsureRunning();
}
protected virtual void ReleaseInstanceIfNecessary(object instance)
{
}
private Dictionary<ImportDefinition, object> ImportValues
{
get
{
var value = _importValues;
if(value == null)
{
lock(_lock)
{
value = _importValues;
if(value == null)
{
value = new Dictionary<ImportDefinition, object>();
_importValues = value;
}
}
}
return value;
}
}
private Dictionary<ImportDefinition, ImportingItem> ImportsCache
{
get
{
var value = _importsCache;
if(value == null)
{
lock(_lock)
{
if(value == null)
{
value = new Dictionary<ImportDefinition, ImportingItem>();
_importsCache = value;
}
}
}
return value;
}
}
protected object CachedInstance
{
get
{
lock (_lock)
{
return _cachedInstance;
}
}
}
public ReflectionComposablePartDefinition Definition
{
get
{
RequiresRunning();
return _definition;
}
}
public override IDictionary<string, object> Metadata
{
get
{
RequiresRunning();
return Definition.Metadata;
}
}
public sealed override IEnumerable<ImportDefinition> ImportDefinitions
{
get
{
RequiresRunning();
return Definition.ImportDefinitions;
}
}
public sealed override IEnumerable<ExportDefinition> ExportDefinitions
{
get
{
RequiresRunning();
return Definition.ExportDefinitions;
}
}
string ICompositionElement.DisplayName
{
get { return GetDisplayName(); }
}
ICompositionElement ICompositionElement.Origin
{
get { return Definition; }
}
// This is the ONLY method which is not executed under the ImportEngine composition lock.
// We need to protect all state that is accesses
public override object GetExportedValue(ExportDefinition definition)
{
RequiresRunning();
// given the implementation of the ImportEngine, this iwll be called under a lock if the part is still being composed
// This is only called outside of the lock when the part is fully composed
// based on that we only protect:
// _exportsCache - and thus all calls to GetExportingMemberFromDefinition
// access to _importValues
// access to _initialCompositionComplete
// access to _instance
Requires.NotNull(definition, nameof(definition));
ExportingMember member = null;
lock (_lock)
{
member = GetExportingMemberFromDefinition(definition);
if (member == null)
{
throw ExceptionBuilder.CreateExportDefinitionNotOnThisComposablePart("definition");
}
EnsureGettable();
}
return GetExportedValue(member);
}
public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports)
{
RequiresRunning();
Requires.NotNull(definition, nameof(definition));
Requires.NotNull(exports, nameof(exports));;
ImportingItem item = GetImportingItemFromDefinition(definition);
if (item == null)
{
throw ExceptionBuilder.CreateImportDefinitionNotOnThisComposablePart("definition");
}
EnsureSettable(definition);
// Avoid walking over exports many times
Export[] exportsAsArray = exports.AsArray();
EnsureCardinality(definition, exportsAsArray);
SetImport(item, exportsAsArray);
}
public override void Activate()
{
RequiresRunning();
SetNonPrerequisiteImports();
// Whenever we are composed/recomposed notify the instance
NotifyImportSatisfied();
lock (_lock)
{
_initialCompositionComplete = true;
_importValues = null;
_importsCache = null;
}
}
public override string ToString()
{
return GetDisplayName();
}
private object GetExportedValue(ExportingMember member)
{
object instance = null;
if (member.RequiresInstance)
{ // Only activate the instance if we actually need to
instance = GetInstanceActivatingIfNeeded();
}
return member.GetExportedValue(instance, _lock);
}
private void SetImport(ImportingItem item, Export[] exports)
{
object value = item.CastExportsToImportType(exports);
lock (_lock)
{
_invokeImportsSatisfied = true;
ImportValues[item.Definition] = value;
}
}
private object GetInstanceActivatingIfNeeded()
{
var cachedInstance = _cachedInstance;
if (cachedInstance != null)
{
return cachedInstance;
}
else
{
ConstructorInfo constructor = null;
object[] arguments = null;
// determine whether activation is required, and collect necessary information for activation
// we need to do that under a lock
lock (_lock)
{
if (!RequiresActivation())
{
return null;
}
constructor = Definition.GetConstructor();
if (constructor == null)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_PartConstructorMissing,
Definition.GetPartType().FullName),
Definition.ToElement());
}
arguments = GetConstructorArguments();
}
// create instance outside of the lock
object createdInstance = CreateInstance(constructor, arguments);
SetPrerequisiteImports();
// set the created instance
if (_cachedInstance == null)
{
lock (_lock)
{
if (_cachedInstance == null)
{
_cachedInstance = createdInstance;
createdInstance = null;
}
}
}
// if the instance has been already set
if (createdInstance == null)
{
ReleaseInstanceIfNecessary(createdInstance);
}
}
return _cachedInstance;
}
private object[] GetConstructorArguments()
{
ReflectionParameterImportDefinition[] parameterImports = ImportDefinitions.OfType<ReflectionParameterImportDefinition>().ToArray();
object[] arguments = new object[parameterImports.Length];
UseImportedValues(
parameterImports,
(import, definition, value) =>
{
if (definition.Cardinality == ImportCardinality.ZeroOrMore && !import.ImportType.IsAssignableCollectionType)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned,
Definition.GetPartType().FullName,
definition.ImportingLazyParameter.Value.Name),
Definition.ToElement());
}
arguments[definition.ImportingLazyParameter.Value.Position] = value;
},
true);
return arguments;
}
// alwayc called under a lock
private bool RequiresActivation()
{
// If we have any imports then we need activation
// (static imports are not supported)
if (ImportDefinitions.Any())
{
return true;
}
// If we have any instance exports, then we also
// need activation.
return ExportDefinitions.Any(definition =>
{
ExportingMember member = GetExportingMemberFromDefinition(definition);
return member.RequiresInstance;
});
}
// this is called under a lock
private void EnsureGettable()
{
// If we're already composed then we know that
// all pre-req imports have been satisfied
if (_initialCompositionComplete)
{
return;
}
// Make sure all pre-req imports have been set
foreach (ImportDefinition definition in ImportDefinitions.Where(definition => definition.IsPrerequisite))
{
if (_importValues == null || !ImportValues.ContainsKey(definition))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
SR.InvalidOperation_GetExportedValueBeforePrereqImportSet,
definition.ToElement().DisplayName));
}
}
}
private void EnsureSettable(ImportDefinition definition)
{
lock (_lock)
{
if (_initialCompositionComplete && !definition.IsRecomposable)
{
throw new InvalidOperationException(SR.InvalidOperation_DefinitionCannotBeRecomposed);
}
}
}
private static void EnsureCardinality(ImportDefinition definition, Export[] exports)
{
Requires.NullOrNotNullElements(exports, "exports");
ExportCardinalityCheckResult result = ExportServices.CheckCardinality(definition, exports);
switch (result)
{
case ExportCardinalityCheckResult.NoExports:
throw new ArgumentException(SR.Argument_ExportsEmpty, "exports");
case ExportCardinalityCheckResult.TooManyExports:
throw new ArgumentException(SR.Argument_ExportsTooMany, "exports");
default:
Assumes.IsTrue(result == ExportCardinalityCheckResult.Match);
break;
}
}
private object CreateInstance(ConstructorInfo constructor, object[] arguments)
{
Exception exception = null;
object instance = null;
try
{
instance = constructor.SafeInvoke(arguments);
}
catch (TypeInitializationException ex)
{
exception = ex;
}
catch (TargetInvocationException ex)
{
exception = ex.InnerException;
}
if (exception != null)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_PartConstructorThrewException,
Definition.GetPartType().FullName),
Definition.ToElement(),
exception);
}
return instance;
}
private void SetNonPrerequisiteImports()
{
IEnumerable<ImportDefinition> members = ImportDefinitions.Where(import => !import.IsPrerequisite);
// NOTE: Dev10 484204 The validation is turned off for post imports because of it broke declarative composition
UseImportedValues(members, SetExportedValueForImport, false);
}
private void SetPrerequisiteImports()
{
IEnumerable<ImportDefinition> members = ImportDefinitions.Where(import => import.IsPrerequisite);
// NOTE: Dev10 484204 The validation is turned off for post imports because of it broke declarative composition
UseImportedValues(members, SetExportedValueForImport, false);
}
private void SetExportedValueForImport(ImportingItem import, ImportDefinition definition, object value)
{
ImportingMember importMember = (ImportingMember)import;
object instance = GetInstanceActivatingIfNeeded();
importMember.SetExportedValue(instance, value);
}
private void UseImportedValues<TImportDefinition>(IEnumerable<TImportDefinition> definitions, Action<ImportingItem, TImportDefinition, object> useImportValue, bool errorIfMissing)
where TImportDefinition : ImportDefinition
{
var result = CompositionResult.SucceededResult;
foreach (var definition in definitions)
{
ImportingItem import = GetImportingItemFromDefinition(definition);
object value;
if (!TryGetImportValue(definition, out value))
{
if (!errorIfMissing)
{
continue;
}
if (definition.Cardinality == ImportCardinality.ExactlyOne)
{
var error = CompositionError.Create(
CompositionErrorId.ImportNotSetOnPart,
SR.ImportNotSetOnPart,
Definition.GetPartType().FullName,
definition.ToString());
result = result.MergeError(error);
continue;
}
else
{
value = import.CastExportsToImportType(new Export[0]);
}
}
useImportValue(import, definition, value);
}
result.ThrowOnErrors();
}
private bool TryGetImportValue(ImportDefinition definition, out object value)
{
lock (_lock)
{
if (_importValues != null && ImportValues.TryGetValue(definition, out value))
{
ImportValues.Remove(definition);
return true;
}
}
value = null;
return false;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void NotifyImportSatisfied()
{
if (_invokeImportsSatisfied)
{
IPartImportsSatisfiedNotification notify = GetInstanceActivatingIfNeeded() as IPartImportsSatisfiedNotification;
lock (_lock)
{
if (!_invokeImportsSatisfied)
{
//Already notified on another thread
return;
}
_invokeImportsSatisfied = false;
}
if (notify != null)
{
try
{
notify.OnImportsSatisfied();
}
catch (Exception exception)
{
throw new ComposablePartException(
String.Format(CultureInfo.CurrentCulture,
SR.ReflectionModel_PartOnImportsSatisfiedThrewException,
Definition.GetPartType().FullName),
Definition.ToElement(),
exception);
}
}
}
}
// this is always called under a lock
private ExportingMember GetExportingMemberFromDefinition(ExportDefinition definition)
{
ExportingMember result;
ReflectionMemberExportDefinition reflectionExport = definition as ReflectionMemberExportDefinition;
if (reflectionExport == null)
{
return null;
}
int exportIndex = reflectionExport.GetIndex();
if(_exportsCache == null)
{
_exportsCache = new Dictionary<int, ExportingMember>();
}
if (!_exportsCache.TryGetValue(exportIndex, out result))
{
result = GetExportingMember(definition);
if (result != null)
{
_exportsCache[exportIndex] = result;
}
}
return result;
}
private ImportingItem GetImportingItemFromDefinition(ImportDefinition definition)
{
ImportingItem result;
if (!ImportsCache.TryGetValue(definition, out result))
{
result = GetImportingItem(definition);
if (result != null)
{
ImportsCache[definition] = result;
}
}
return result;
}
private static ImportingItem GetImportingItem(ImportDefinition definition)
{
ReflectionImportDefinition reflectionDefinition = definition as ReflectionImportDefinition;
if (reflectionDefinition != null)
{
return reflectionDefinition.ToImportingItem();
}
// Don't recognize it
return null;
}
private static ExportingMember GetExportingMember(ExportDefinition definition)
{
ReflectionMemberExportDefinition exportDefinition = definition as ReflectionMemberExportDefinition;
if (exportDefinition != null)
{
return exportDefinition.ToExportingMember();
}
// Don't recognize it
return null;
}
private string GetDisplayName()
{
return _definition.GetPartType().GetDisplayName();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public partial class SByteTests
{
[Fact]
public static void Ctor_Empty()
{
var i = new sbyte();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
sbyte i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7F, sbyte.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(-0x80, sbyte.MinValue);
}
[Theory]
[InlineData((sbyte)114, (sbyte)114, 0)]
[InlineData((sbyte)114, sbyte.MinValue, 1)]
[InlineData((sbyte)114, (sbyte)-123, 1)]
[InlineData((sbyte)114, (sbyte)0, 1)]
[InlineData((sbyte)114, (sbyte)123, -1)]
[InlineData((sbyte)114, sbyte.MaxValue, -1)]
[InlineData((sbyte)114, null, 1)]
public void CompareTo_Other_ReturnsExpected(sbyte i, object value, int expected)
{
if (value is sbyte sbyteValue)
{
Assert.Equal(expected, Math.Sign(i.CompareTo(sbyteValue)));
}
Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
[Theory]
[InlineData("a")]
[InlineData(234)]
public void CompareTo_ObjectNotSByte_ThrowsArgumentException(object value)
{
AssertExtensions.Throws<ArgumentException>(null, () => ((sbyte)123).CompareTo(value));
}
[Theory]
[InlineData((sbyte)78, (sbyte)78, true)]
[InlineData((sbyte)78, (sbyte)-78, false)]
[InlineData((sbyte)78, (sbyte)0, false)]
[InlineData((sbyte)0, (sbyte)0, true)]
[InlineData((sbyte)-78, (sbyte)-78, true)]
[InlineData((sbyte)-78, (sbyte)78, false)]
[InlineData((sbyte)78, null, false)]
[InlineData((sbyte)78, "78", false)]
[InlineData((sbyte)78, 78, false)]
public static void Equals(sbyte i1, object obj, bool expected)
{
if (obj is sbyte)
{
sbyte i2 = (sbyte)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
[Fact]
public void GetTypeCode_Invoke_ReturnsSByte()
{
Assert.Equal(TypeCode.SByte, ((sbyte)1).GetTypeCode());
}
public static IEnumerable<object[]> ToString_TestData()
{
foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo })
{
yield return new object[] { sbyte.MinValue, "G", defaultFormat, "-128" };
yield return new object[] { (sbyte)-123, "G", defaultFormat, "-123" };
yield return new object[] { (sbyte)0, "G", defaultFormat, "0" };
yield return new object[] { (sbyte)123, "G", defaultFormat, "123" };
yield return new object[] { sbyte.MaxValue, "G", defaultFormat, "127" };
yield return new object[] { (sbyte)123, "D", defaultFormat, "123" };
yield return new object[] { (sbyte)123, "D99", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123" };
yield return new object[] { (sbyte)(-123), "D99", defaultFormat, "-000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000123" };
yield return new object[] { (sbyte)0x24, "x", defaultFormat, "24" };
yield return new object[] { (sbyte)24, "N", defaultFormat, string.Format("{0:N}", 24.00) };
}
var customFormat = new NumberFormatInfo()
{
NegativeSign = "#",
NumberDecimalSeparator = "~",
NumberGroupSeparator = "*",
PositiveSign = "&",
NumberDecimalDigits = 2,
PercentSymbol = "@",
PercentGroupSeparator = ",",
PercentDecimalSeparator = ".",
PercentDecimalDigits = 5
};
yield return new object[] { (sbyte)-24, "N", customFormat, "#24~00" };
yield return new object[] { (sbyte)24, "N", customFormat, "24~00" };
yield return new object[] { (sbyte)123, "E", customFormat, "1~230000E&002" };
yield return new object[] { (sbyte)123, "F", customFormat, "123~00" };
yield return new object[] { (sbyte)123, "P", customFormat, "12,300.00000 @" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(sbyte i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
IComparable comparable = (sbyte)123;
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a sbyte
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a sbyte
}
public static IEnumerable<object[]> ParseValidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
yield return new object[] { "-123", defaultStyle, defaultFormat, (sbyte)-123 };
yield return new object[] { "0", defaultStyle, defaultFormat, (sbyte)0 };
yield return new object[] { "123", defaultStyle, defaultFormat, (sbyte)123 };
yield return new object[] { " 123 ", defaultStyle, defaultFormat, (sbyte)123 };
yield return new object[] { "127", defaultStyle, defaultFormat, (sbyte)127 };
yield return new object[] { "12", NumberStyles.HexNumber, defaultFormat, (sbyte)0x12 };
yield return new object[] { "10", NumberStyles.AllowThousands, defaultFormat, (sbyte)10 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, (sbyte)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyNfi, (sbyte)123 };
yield return new object[] { "123", NumberStyles.Any, emptyNfi, (sbyte)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, (sbyte)0x12 };
yield return new object[] { "$100", NumberStyles.Currency, testNfi, (sbyte)100 };
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "-123", defaultStyle, null, (sbyte)-123 };
yield return new object[] { "0", defaultStyle, null, (sbyte)0 };
yield return new object[] { "123", defaultStyle, null, (sbyte)123 };
yield return new object[] { "+123", defaultStyle, null, (sbyte)123 };
yield return new object[] { " 123 ", defaultStyle, null, (sbyte)123 };
yield return new object[] { "127", defaultStyle, null, (sbyte)127 };
yield return new object[] { "12", NumberStyles.HexNumber, null, (sbyte)0x12 };
yield return new object[] { "10", NumberStyles.AllowThousands, null, (sbyte)10 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (sbyte)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyFormat, (sbyte)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (sbyte)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (sbyte)0x12 };
yield return new object[] { "a", NumberStyles.HexNumber, null, (sbyte)0xa };
yield return new object[] { "A", NumberStyles.HexNumber, null, (sbyte)0xa };
yield return new object[] { "$100", NumberStyles.Currency, customFormat, (sbyte)100 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, sbyte expected)
{
sbyte result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(sbyte.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, sbyte.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, sbyte.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(sbyte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, sbyte.Parse(value, style));
}
Assert.Equal(expected, sbyte.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "ab", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 100.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 67.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "ab", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-129", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "128", defaultStyle, null, typeof(OverflowException) }; // > max value
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
sbyte result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(sbyte.TryParse(value, out result));
Assert.Equal(default(sbyte), result);
Assert.Throws(exceptionType, () => sbyte.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => sbyte.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(sbyte.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(sbyte), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => sbyte.Parse(value, style));
}
Assert.Throws(exceptionType, () => sbyte.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName)
{
sbyte result = 0;
AssertExtensions.Throws<ArgumentException>(paramName, () => sbyte.TryParse("1", style, null, out result));
Assert.Equal(default(sbyte), result);
AssertExtensions.Throws<ArgumentException>(paramName, () => sbyte.Parse("1", style));
AssertExtensions.Throws<ArgumentException>(paramName, () => sbyte.Parse("1", style, null));
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.Fees;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Positions;
using QuantConnect.Util;
namespace QuantConnect.Brokerages.Backtesting
{
/// <summary>
/// Represents a brokerage to be used during backtesting. This is intended to be only be used with the BacktestingTransactionHandler
/// </summary>
public class BacktestingBrokerage : Brokerage
{
// flag used to indicate whether or not we need to scan for
// fills, this is purely a performance concern is ConcurrentDictionary.IsEmpty
// is not exactly the fastest operation and Scan gets called at least twice per
// time loop
private bool _needsScan;
private readonly ConcurrentDictionary<int, Order> _pending;
private readonly object _needsScanLock = new object();
private readonly HashSet<Symbol> _pendingOptionAssignments = new HashSet<Symbol>();
/// <summary>
/// This is the algorithm under test
/// </summary>
protected readonly IAlgorithm Algorithm;
/// <summary>
/// Creates a new BacktestingBrokerage for the specified algorithm
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
public BacktestingBrokerage(IAlgorithm algorithm)
: base("Backtesting Brokerage")
{
Algorithm = algorithm;
_pending = new ConcurrentDictionary<int, Order>();
}
/// <summary>
/// Creates a new BacktestingBrokerage for the specified algorithm
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="name">The name of the brokerage</param>
protected BacktestingBrokerage(IAlgorithm algorithm, string name)
: base(name)
{
Algorithm = algorithm;
_pending = new ConcurrentDictionary<int, Order>();
}
/// <summary>
/// Creates a new BacktestingBrokerage for the specified algorithm. Adds market simulation to BacktestingBrokerage;
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="marketSimulation">The backtesting market simulation instance</param>
public BacktestingBrokerage(IAlgorithm algorithm, IBacktestingMarketSimulation marketSimulation)
: base("Backtesting Brokerage")
{
Algorithm = algorithm;
MarketSimulation = marketSimulation;
_pending = new ConcurrentDictionary<int, Order>();
}
/// <summary>
/// Gets the connection status
/// </summary>
/// <remarks>
/// The BacktestingBrokerage is always connected
/// </remarks>
public override bool IsConnected => true;
/// <summary>
/// Gets all open orders on the account
/// </summary>
/// <returns>The open orders returned from IB</returns>
public override List<Order> GetOpenOrders()
{
return Algorithm.Transactions.GetOpenOrders().ToList();
}
/// <summary>
/// Gets all holdings for the account
/// </summary>
/// <returns>The current holdings from the account</returns>
public override List<Holding> GetAccountHoldings()
{
// grab everything from the portfolio with a non-zero absolute quantity
return (from kvp in Algorithm.Portfolio.Securities.OrderBy(x => x.Value.Symbol)
where kvp.Value.Holdings.AbsoluteQuantity > 0
select new Holding(kvp.Value)).ToList();
}
/// <summary>
/// Gets the current cash balance for each currency held in the brokerage account
/// </summary>
/// <returns>The current cash balance for each currency available for trading</returns>
public override List<CashAmount> GetCashBalance()
{
return Algorithm.Portfolio.CashBook.Select(x => new CashAmount(x.Value.Amount, x.Value.Symbol)).ToList();
}
/// <summary>
/// Places a new order and assigns a new broker ID to the order
/// </summary>
/// <param name="order">The order to be placed</param>
/// <returns>True if the request for a new order has been placed, false otherwise</returns>
public override bool PlaceOrder(Order order)
{
if (Algorithm.LiveMode)
{
Log.Trace("BacktestingBrokerage.PlaceOrder(): Type: " + order.Type + " Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity);
}
if (order.Status == OrderStatus.New)
{
lock (_needsScanLock)
{
_needsScan = true;
SetPendingOrder(order);
}
var orderId = order.Id.ToStringInvariant();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId);
// fire off the event that says this order has been submitted
var submitted = new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{ Status = OrderStatus.Submitted };
OnOrderEvent(submitted);
return true;
}
return false;
}
/// <summary>
/// Updates the order with the same ID
/// </summary>
/// <param name="order">The new order information</param>
/// <returns>True if the request was made for the order to be updated, false otherwise</returns>
public override bool UpdateOrder(Order order)
{
if (Algorithm.LiveMode)
{
Log.Trace("BacktestingBrokerage.UpdateOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity + " Status: " + order.Status);
}
lock (_needsScanLock)
{
Order pending;
if (!_pending.TryGetValue(order.Id, out pending))
{
// can't update something that isn't there
return false;
}
_needsScan = true;
SetPendingOrder(order);
}
var orderId = order.Id.ToStringInvariant();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(orderId);
// fire off the event that says this order has been updated
var updated = new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{
Status = OrderStatus.UpdateSubmitted
};
OnOrderEvent(updated);
return true;
}
/// <summary>
/// Cancels the order with the specified ID
/// </summary>
/// <param name="order">The order to cancel</param>
/// <returns>True if the request was made for the order to be canceled, false otherwise</returns>
public override bool CancelOrder(Order order)
{
if (Algorithm.LiveMode)
{
Log.Trace("BacktestingBrokerage.CancelOrder(): Symbol: " + order.Symbol.Value + " Quantity: " + order.Quantity);
}
lock (_needsScanLock)
{
Order pending;
if (!_pending.TryRemove(order.Id, out pending))
{
// can't cancel something that isn't there
return false;
}
}
var orderId = order.Id.ToStringInvariant();
if (!order.BrokerId.Contains(orderId)) order.BrokerId.Add(order.Id.ToStringInvariant());
// fire off the event that says this order has been canceled
var canceled = new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{ Status = OrderStatus.Canceled };
OnOrderEvent(canceled);
return true;
}
/// <summary>
/// Market Simulation - simulates various market conditions in backtest
/// </summary>
public IBacktestingMarketSimulation MarketSimulation { get; set; }
/// <summary>
/// Scans all the outstanding orders and applies the algorithm model fills to generate the order events
/// </summary>
public virtual void Scan()
{
lock (_needsScanLock)
{
// there's usually nothing in here
if (!_needsScan)
{
return;
}
var stillNeedsScan = false;
// process each pending order to produce fills/fire events
foreach (var kvp in _pending.OrderBySafe(x => x.Key))
{
var order = kvp.Value;
if (order == null)
{
Log.Error("BacktestingBrokerage.Scan(): Null pending order found: " + kvp.Key);
_pending.TryRemove(kvp.Key, out order);
continue;
}
if (order.Status.IsClosed())
{
// this should never actually happen as we always remove closed orders as they happen
_pending.TryRemove(order.Id, out order);
continue;
}
// all order fills are processed on the next bar (except for market orders)
if (order.Time == Algorithm.UtcTime && order.Type != OrderType.Market && order.Type != OrderType.OptionExercise)
{
stillNeedsScan = true;
continue;
}
var fills = new OrderEvent[0];
Security security;
if (!Algorithm.Securities.TryGetValue(order.Symbol, out security))
{
Log.Error("BacktestingBrokerage.Scan(): Unable to process order: " + order.Id + ". The security no longer exists.");
// invalidate the order in the algorithm before removing
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{Status = OrderStatus.Invalid});
_pending.TryRemove(order.Id, out order);
continue;
}
if (order.Type == OrderType.MarketOnOpen)
{
// This is a performance improvement:
// Since MOO should never fill on the same bar or on stale data (see FillModel)
// the order can remain unfilled for multiple 'scans', so we want to avoid
// margin and portfolio calculations since they are expensive
var currentBar = security.GetLastData();
var localOrderTime = order.Time.ConvertFromUtc(security.Exchange.TimeZone);
if (currentBar == null || localOrderTime >= currentBar.EndTime)
{
stillNeedsScan = true;
continue;
}
}
// check if the time in force handler allows fills
if (order.TimeInForce.IsOrderExpired(security, order))
{
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero)
{
Status = OrderStatus.Canceled,
Message = "The order has expired."
});
_pending.TryRemove(order.Id, out order);
continue;
}
// check if we would actually be able to fill this
if (!Algorithm.BrokerageModel.CanExecuteOrder(security, order))
{
continue;
}
// verify sure we have enough cash to perform the fill
HasSufficientBuyingPowerForOrderResult hasSufficientBuyingPowerResult;
try
{
var group = Algorithm.Portfolio.Positions.CreatePositionGroup(order);
hasSufficientBuyingPowerResult = group.BuyingPowerModel.HasSufficientBuyingPowerForOrder(
new HasSufficientPositionGroupBuyingPowerForOrderParameters(Algorithm.Portfolio, group, order)
);
}
catch (Exception err)
{
// if we threw an error just mark it as invalid and remove the order from our pending list
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero,
err.Message)
{ Status = OrderStatus.Invalid });
Order pending;
_pending.TryRemove(order.Id, out pending);
Log.Error(err);
Algorithm.Error($"Order Error: id: {order.Id}, Error executing margin models: {err.Message}");
continue;
}
//Before we check this queued order make sure we have buying power:
if (hasSufficientBuyingPowerResult.IsSufficient)
{
//Model:
var model = security.FillModel;
//Based on the order type: refresh its model to get fill price and quantity
try
{
if (order.Type == OrderType.OptionExercise)
{
var option = (Option)security;
fills = option.OptionExerciseModel.OptionExercise(option, order as OptionExerciseOrder).ToArray();
}
else
{
var context = new FillModelParameters(
security,
order,
Algorithm.SubscriptionManager.SubscriptionDataConfigService,
Algorithm.Settings.StalePriceTimeSpan);
fills = new[] { model.Fill(context).OrderEvent };
}
// invoke fee models for completely filled order events
foreach (var fill in fills)
{
if (fill.Status == OrderStatus.Filled)
{
// this check is provided for backwards compatibility of older user-defined fill models
// that may be performing fee computation inside the fill model w/out invoking the fee model
// TODO : This check can be removed in April, 2019 -- a 6-month window to upgrade (also, suspect small % of users, if any are impacted)
if (fill.OrderFee.Value.Amount == 0m)
{
fill.OrderFee = security.FeeModel.GetOrderFee(
new OrderFeeParameters(security,
order));
}
}
}
}
catch (Exception err)
{
Log.Error(err);
Algorithm.Error($"Order Error: id: {order.Id}, Transaction model failed to fill for order type: {order.Type} with error: {err.Message}");
}
}
else if (order.Status == OrderStatus.CancelPending)
{
// the pending CancelOrderRequest will be handled during the next transaction handler run
continue;
}
else
{
// invalidate the order in the algorithm before removing
var message = $"Insufficient buying power to complete order (Value:{order.GetValue(security).SmartRounding()}), Reason: {hasSufficientBuyingPowerResult.Reason}.";
OnOrderEvent(new OrderEvent(order,
Algorithm.UtcTime,
OrderFee.Zero,
message)
{ Status = OrderStatus.Invalid });
Order pending;
_pending.TryRemove(order.Id, out pending);
Algorithm.Error($"Order Error: id: {order.Id}, {message}");
continue;
}
foreach (var fill in fills)
{
// check if the fill should be emitted
if (!order.TimeInForce.IsFillValid(security, order, fill))
{
break;
}
// change in status or a new fill
if (order.Status != fill.Status || fill.FillQuantity != 0)
{
// we update the order status so we do not re process it if we re enter
// because of the call to OnOrderEvent.
// Note: this is done by the transaction handler but we have a clone of the order
order.Status = fill.Status;
//If the fill models come back suggesting filled, process the affects on portfolio
OnOrderEvent(fill);
}
if (fill.IsAssignment)
{
fill.Message = order.Tag;
OnOptionPositionAssigned(fill);
}
}
if (fills.All(x => x.Status.IsClosed()))
{
_pending.TryRemove(order.Id, out order);
}
else
{
stillNeedsScan = true;
}
}
// if we didn't fill then we need to continue to scan or
// if there are still pending orders
_needsScan = stillNeedsScan || !_pending.IsEmpty;
}
}
/// <summary>
/// Runs market simulation
/// </summary>
public void SimulateMarket()
{
// if simulator is installed, we run it
MarketSimulation?.SimulateMarketConditions(this, Algorithm);
}
/// <summary>
/// This method is called by market simulator in order to launch an assignment event
/// </summary>
/// <param name="option">Option security to assign</param>
/// <param name="quantity">Quantity to assign</param>
public virtual void ActivateOptionAssignment(Option option, int quantity)
{
// do not process the same assignment more than once
if (_pendingOptionAssignments.Contains(option.Symbol)) return;
_pendingOptionAssignments.Add(option.Symbol);
// assignments always cause a positive change to option contract holdings
var request = new SubmitOrderRequest(OrderType.OptionExercise, option.Type, option.Symbol, Math.Abs(quantity), 0m, 0m, 0m, Algorithm.UtcTime, "Simulated option assignment before expiration");
var ticket = Algorithm.Transactions.ProcessRequest(request);
Log.Trace($"BacktestingBrokerage.ActivateOptionAssignment(): OrderId: {ticket.OrderId}");
}
/// <summary>
/// Event invocator for the OrderFilled event
/// </summary>
/// <param name="e">The OrderEvent</param>
protected override void OnOrderEvent(OrderEvent e)
{
if (e.Status.IsClosed() && _pendingOptionAssignments.Contains(e.Symbol))
{
_pendingOptionAssignments.Remove(e.Symbol);
}
base.OnOrderEvent(e);
}
/// <summary>
/// The BacktestingBrokerage is always connected. This is a no-op.
/// </summary>
public override void Connect()
{
//NOP
}
/// <summary>
/// The BacktestingBrokerage is always connected. This is a no-op.
/// </summary>
public override void Disconnect()
{
//NOP
}
/// <summary>
/// Sets the pending order as a clone to prevent object reference nastiness
/// </summary>
/// <param name="order">The order to be added to the pending orders dictionary</param>
/// <returns></returns>
private void SetPendingOrder(Order order)
{
_pending[order.Id] = order;
}
/// <summary>
/// Process delistings
/// </summary>
/// <param name="delistings">Delistings to process</param>
public void ProcessDelistings(Delistings delistings)
{
// Process our delistings, important to do options first because of possibility of having future options contracts
// and underlying future delisting at the same time.
foreach (var delisting in delistings?.Values.OrderBy(x => !x.Symbol.SecurityType.IsOption()))
{
Log.Trace($"BacktestingBrokerage.ProcessDelistings(): Delisting {delisting.Type}: {delisting.Symbol.Value}, UtcTime: {Algorithm.UtcTime}, DelistingTime: {delisting.Time}");
if (delisting.Type == DelistingType.Warning)
{
// We do nothing with warnings
continue;
}
var security = Algorithm.Securities[delisting.Symbol];
if (security.Symbol.SecurityType.IsOption())
{
// Process the option delisting
OnOptionNotification(new OptionNotificationEventArgs(delisting.Symbol, 0));
}
else
{
// Any other type of delisting
OnDelistingNotification(new DelistingNotificationEventArgs(delisting.Symbol));
}
// don't allow users to open a new position once we sent the liquidation order
security.IsTradable = false;
security.IsDelisted = true;
// the subscription are getting removed from the data feed because they end
// remove security from all universes
foreach (var ukvp in Algorithm.UniverseManager)
{
var universe = ukvp.Value;
if (universe.ContainsMember(security.Symbol))
{
var userUniverse = universe as UserDefinedUniverse;
if (userUniverse != null)
{
userUniverse.Remove(security.Symbol);
}
else
{
universe.RemoveMember(Algorithm.UtcTime, security);
}
}
}
// Cancel any other orders
var cancelledOrders = Algorithm.Transactions.CancelOpenOrders(delisting.Symbol);
foreach (var cancelledOrder in cancelledOrders)
{
Log.Trace("AlgorithmManager.Run(): " + cancelledOrder);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Plugins;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
using System.Globalization;
public class TripleSlashCommentModel
{
private const string idSelector = @"((?![0-9])[\w_])+[\w\(\)\.\{\}\[\]\|\*\^~#@!`,_<>:]*";
private static Regex CommentIdRegex = new Regex(@"^(?<type>N|T|M|P|F|E|Overload):(?<id>" + idSelector + ")$", RegexOptions.Compiled);
private static Regex LineBreakRegex = new Regex(@"\r?\n", RegexOptions.Compiled);
private static Regex CodeElementRegex = new Regex(@"<code[^>]*>([\s\S]*?)</code>", RegexOptions.Compiled);
private static Regex RegionRegex = new Regex(@"^\s*#region\s*(.*)$");
private static Regex EndRegionRegex = new Regex(@"^\s*#endregion\s*.*$");
private readonly ITripleSlashCommentParserContext _context;
public string Summary { get; private set; }
public string Remarks { get; private set; }
public string Returns { get; private set; }
public List<ExceptionInfo> Exceptions { get; private set; }
public List<LinkInfo> Sees { get; private set; }
public List<LinkInfo> SeeAlsos { get; private set; }
public List<string> Examples { get; private set; }
public Dictionary<string, string> Parameters { get; private set; }
public Dictionary<string, string> TypeParameters { get; private set; }
public bool IsInheritDoc { get; private set; }
private TripleSlashCommentModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context)
{
// Transform triple slash comment
XDocument doc = TripleSlashCommentTransformer.Transform(xml, language);
_context = context;
if (!context.PreserveRawInlineComments)
{
ResolveSeeCref(doc, context.AddReferenceDelegate);
ResolveSeeAlsoCref(doc, context.AddReferenceDelegate);
}
ResolveCodeSource(doc, context);
var nav = doc.CreateNavigator();
Summary = GetSummary(nav, context);
Remarks = GetRemarks(nav, context);
Returns = GetReturns(nav, context);
Exceptions = GetExceptions(nav, context);
Sees = GetSees(nav, context);
SeeAlsos = GetSeeAlsos(nav, context);
Examples = GetExamples(nav, context);
Parameters = GetParameters(nav, context);
TypeParameters = GetTypeParameters(nav, context);
IsInheritDoc = GetIsInheritDoc(nav, context);
}
public static TripleSlashCommentModel CreateModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (string.IsNullOrEmpty(xml)) return null;
// Quick turnaround for badly formed XML comment
if (xml.StartsWith("<!-- Badly formed XML comment ignored for member "))
{
Logger.LogWarning($"Invalid triple slash comment is ignored: {xml}");
return null;
}
try
{
var model = new TripleSlashCommentModel(xml, language, context);
return model;
}
catch (XmlException)
{
return null;
}
}
public void CopyInheritedData(TripleSlashCommentModel src)
{
if (src == null)
throw new ArgumentNullException(nameof(src));
if (Summary == null)
Summary = src.Summary;
if (Remarks == null)
Remarks = src.Remarks;
if (Returns == null)
Returns = src.Returns;
if (Exceptions == null && src.Exceptions != null)
Exceptions = src.Exceptions.Select(e => e.Clone()).ToList();
if (Sees == null && src.Sees != null)
Sees = src.Sees.Select(s => s.Clone()).ToList();
if (SeeAlsos == null && src.SeeAlsos != null)
SeeAlsos = src.SeeAlsos.Select(s => s.Clone()).ToList();
if (Examples == null && src.Examples != null)
Examples = new List<string>(src.Examples);
if (Parameters == null && src.Parameters != null)
Parameters = new Dictionary<string, string>(src.Parameters);
if (TypeParameters == null && src.TypeParameters != null)
TypeParameters = new Dictionary<string, string>(src.TypeParameters);
}
public string GetParameter(string name)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
return GetValue(name, Parameters);
}
public string GetTypeParameter(string name)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
return GetValue(name, TypeParameters);
}
private static string GetValue(string name, Dictionary<string, string> dictionary)
{
if (dictionary == null) return null;
string description;
if (dictionary.TryGetValue(name, out description))
{
return description;
}
return null;
}
/// <summary>
/// Get summary node out from triple slash comments
/// </summary>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
/// <example>
/// <code> <see cref="Hello"/></code>
/// </example>
private string GetSummary(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
string selector = "/member/summary";
return GetSingleNodeValue(nav, selector);
}
/// <summary>
/// Get remarks node out from triple slash comments
/// </summary>
/// <remarks>
/// <para>This is a sample of exception node</para>
/// </remarks>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
private string GetRemarks(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
string selector = "/member/remarks";
return GetSingleNodeValue(nav, selector);
}
private string GetReturns(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
string selector = "/member/returns";
return GetSingleNodeValue(nav, selector);
}
/// <summary>
/// Get exceptions nodes out from triple slash comments
/// </summary>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
/// <exception cref="XmlException">This is a sample of exception node</exception>
private List<ExceptionInfo> GetExceptions(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
string selector = "/member/exception";
var result = GetMulitpleCrefInfo(nav, selector).ToList();
if (result.Count == 0) return null;
return result;
}
/// <summary>
/// To get `see` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <see cref="SpecIdHelper"/>
/// <see cref="SourceSwitch"/>
private List<LinkInfo> GetSees(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var result = GetMultipleLinkInfo(nav, "/member/see").ToList();
if (result.Count == 0) return null;
return result;
}
/// <summary>
/// To get `seealso` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <seealso cref="WaitForChangedResult"/>
/// <seealso cref="http://google.com">ABCS</seealso>
private List<LinkInfo> GetSeeAlsos(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var result = GetMultipleLinkInfo(nav, "/member/seealso").ToList();
if (result.Count == 0) return null;
return result;
}
/// <summary>
/// To get `example` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <example>
/// This sample shows how to call the <see cref="GetExceptions(string, ITripleSlashCommentParserContext)"/> method.
/// <code>
/// class TestClass
/// {
/// static int Main()
/// {
/// return GetExceptions(null, null).Count();
/// }
/// }
/// </code>
/// </example>
private List<string> GetExamples(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
return GetMultipleExampleNodes(nav, "/member/example").ToList();
}
private bool GetIsInheritDoc(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var node = nav.SelectSingleNode("/member/inheritdoc");
if (node == null)
return false;
if (node.HasAttributes)
{
//The Sandcastle implementation of <inheritdoc /> supports two attributes: 'cref' and 'select'.
//These attributes allow changing the source of the inherited doc and controlling what is inherited.
//Until these attributes are supported, ignoring inheritdoc elements with attributes, so as not to misinterpret them.
Logger.LogWarning("Attributes on <inheritdoc /> elements are not supported; inheritdoc element will be ignored.");
return false;
}
return true;
}
private void ResolveCodeSource(XDocument doc, ITripleSlashCommentParserContext context)
{
foreach (XElement node in doc.XPathSelectElements("//code"))
{
var source = node.Attribute("source");
if (source == null || string.IsNullOrEmpty(source.Value))
{
continue;
}
if (context.Source == null || string.IsNullOrEmpty(context.Source.Path))
{
Logger.LogWarning($"Unable to get source file path for {node.ToString()}");
return;
}
var region = node.Attribute("region");
var path = source.Value;
if (!Path.IsPathRooted(path))
{
string currentFilePath = context.Source.Remote != null ? Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Remote.RelativePath) : context.Source.Path;
var directory = Path.GetDirectoryName(currentFilePath);
path = Path.Combine(directory, path);
}
ResolveCodeSource(node, path, region.Value);
}
}
private void ResolveCodeSource(XElement element, string source, string region)
{
if (!File.Exists(source))
{
Logger.LogWarning($"Source file '{source}' not found.");
return;
}
var builder = new StringBuilder();
var regionCount = 0;
foreach (var line in File.ReadLines(source))
{
var match = RegionRegex.Match(line);
if (match.Success)
{
var name = match.Groups[1].Value.Trim();
if (name == region)
{
++regionCount;
continue;
}
else if (regionCount > 0)
{
++regionCount;
}
}
else if (regionCount > 0 && EndRegionRegex.IsMatch(line))
{
--regionCount;
if (regionCount == 0)
{
break;
}
}
if (string.IsNullOrEmpty(region) || regionCount > 0)
{
builder.AppendLine(line);
}
}
element.SetValue(builder.ToString());
}
private Dictionary<string, string> GetListContent(XPathNavigator navigator, string xpath, string contentType, ITripleSlashCommentParserContext context)
{
var iterator = navigator.Select(xpath);
var result = new Dictionary<string, string>();
if (iterator == null) return result;
foreach (XPathNavigator nav in iterator)
{
string name = nav.GetAttribute("name", string.Empty);
string description = GetXmlValue(nav);
if (!string.IsNullOrEmpty(name))
{
if (result.ContainsKey(name))
{
string path = context.Source.Remote != null ? Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Remote.RelativePath) : context.Source.Path;
Logger.LogWarning($"Duplicate {contentType} '{name}' found in comments, the latter one is ignored.", file: StringExtension.ToDisplayPath(path), line: context.Source.StartLine.ToString());
}
else
{
result.Add(name, description);
}
}
}
return result;
}
private Dictionary<string, string> GetParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context)
{
return GetListContent(navigator, "/member/param", "parameter", context);
}
private Dictionary<string, string> GetTypeParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context)
{
return GetListContent(navigator, "/member/typeparam", "type parameter", context);
}
private void ResolveSeeAlsoCref(XNode node, Action<string, string> addReference)
{
// Resolve <see cref> to <xref>
ResolveCrefLink(node, "//seealso[@cref]", addReference);
}
private void ResolveSeeCref(XNode node, Action<string, string> addReference)
{
// Resolve <see cref> to <xref>
ResolveCrefLink(node, "//see[@cref]", addReference);
}
private void ResolveCrefLink(XNode node, string nodeSelector, Action<string, string> addReference)
{
if (node == null || string.IsNullOrEmpty(nodeSelector)) return;
try
{
var nodes = node.XPathSelectElements(nodeSelector + "[@cref]").ToList();
foreach (var item in nodes)
{
var cref = item.Attribute("cref").Value;
// Strict check is needed as value could be an invalid href,
// e.g. !:Dictionary<TKey, string> when user manually changed the intellisensed generic type
var match = CommentIdRegex.Match(cref);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "Overload")
{
id += '*';
}
// When see and seealso are top level nodes in triple slash comments, do not convert it into xref node
if (item.Parent?.Parent != null)
{
var replacement = XElement.Parse($"<xref href=\"{HttpUtility.UrlEncode(id)}\" data-throw-if-not-resolved=\"false\"></xref>");
item.ReplaceWith(replacement);
}
if (addReference != null)
{
addReference(id, cref);
}
}
else
{
var detailedInfo = new StringBuilder();
if (_context != null && _context.Source != null)
{
if (!string.IsNullOrEmpty(_context.Source.Name))
{
detailedInfo.Append(" for ");
detailedInfo.Append(_context.Source.Name);
}
if (!string.IsNullOrEmpty(_context.Source.Path))
{
detailedInfo.Append(" defined in ");
detailedInfo.Append(_context.Source.Path);
detailedInfo.Append(" Line ");
detailedInfo.Append(_context.Source.StartLine);
}
}
Logger.Log(LogLevel.Warning, $"Invalid cref value \"{cref}\" found in triple-slash-comments{detailedInfo}, ignored.");
}
}
}
catch
{
}
}
private IEnumerable<string> GetMultipleExampleNodes(XPathNavigator navigator, string selector)
{
var iterator = navigator.Select(selector);
if (iterator == null) yield break;
foreach (XPathNavigator nav in iterator)
{
string description = GetXmlValue(nav);
yield return description;
}
}
private IEnumerable<ExceptionInfo> GetMulitpleCrefInfo(XPathNavigator navigator, string selector)
{
var iterator = navigator.Clone().Select(selector);
if (iterator == null) yield break;
foreach (XPathNavigator nav in iterator)
{
string description = GetXmlValue(nav);
string commentId = nav.GetAttribute("cref", string.Empty);
if (!string.IsNullOrEmpty(commentId))
{
// Check if exception type is valid and trim prefix
var match = CommentIdRegex.Match(commentId);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "T")
{
if (string.IsNullOrEmpty(description)) description = null;
yield return new ExceptionInfo { Description = description, Type = id, CommentId = commentId };
}
}
}
}
}
private IEnumerable<LinkInfo> GetMultipleLinkInfo(XPathNavigator navigator, string selector)
{
var iterator = navigator.Clone().Select(selector);
if (iterator == null) yield break;
foreach (XPathNavigator nav in iterator)
{
string altText = GetXmlValue(nav);
if (string.IsNullOrEmpty(altText)) altText = null;
string commentId = nav.GetAttribute("cref", string.Empty);
string url = nav.GetAttribute("href", string.Empty);
if (!string.IsNullOrEmpty(commentId))
{
// Check if cref type is valid and trim prefix
var match = CommentIdRegex.Match(commentId);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "Overload")
{
id += '*';
}
yield return new LinkInfo { AltText = altText, LinkId = id, CommentId = commentId, LinkType = LinkType.CRef };
}
}
else if (!string.IsNullOrEmpty(url))
{
yield return new LinkInfo { AltText = altText ?? url, LinkId = url, LinkType = LinkType.HRef };
}
}
}
private string GetSingleNodeValue(XPathNavigator nav, string selector)
{
var node = nav.Clone().SelectSingleNode(selector);
if (node == null)
{
// throw new ArgumentException(selector + " is not found");
return null;
}
else
{
var output = GetXmlValue(node);
return output;
}
}
private string GetXmlValue(XPathNavigator node)
{
// NOTE: use node.InnerXml instead of node.Value, to keep decorative nodes,
// e.g.
// <remarks><para>Value</para></remarks>
// decode InnerXml as it encodes
// IXmlLineInfo.LinePosition starts from 1 and it would ignore '<'
// e.g.
// <summary/> the LinePosition is the column number of 's', so it should be minus 2
var lineInfo = node as IXmlLineInfo;
int column = lineInfo.HasLineInfo() ? lineInfo.LinePosition - 2 : 0;
return NormalizeXml(RemoveLeadingSpaces(GetInnerXml(node)), column);
}
/// <summary>
/// Remove least common whitespces in each line of xml
/// </summary>
/// <param name="xml"></param>
/// <returns>xml after removing least common whitespaces</returns>
private static string RemoveLeadingSpaces(string xml)
{
var lines = LineBreakRegex.Split(xml);
var normalized = new List<string>();
var preIndex = 0;
var leadingSpaces = from line in lines
where !string.IsNullOrWhiteSpace(line)
select line.TakeWhile(char.IsWhiteSpace).Count();
if (leadingSpaces.Any())
{
preIndex = leadingSpaces.Min();
}
if (preIndex == 0)
{
return xml;
}
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
normalized.Add(string.Empty);
}
else
{
normalized.Add(line.Substring(preIndex));
}
}
return string.Join("\n", normalized);
}
/// <summary>
/// Split xml into lines. Trim meaningless whitespaces.
/// if a line starts with xml node, all leading whitespaces would be trimmed
/// otherwise text node start position always aligns with the start position of its parent line(the last previous line that starts with xml node)
/// Trim newline character for code element.
/// </summary>
/// <param name="xml"></param>
/// <param name="parentIndex">the start position of the last previous line that starts with xml node</param>
/// <returns>normalized xml</returns>
private static string NormalizeXml(string xml, int parentIndex)
{
var lines = LineBreakRegex.Split(xml);
var normalized = new List<string>();
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
normalized.Add(string.Empty);
}
else
{
// TO-DO: special logic for TAB case
int index = line.TakeWhile(char.IsWhiteSpace).Count();
if (line[index] == '<')
{
parentIndex = index;
}
normalized.Add(line.Substring(Math.Min(parentIndex, index)));
}
}
// trim newline character for code element
return CodeElementRegex.Replace(
string.Join("\n", normalized),
m =>
{
var group = m.Groups[1];
if (group.ToString() == string.Empty)
{
return m.Value;
}
return m.Value.Replace(group.ToString(), group.ToString().Trim('\n'));
});
}
/// <summary>
/// `>` is always encoded to `>` in XML, when triple-slash-comments is considered as Markdown content, `>` is considered as blockquote
/// Decode `>` to enable the Markdown syntax considering `>` is not a Must-Encode in Text XElement
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static string GetInnerXml(XPathNavigator node)
{
using (var sw = new StringWriter(CultureInfo.InvariantCulture))
{
using (var tw = new XmlWriterWithGtDecoded(sw))
{
if (node.MoveToFirstChild())
{
do
{
tw.WriteNode(node, true);
} while (node.MoveToNext());
node.MoveToParent();
}
}
return sw.ToString();
}
}
private sealed class XmlWriterWithGtDecoded : XmlTextWriter
{
public XmlWriterWithGtDecoded(TextWriter tw) : base(tw) { }
public XmlWriterWithGtDecoded(Stream w, Encoding encoding) : base(w, encoding) { }
public override void WriteString(string text)
{
var encoded = text.Replace("&", "&").Replace("<", "<").Replace("'", "'").Replace("\"", """);
base.WriteRaw(encoded);
}
}
}
}
| |
namespace Onychophora.Infra.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class migration : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.CustomFields",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 100, unicode: false),
Type = c.String(nullable: false, maxLength: 100, unicode: false),
Required = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Organizations",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 100, unicode: false),
ParentOrganization = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Organizations", t => t.ParentOrganization)
.Index(t => t.ParentOrganization);
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128, unicode: false),
Name = c.String(nullable: false, maxLength: 256, unicode: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.SpecimenCustomValues",
c => new
{
SpecimenId = c.Int(nullable: false),
CustomFieldId = c.Int(nullable: false),
Value = c.String(nullable: false, maxLength: 256, unicode: false),
})
.PrimaryKey(t => new { t.SpecimenId, t.CustomFieldId })
.ForeignKey("dbo.CustomFields", t => t.CustomFieldId)
.ForeignKey("dbo.Specimens", t => t.SpecimenId)
.Index(t => t.SpecimenId)
.Index(t => t.CustomFieldId);
CreateTable(
"dbo.Specimens",
c => new
{
Id = c.Int(nullable: false, identity: true),
Date = c.DateTime(nullable: false),
Public = c.Boolean(nullable: false),
ScientificName = c.String(nullable: false, maxLength: 100, unicode: false),
TaxonId = c.Int(nullable: false),
UserId = c.String(nullable: false, maxLength: 128, unicode: false),
OrganizationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Organizations", t => t.OrganizationId)
.ForeignKey("dbo.Taxa", t => t.TaxonId)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.TaxonId)
.Index(t => t.UserId)
.Index(t => t.OrganizationId);
CreateTable(
"dbo.Taxa",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128, unicode: false),
RankId = c.Int(nullable: false),
Author = c.String(maxLength: 128, unicode: false),
Year = c.Int(),
TaxonStatusId = c.Int(),
Synonyms = c.String(maxLength: 100, unicode: false),
ParentTaxonId = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Taxa", t => t.ParentTaxonId)
.ForeignKey("dbo.TaxonRanks", t => t.RankId)
.ForeignKey("dbo.TaxonStatus", t => t.TaxonStatusId)
.Index(t => t.RankId)
.Index(t => t.TaxonStatusId)
.Index(t => t.ParentTaxonId);
CreateTable(
"dbo.TaxonRanks",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 40, unicode: false),
ParentTaxonId = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.TaxonRanks", t => t.ParentTaxonId)
.Index(t => t.ParentTaxonId);
CreateTable(
"dbo.TaxonStatus",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 40, unicode: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128, unicode: false),
Email = c.String(maxLength: 256, unicode: false),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(unicode: false),
SecurityStamp = c.String(unicode: false),
PhoneNumber = c.String(unicode: false),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256, unicode: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.TaxonCustomFields",
c => new
{
TaxonId = c.Int(nullable: false),
CustomFieldId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.TaxonId, t.CustomFieldId })
.ForeignKey("dbo.CustomFields", t => t.CustomFieldId)
.ForeignKey("dbo.Taxa", t => t.TaxonId)
.Index(t => t.TaxonId)
.Index(t => t.CustomFieldId);
CreateTable(
"dbo.AspNetUserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128, unicode: false),
ClaimType = c.String(unicode: false),
ClaimValue = c.String(unicode: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128, unicode: false),
ProviderKey = c.String(nullable: false, maxLength: 128, unicode: false),
UserId = c.String(nullable: false, maxLength: 128, unicode: false),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId);
CreateTable(
"dbo.UserOrganizations",
c => new
{
UserId = c.String(nullable: false, maxLength: 128, unicode: false),
OrganizationId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.UserId, t.OrganizationId })
.ForeignKey("dbo.Organizations", t => t.OrganizationId)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId)
.Index(t => t.OrganizationId);
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128, unicode: false),
RoleId = c.String(nullable: false, maxLength: 128, unicode: false),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetRoles", t => t.RoleId)
.ForeignKey("dbo.AspNetUsers", t => t.UserId)
.Index(t => t.UserId)
.Index(t => t.RoleId);
}
public override void Down()
{
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles");
DropForeignKey("dbo.UserOrganizations", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.UserOrganizations", "OrganizationId", "dbo.Organizations");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.TaxonCustomFields", "TaxonId", "dbo.Taxa");
DropForeignKey("dbo.TaxonCustomFields", "CustomFieldId", "dbo.CustomFields");
DropForeignKey("dbo.SpecimenCustomValues", "SpecimenId", "dbo.Specimens");
DropForeignKey("dbo.Specimens", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.Specimens", "TaxonId", "dbo.Taxa");
DropForeignKey("dbo.Taxa", "TaxonStatusId", "dbo.TaxonStatus");
DropForeignKey("dbo.Taxa", "RankId", "dbo.TaxonRanks");
DropForeignKey("dbo.TaxonRanks", "ParentTaxonId", "dbo.TaxonRanks");
DropForeignKey("dbo.Taxa", "ParentTaxonId", "dbo.Taxa");
DropForeignKey("dbo.Specimens", "OrganizationId", "dbo.Organizations");
DropForeignKey("dbo.SpecimenCustomValues", "CustomFieldId", "dbo.CustomFields");
DropForeignKey("dbo.Organizations", "ParentOrganization", "dbo.Organizations");
DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" });
DropIndex("dbo.AspNetUserRoles", new[] { "UserId" });
DropIndex("dbo.UserOrganizations", new[] { "OrganizationId" });
DropIndex("dbo.UserOrganizations", new[] { "UserId" });
DropIndex("dbo.AspNetUserLogins", new[] { "UserId" });
DropIndex("dbo.AspNetUserClaims", new[] { "UserId" });
DropIndex("dbo.TaxonCustomFields", new[] { "CustomFieldId" });
DropIndex("dbo.TaxonCustomFields", new[] { "TaxonId" });
DropIndex("dbo.TaxonRanks", new[] { "ParentTaxonId" });
DropIndex("dbo.Taxa", new[] { "ParentTaxonId" });
DropIndex("dbo.Taxa", new[] { "TaxonStatusId" });
DropIndex("dbo.Taxa", new[] { "RankId" });
DropIndex("dbo.Specimens", new[] { "OrganizationId" });
DropIndex("dbo.Specimens", new[] { "UserId" });
DropIndex("dbo.Specimens", new[] { "TaxonId" });
DropIndex("dbo.SpecimenCustomValues", new[] { "CustomFieldId" });
DropIndex("dbo.SpecimenCustomValues", new[] { "SpecimenId" });
DropIndex("dbo.Organizations", new[] { "ParentOrganization" });
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.UserOrganizations");
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.TaxonCustomFields");
DropTable("dbo.AspNetUsers");
DropTable("dbo.TaxonStatus");
DropTable("dbo.TaxonRanks");
DropTable("dbo.Taxa");
DropTable("dbo.Specimens");
DropTable("dbo.SpecimenCustomValues");
DropTable("dbo.AspNetRoles");
DropTable("dbo.Organizations");
DropTable("dbo.CustomFields");
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlTypes;
public partial class Backoffice_Controls_EditRegistrasiLAB : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Draw(string RawatJalanId)
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.RawatJalanId = Int64.Parse(RawatJalanId);
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
HFRegistrasiId.Value = row["RegistrasiId"].ToString();
HFRawatJalanId.Value = row["RawatJalanId"].ToString();
HFPasienId.Value = row["PasienId"].ToString();
HFStatusRawatJalan.Value = row["StatusRawatJalan"].ToString();
HFPenjaminId.Value = row["PenjaminId"].ToString() == "" ? "0" : row["PenjaminId"].ToString();
lblNoRM.Text = row["NoRM"].ToString();
lblNamaPasien.Text = row["Nama"].ToString();
//Data Registrasi
lblNoRegistrasi.Text = row["NoRegistrasi"].ToString();
txtNoRegistrasi.Text = row["NoRegistrasi"].ToString();
txtTanggalRegistrasi.Text = row["TanggalBerobat"].ToString() != "" ? ((DateTime)row["TanggalBerobat"]).ToString("dd/MM/yyyy") : "";
txtNomorTunggu.Text = row["NomorTunggu"].ToString();
GetListJenisPenjamin(row["JenisPenjaminId"].ToString());
string JenisPenjaminId = row["JenisPenjaminId"].ToString();
GetListHubungan(row["HubunganId"].ToString());
GetListAgama(row["AgamaIdPenjamin"].ToString());
GetListPendidikan(row["PendidikanIdPenjamin"].ToString());
GetListStatus(row["StatusIdPenjamin"].ToString());
GetListPangkatPenjamin(row["PangkatIdPenjamin"].ToString());
if (JenisPenjaminId == "2")
{
tblPenjaminKeluarga.Visible = true;
tblPenjaminPerusahaan.Visible = false;
//Data Keluarga Penjamin
txtNamaPenjamin.Text = row["NamaPenjamin"].ToString();
txtUmurPenjamin.Text = row["UmurPenjamin"].ToString();
txtAlamatPenjamin.Text = row["AlamatPenjamin"].ToString();
txtTeleponPenjamin.Text = row["TeleponPenjamin"].ToString();
txtNRPPenjamin.Text = row["NRPPenjamin"].ToString();
txtJabatanPenjamin.Text = row["JabatanPenjamin"].ToString();
//txtKesatuanPenjamin.Text = row["KesatuanPenjamin"].ToString();
GetListSatuanKerjaPenjamin(row["KesatuanPenjamin"].ToString());
txtAlamatKesatuanPenjamin.Text = row["AlamatKesatuan"].ToString();
txtNoKTPPenjamin.Text = row["NoKTPPenjamin"].ToString();
txtGolDarahPenjamin.Text = row["GolDarahPenjamin"].ToString();
txtKeteranganPenjamin.Text = row["KeteranganPenjamin"].ToString();
}
else if (JenisPenjaminId == "3" || JenisPenjaminId == "4")
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = true;
txtNamaPerusahaan.Text = row["NamaPenjamin"].ToString();
txtNamaKontak.Text = row["NamaKontakPenjamin"].ToString();
txtAlamatPerusahaan.Text = row["AlamatPenjamin"].ToString();
txtTeleponPerusahaan.Text = row["TeleponPenjamin"].ToString();
txtFAXPerusahaan.Text = row["FaxPenjamin"].ToString();
txtKeteranganPerusahaan.Text = row["KeteranganPenjamin"].ToString();
}
else
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = false;
}
}
}
public void GetListStatus(string StatusId)
{
SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status();
DataTable dt = myObj.GetList();
cmbStatusPenjamin.Items.Clear();
int i = 0;
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = "";
cmbStatusPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == StatusId)
{
cmbStatusPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetListPangkatPenjamin(string PangkatId)
{
SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat();
if (cmbStatusPenjamin.SelectedIndex > 0)
myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value);
DataTable dt = myObj.GetListByStatusId();
cmbPangkatPenjamin.Items.Clear();
int i = 0;
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = "";
cmbPangkatPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PangkatId)
{
cmbPangkatPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetNomorTunggu()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 42;//LAB
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString();
}
public void GetListAgama(string AgamaId)
{
BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama();
DataTable dt = myObj.GetList();
cmbAgamaPenjamin.Items.Clear();
int i = 0;
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = "";
cmbAgamaPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == AgamaId)
cmbAgamaPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListPendidikan(string PendidikanId)
{
BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan();
DataTable dt = myObj.GetList();
cmbPendidikanPenjamin.Items.Clear();
int i = 0;
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "";
cmbPendidikanPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString();
cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PendidikanId)
cmbPendidikanPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListJenisPenjamin(string JenisPenjaminId)
{
SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin();
DataTable dt = myObj.GetList();
cmbJenisPenjamin.Items.Clear();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
cmbJenisPenjamin.Items.Add("");
cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == JenisPenjaminId)
cmbJenisPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListHubungan(string HubunganId)
{
SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan();
DataTable dt = myObj.GetList();
cmbHubungan.Items.Clear();
int i = 0;
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = "";
cmbHubungan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = dr["Nama"].ToString();
cmbHubungan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == HubunganId)
cmbHubungan.SelectedIndex = i;
i++;
}
}
public void GetNomorRegistrasi()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 42;//LAB
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNoRegistrasi.Text = myObj.GetNomorRegistrasi();
}
public bool OnSave()
{
bool result = false;
lblError.Text = "";
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (!Page.IsValid)
{
return false;
}
SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin();
myPenj.PenjaminId = Int64.Parse(HFPenjaminId.Value);
myPenj.SelectOne();
if (cmbJenisPenjamin.SelectedIndex > 0)
{
//Input Data Penjamin
if (cmbJenisPenjamin.SelectedIndex == 1)
{
if (cmbHubungan.SelectedIndex > 0)
myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value);
myPenj.Nama = txtNamaPenjamin.Text;
myPenj.Umur = txtUmurPenjamin.Text;
myPenj.Alamat = txtAlamatPenjamin.Text;
myPenj.Telepon = txtTeleponPenjamin.Text;
if (cmbAgamaPenjamin.SelectedIndex > 0)
myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value);
if (cmbPendidikanPenjamin.SelectedIndex > 0)
myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value);
if (cmbStatusPenjamin.SelectedIndex > 0)
myPenj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value);
if (cmbPangkatPenjamin.SelectedIndex > 0)
myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value);
myPenj.NRP = txtNRPPenjamin.Text;
myPenj.Jabatan = txtJabatanPenjamin.Text;
//myPenj.Kesatuan = txtKesatuanPenjamin.Text;
myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString();
myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text;
myPenj.NoKTP = txtNoKTPPenjamin.Text;
myPenj.GolDarah = txtGolDarahPenjamin.Text;
myPenj.Keterangan = txtKeteranganPenjamin.Text;
}
else
{
myPenj.Nama = txtNamaPerusahaan.Text;
myPenj.NamaKontak = txtNamaKontak.Text;
myPenj.Alamat = txtAlamatPerusahaan.Text;
myPenj.Telepon = txtTeleponPerusahaan.Text;
myPenj.Fax = txtFAXPerusahaan.Text;
}
if (HFPenjaminId.Value == "0")
{
myPenj.CreatedBy = UserId;
myPenj.CreatedDate = DateTime.Now;
result = myPenj.Insert();
}
else
{
myPenj.ModifiedBy = UserId;
myPenj.ModifiedDate = DateTime.Now;
result = myPenj.Update();
}
HFPenjaminId.Value = myPenj.PenjaminId.ToString();
}
else
{
if (HFPenjaminId.Value != "0")
myPenj.Delete();
HFPenjaminId.Value = "0";
}
//Input Data Registrasi
SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi();
myReg.RegistrasiId = Int64.Parse(HFRegistrasiId.Value);
myReg.SelectOne();
//GetNomorRegistrasi();
myReg.NoRegistrasi = txtNoRegistrasi.Text;
myReg.JenisRegistrasiId = 1;
myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text);
myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value);
if (cmbJenisPenjamin.SelectedIndex > 0)
myReg.PenjaminId = Int64.Parse(HFPenjaminId.Value);
else
myReg.PenjaminId = SqlInt64.Null;
myReg.ModifiedBy = UserId;
myReg.ModifiedDate = DateTime.Now;
result = myReg.Update();
//Update Data Rawat Jalan
SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan();
myRJ.RawatJalanId = Int64.Parse(HFRawatJalanId.Value);
myRJ.SelectOne();
myRJ.RegistrasiId = myReg.RegistrasiId;
myRJ.PoliklinikId = 42;//LAB
myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
//GetNomorTunggu();
if (txtNomorTunggu.Text != "")
myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text);
myRJ.Status = 0;//Baru daftar
myRJ.ModifiedBy = UserId;
myRJ.ModifiedDate = DateTime.Now;
result = myRJ.Update();
return result;
//string CurrentPage = "";
//if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
// CurrentPage = Request.QueryString["CurrentPage"].ToString();
//Response.Redirect("RJView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId);
}
public void OnCancel()
{
//string CurrentPage = "";
//if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
// CurrentPage = Request.QueryString["CurrentPage"].ToString();
//Response.Redirect("RJList.aspx?CurrentPage=" + CurrentPage);
}
protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbJenisPenjamin.SelectedIndex == 1)
{
tblPenjaminKeluarga.Visible = true;
tblPenjaminPerusahaan.Visible = false;
}
else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3)
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = true;
}
else
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = false;
}
}
protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e)
{
GetNomorTunggu();
GetNomorRegistrasi();
}
protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e)
{
GetListPangkatPenjamin("");
}
public void GetListSatuanKerjaPenjamin(string KesatuanPenjamin)
{
SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja();
DataTable dt = myObj.GetList();
cmbSatuanKerjaPenjamin.Items.Clear();
int i = 0;
cmbSatuanKerjaPenjamin.Items.Add("");
cmbSatuanKerjaPenjamin.Items[i].Text = "";
cmbSatuanKerjaPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbSatuanKerjaPenjamin.Items.Add("");
cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString();
cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString();
if (dr["NamaSatker"].ToString() == KesatuanPenjamin)
{
cmbSatuanKerjaPenjamin.SelectedIndex = i;
}
i++;
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using System.Collections.Generic;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI80;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LLA80 = Net.Pkcs11Interop.LowLevelAPI80;
using System.Reflection;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI80
{
/// <summary>
/// Object attributes tests.
/// </summary>
[TestClass]
public class _13_ObjectAttributeTest
{
/// <summary>
/// Attribute dispose test.
/// </summary>
[TestMethod]
public void _01_DisposeAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
// Unmanaged memory for attribute value stored in low level CK_ATTRIBUTE struct
// is allocated by constructor of ObjectAttribute class.
ObjectAttribute attr1 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
// Do something interesting with attribute
// This unmanaged memory is freed by Dispose() method.
attr1.Dispose();
// ObjectAttribute class can be used in using statement which defines a scope
// at the end of which an object will be disposed (and unmanaged memory freed).
using (ObjectAttribute attr2 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA))
{
// Do something interesting with attribute
}
#pragma warning disable 0219
// Explicit calling of Dispose() method can also be ommitted.
ObjectAttribute attr3 = new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_DATA);
// Do something interesting with attribute
// Dispose() method will be called (and unmanaged memory freed) by GC eventually
// but we cannot be sure when will this occur.
#pragma warning restore 0219
}
/// <summary>
/// Attribute with empty value test.
/// </summary>
[TestMethod]
public void _02_EmptyAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
// Create attribute without the value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS);
Assert.IsTrue(attr.GetValueAsByteArray() == null);
}
}
/// <summary>
/// Attribute with ulong value test.
/// </summary>
[TestMethod]
public void _03_UintAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
ulong value = (ulong)CKO.CKO_DATA;
// Create attribute with ulong value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_CLASS, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_CLASS);
Assert.IsTrue(attr.GetValueAsUlong() == value);
}
}
/// <summary>
/// Attribute with bool value test.
/// </summary>
[TestMethod]
public void _04_BoolAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
bool value = true;
// Create attribute with bool value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_TOKEN, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_TOKEN);
Assert.IsTrue(attr.GetValueAsBool() == value);
}
}
/// <summary>
/// Attribute with string value test.
/// </summary>
[TestMethod]
public void _05_StringAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
string value = "Hello world";
// Create attribute with string value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL);
Assert.IsTrue(attr.GetValueAsString() == value);
}
value = null;
// Create attribute with null string value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_LABEL, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_LABEL);
Assert.IsTrue(attr.GetValueAsString() == value);
}
}
/// <summary>
/// Attribute with byte array value test.
/// </summary>
[TestMethod]
public void _06_ByteArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
byte[] value = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
// Create attribute with byte array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID);
Assert.IsTrue(Convert.ToBase64String(attr.GetValueAsByteArray()) == Convert.ToBase64String(value));
}
value = null;
// Create attribute with null byte array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ID, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ID);
Assert.IsTrue(attr.GetValueAsByteArray() == value);
}
}
/// <summary>
/// Attribute with DateTime (CKA_DATE) value test.
/// </summary>
[TestMethod]
public void _07_DateTimeAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
DateTime value = new DateTime(2012, 1, 30, 0, 0, 0, DateTimeKind.Utc);
// Create attribute with DateTime value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_START_DATE, value))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_START_DATE);
Assert.IsTrue(attr.GetValueAsDateTime() == value);
}
}
/// <summary>
/// Attribute with attribute array value test.
/// </summary>
[TestMethod]
public void _08_AttributeArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
ObjectAttribute nestedAttribute1 = new ObjectAttribute(CKA.CKA_TOKEN, true);
ObjectAttribute nestedAttribute2 = new ObjectAttribute(CKA.CKA_PRIVATE, true);
List<ObjectAttribute> originalValue = new List<ObjectAttribute>();
originalValue.Add(nestedAttribute1);
originalValue.Add(nestedAttribute2);
// Create attribute with attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE);
List<ObjectAttribute> recoveredValue = attr.GetValueAsObjectAttributeList();
Assert.IsTrue(recoveredValue.Count == 2);
Assert.IsTrue(recoveredValue[0].Type == (ulong)CKA.CKA_TOKEN);
Assert.IsTrue(recoveredValue[0].GetValueAsBool() == true);
Assert.IsTrue(recoveredValue[1].Type == (ulong)CKA.CKA_PRIVATE);
Assert.IsTrue(recoveredValue[1].GetValueAsBool() == true);
}
// There is the same pointer to unmanaged memory in both nestedAttribute1 and recoveredValue[0] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
LLA80.CK_ATTRIBUTE ckAttribute1 = (LLA80.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute1);
ckAttribute1.value = IntPtr.Zero;
ckAttribute1.valueLen = 0;
typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute1, ckAttribute1);
// There is the same pointer to unmanaged memory in both nestedAttribute2 and recoveredValue[1] instances
// therefore private low level attribute structure needs to be modified to prevent double free.
// This special handling is needed only in this synthetic test and should be avoided in real world application.
LLA80.CK_ATTRIBUTE ckAttribute2 = (LLA80.CK_ATTRIBUTE)typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(nestedAttribute2);
ckAttribute2.value = IntPtr.Zero;
ckAttribute2.valueLen = 0;
typeof(ObjectAttribute).GetField("_ckAttribute", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(nestedAttribute2, ckAttribute2);
originalValue = null;
// Create attribute with null attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE);
Assert.IsTrue(attr.GetValueAsObjectAttributeList() == originalValue);
}
originalValue = new List<ObjectAttribute>();
// Create attribute with empty attribute array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_WRAP_TEMPLATE, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_WRAP_TEMPLATE);
Assert.IsTrue(attr.GetValueAsObjectAttributeList() == null);
}
}
/// <summary>
/// Attribute with ulong array value test.
/// </summary>
[TestMethod]
public void _09_UintArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
List<ulong> originalValue = new List<ulong>();
originalValue.Add(333333);
originalValue.Add(666666);
// Create attribute with ulong array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
List<ulong> recoveredValue = attr.GetValueAsUlongList();
for (int i = 0; i < recoveredValue.Count; i++)
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
originalValue = null;
// Create attribute with null ulong array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsUlongList() == originalValue);
}
originalValue = new List<ulong>();
// Create attribute with empty ulong array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsUlongList() == null);
}
}
/// <summary>
/// Attribute with mechanism array value test.
/// </summary>
[TestMethod]
public void _10_MechanismArrayAttributeTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
List<CKM> originalValue = new List<CKM>();
originalValue.Add(CKM.CKM_RSA_PKCS);
originalValue.Add(CKM.CKM_AES_CBC);
// Create attribute with mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
List<CKM> recoveredValue = attr.GetValueAsCkmList();
for (int i = 0; i < recoveredValue.Count; i++)
Assert.IsTrue(originalValue[i] == recoveredValue[i]);
}
originalValue = null;
// Create attribute with null mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsCkmList() == originalValue);
}
originalValue = new List<CKM>();
// Create attribute with empty mechanism array value
using (ObjectAttribute attr = new ObjectAttribute(CKA.CKA_ALLOWED_MECHANISMS, originalValue))
{
Assert.IsTrue(attr.Type == (ulong)CKA.CKA_ALLOWED_MECHANISMS);
Assert.IsTrue(attr.GetValueAsCkmList() == null);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// UserProfileManager
/// </summary>
public class UserProfileManager
{
#region Static
private static readonly UserProfileManager _instance = new UserProfileManager();
public static UserProfileManager instance
{
get
{
return _instance;
}
}
private UserProfileManager()
{
_secretKey = AESHelper.CreateKey(CRYPTO_KEY);
}
#endregion
#region Private
private const string CRYPTO_KEY = "www.virtuos.com.key";
private byte[] _secretKey = null;
private byte[] secretKey
{
get
{
if (_secretKey == null)
{
_secretKey = AESHelper.CreateKey(CRYPTO_KEY);
}
return _secretKey;
}
}
private string GetFileName(string username)
{
return string.Format("{0}.dat", MD5Helper.GetHash(username));
}
#endregion
#region Properties
public UserProfile profile
{
get
{
return UserProfile.current;
}
}
public int gold
{
get
{
return this.profile.gameInfo.gold;
}
set
{
this.UpdateGold(value);
}
}
public int gem
{
get
{
return this.profile.gameInfo.gem;
}
set
{
this.UpdateGem(value);
}
}
public int energy
{
get
{
return this.profile.gameInfo.energy;
}
set
{
this.UpdateEnergy(value);
}
}
public int onlineEnergy
{
get
{
return this.profile.gameInfo.onlineEnergy;
}
set
{
this.UpdateOnlineEnergy(value);
}
}
public int experience
{
get
{
return this.profile.gameInfo.experience;
}
set
{
this.UpdateExperience(value);
}
}
public int level
{
get
{
return this.profile.gameInfo.level;
}
private set
{
this.UpdateLevel(value);
}
}
#endregion
#region Interfaces.
public UserProfile Load(string id)
{
try
{
string filename = GetFileName(id);
UserProfile profile = LocalDataManager.Load<UserProfile>(filename, this.secretKey);
UserProfile.current = profile;
return profile;
}
catch
{
return null;
}
}
public void Save(string id, UserProfile profile)
{
if (profile == null)
return;
string filename = GetFileName(id);
LocalDataManager.Save<UserProfile>(profile, filename, true, this.secretKey);
}
public void Delete(string id)
{
string filename = GetFileName(id);
LocalDataManager.Delete(id);
}
public void Save()
{
if (UserProfile.current != null && !string.IsNullOrEmpty(UserProfile.current.account.id))
this.Save(UserProfile.current.account.id, UserProfile.current);
}
public void Delete()
{
if (UserProfile.current != null && !string.IsNullOrEmpty(UserProfile.current.account.id))
this.Delete(UserProfile.current.account.id);
}
public void UpdateItems(ICollection<ItemInfo> items)
{
if (items == null || items.Count == 0)
return;
foreach (ItemInfo item in items)
{
this.UpdateItem(item);
}
}
public void UpdateInventory(ICollection<InventoryItem> inventoryItems)
{
if (inventoryItems == null || inventoryItems.Count == 0)
return;
bool changed = false;
foreach (InventoryItem it in inventoryItems)
{
if (it == null)
continue;
InventoryItem item = null;
if (profile.gameInfo.inventoryItems.TryGetValue(it.uid, out item))
{
if (item.count != it.count)
{
item.count = it.count;
changed = true;
ItemType type = ItemTypeUtilty.GetType(item.id);
this.UnlockItems(item.id);
}
if (it.count == 0)
{
profile.gameInfo.inventoryItems.Remove(item.uid);
changed = true;
}
}
else if(it.count != 0)
{
changed = true;
item = new InventoryItem();
item.uid = it.uid;
item.id = it.id;
item.count = it.count;
profile.gameInfo.inventoryItems[item.uid] = item;
this.UnlockItems(item.id);
}
}
if (changed)
EventDispatcher.Instance.DispatchEvent(EventNames.InventoryChanged, 0);
}
public void ModifyItems(ICollection<ItemInfo> items)
{
if (items == null || items.Count == 0)
return;
foreach (ItemInfo item in items)
{
this.ModifyItem(item);
}
}
public void ModifyItem(ItemInfo item)
{
if (item == null)
return;
ItemType type = ItemTypeUtilty.GetType(item.id);
switch (type)
{
case ItemType.Unknown:
break;
case ItemType.Gold:
this.ModifyGold(item.count);
break;
case ItemType.Energy:
this.ModifyEnergy(item.count);
break;
case ItemType.Gem:
this.ModifyGem(item.count);
break;
case ItemType.OnlineEnergy:
this.ModifyOnlineEnergy(item.count);
break;
case ItemType.Experience:
this.ModifyExperience(item.count);
this.UpdateLevel(GamePlayDataManager.instance.GetLevelByExp(profile.gameInfo.experience));
break;
case ItemType.Box:
break;
default:
break;
}
}
private void UnlockItems(string id)
{
ItemType type = ItemTypeUtilty.GetType(id);
switch (type)
{
default:
break;
}
}
public void UpdateItem(ItemInfo item)
{
if (item == null)
return;
ItemType type = ItemTypeUtilty.GetType(item.id);
switch (type)
{
case ItemType.Unknown:
break;
case ItemType.Gold:
this.UpdateGold(item.count);
break;
case ItemType.Energy:
this.UpdateEnergy(item.count);
break;
case ItemType.Gem:
this.UpdateGem(item.count);
break;
case ItemType.OnlineEnergy:
this.UpdateOnlineEnergy(item.count);
break;
case ItemType.Experience:
this.UpdateExperience(item.count);
this.UpdateLevel(GamePlayDataManager.instance.GetLevelByExp(profile.gameInfo.experience));
break;
case ItemType.Box:
break;
default:
break;
}
}
public void UpdateGold(int value)
{
if (this.profile.gameInfo.gold != value)
{
this.profile.gameInfo.gold = value;
EventDispatcher.Instance.DispatchEvent(EventNames.GoldChanged, this.profile.gameInfo.gold);
}
}
public void ModifyGold(int change)
{
this.UpdateGold(this.profile.gameInfo.gold + change);
}
public void UpdateGem(int value)
{
if (this.profile.gameInfo.gem != value)
{
this.profile.gameInfo.gem = value;
EventDispatcher.Instance.DispatchEvent(EventNames.GemChanged, this.profile.gameInfo.gem);
}
}
public void ModifyGem(int change)
{
this.UpdateGem(this.profile.gameInfo.gem + change);
}
public void UpdateEnergy(int value)
{
if (this.profile.gameInfo.energy != value)
{
this.profile.gameInfo.energy = value;
EventDispatcher.Instance.DispatchEvent(EventNames.EnergyChanged, this.profile.gameInfo.energy);
}
}
public void ModifyEnergy(int change)
{
this.UpdateEnergy(this.profile.gameInfo.energy + change);
}
public void UpdateOnlineEnergy(int value)
{
if (this.profile.gameInfo.onlineEnergy != value)
{
this.profile.gameInfo.onlineEnergy = value;
EventDispatcher.Instance.DispatchEvent(EventNames.OnlineEnergyChanged, this.profile.gameInfo.onlineEnergy);
}
}
public void ModifyOnlineEnergy(int change)
{
this.UpdateOnlineEnergy(this.profile.gameInfo.onlineEnergy + change);
}
public void UpdateExperience(int value)
{
if (this.profile.gameInfo.experience != value)
{
this.profile.gameInfo.experience = value;
EventDispatcher.Instance.DispatchEvent(EventNames.ExperienceChanged, this.profile.gameInfo.experience);
}
}
public void ModifyExperience(int change)
{
this.UpdateExperience(this.profile.gameInfo.experience + change);
}
private void UpdateLevel(int value)
{
if (this.profile.gameInfo.level != value)
{
this.profile.gameInfo.level = value;
EventDispatcher.Instance.DispatchEvent(EventNames.LevelChanged, this.profile.gameInfo.level);
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.Linq;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.Language.Components;
using Xunit;
namespace Microsoft.CodeAnalysis.Razor
{
public class BindTagHelperDescriptorProviderTest : TagHelperDescriptorProviderTestBase
{
[Fact]
public void Execute_FindsBindTagHelperOnComponentType_Delegate_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
namespace Test
{
public class MyComponent : IComponent
{
public void Attach(RenderHandle renderHandle) { }
public Task SetParametersAsync(ParameterView parameters)
{
return Task.CompletedTask;
}
[Parameter]
public string MyProperty { get; set; }
[Parameter]
public Action<string> MyPropertyChanged { get; set; }
[Parameter]
public Expression<Func<string>> MyPropertyExpression { get; set; }
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
// We run after component discovery and depend on the results.
var componentProvider = new ComponentTagHelperDescriptorProvider();
componentProvider.Execute(context);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 1);
var bind = Assert.Single(matches);
// These are features Bind Tags Helpers don't use. Verifying them once here and
// then ignoring them.
Assert.Empty(bind.AllowedChildTags);
Assert.Null(bind.TagOutputHint);
// These are features that are invariants of all Bind Tag Helpers. Verifying them once
// here and then ignoring them.
Assert.Empty(bind.Diagnostics);
Assert.False(bind.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, bind.Kind);
Assert.Equal(ComponentMetadata.Bind.RuntimeName, bind.Metadata[TagHelperMetadata.Runtime.Name]);
Assert.False(bind.IsDefaultKind());
Assert.False(bind.KindUsesDefaultTagHelperRuntime());
Assert.False(bind.IsComponentOrChildContentTagHelper());
Assert.True(bind.CaseSensitive);
Assert.Equal("MyProperty", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("MyPropertyChanged", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.Equal("MyPropertyExpression", bind.Metadata[ComponentMetadata.Bind.ExpressionAttribute]);
Assert.Equal(
"Binds the provided expression to the 'MyProperty' property and a change event " +
"delegate to the 'MyPropertyChanged' property of the component.",
bind.Documentation);
// These are all trivially derived from the assembly/namespace/type name
Assert.Equal("TestAssembly", bind.AssemblyName);
Assert.Equal("Test.MyComponent", bind.Name);
Assert.Equal("Test.MyComponent", bind.DisplayName);
Assert.Equal("Test.MyComponent", bind.GetTypeName());
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Empty(rule.Diagnostics);
Assert.False(rule.HasErrors);
Assert.Null(rule.ParentTag);
Assert.Equal("MyComponent", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
var requiredAttribute = Assert.Single(rule.Attributes);
Assert.Empty(requiredAttribute.Diagnostics);
Assert.Equal("@bind-MyProperty", requiredAttribute.DisplayName);
Assert.Equal("@bind-MyProperty", requiredAttribute.Name);
Assert.Equal(RequiredAttributeDescriptor.NameComparisonMode.FullMatch, requiredAttribute.NameComparison);
Assert.Null(requiredAttribute.Value);
Assert.Equal(RequiredAttributeDescriptor.ValueComparisonMode.None, requiredAttribute.ValueComparison);
var attribute = Assert.Single(bind.BoundAttributes);
// Invariants
Assert.Empty(attribute.Diagnostics);
Assert.False(attribute.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, attribute.Kind);
Assert.False(attribute.IsDefaultKind());
Assert.False(attribute.HasIndexer);
Assert.Null(attribute.IndexerNamePrefix);
Assert.Null(attribute.IndexerTypeName);
Assert.False(attribute.IsIndexerBooleanProperty);
Assert.False(attribute.IsIndexerStringProperty);
Assert.Equal(
"Binds the provided expression to the 'MyProperty' property and a change event " +
"delegate to the 'MyPropertyChanged' property of the component.",
attribute.Documentation);
Assert.Equal("@bind-MyProperty", attribute.Name);
Assert.Equal("MyProperty", attribute.GetPropertyName());
Assert.Equal("System.Action<System.String> Test.MyComponent.MyProperty", attribute.DisplayName);
// Defined from the property type
Assert.Equal("System.Action<System.String>", attribute.TypeName);
Assert.False(attribute.IsStringProperty);
Assert.False(attribute.IsBooleanProperty);
Assert.False(attribute.IsEnum);
}
[Fact]
public void Execute_FindsBindTagHelperOnComponentType_EventCallback_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
namespace Test
{
public class MyComponent : IComponent
{
public void Attach(RenderHandle renderHandle) { }
public Task SetParametersAsync(ParameterView parameters)
{
return Task.CompletedTask;
}
[Parameter]
public string MyProperty { get; set; }
[Parameter]
public EventCallback<string> MyPropertyChanged { get; set; }
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
// We run after component discovery and depend on the results.
var componentProvider = new ComponentTagHelperDescriptorProvider();
componentProvider.Execute(context);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 1);
var bind = Assert.Single(matches);
// These are features Bind Tags Helpers don't use. Verifying them once here and
// then ignoring them.
Assert.Empty(bind.AllowedChildTags);
Assert.Null(bind.TagOutputHint);
// These are features that are invariants of all Bind Tag Helpers. Verifying them once
// here and then ignoring them.
Assert.Empty(bind.Diagnostics);
Assert.False(bind.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, bind.Kind);
Assert.Equal(ComponentMetadata.Bind.RuntimeName, bind.Metadata[TagHelperMetadata.Runtime.Name]);
Assert.False(bind.IsDefaultKind());
Assert.False(bind.KindUsesDefaultTagHelperRuntime());
Assert.False(bind.IsComponentOrChildContentTagHelper());
Assert.True(bind.CaseSensitive);
Assert.Equal("MyProperty", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("MyPropertyChanged", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.Equal(
"Binds the provided expression to the 'MyProperty' property and a change event " +
"delegate to the 'MyPropertyChanged' property of the component.",
bind.Documentation);
// These are all trivially derived from the assembly/namespace/type name
Assert.Equal("TestAssembly", bind.AssemblyName);
Assert.Equal("Test.MyComponent", bind.Name);
Assert.Equal("Test.MyComponent", bind.DisplayName);
Assert.Equal("Test.MyComponent", bind.GetTypeName());
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Empty(rule.Diagnostics);
Assert.False(rule.HasErrors);
Assert.Null(rule.ParentTag);
Assert.Equal("MyComponent", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
var requiredAttribute = Assert.Single(rule.Attributes);
Assert.Empty(requiredAttribute.Diagnostics);
Assert.Equal("@bind-MyProperty", requiredAttribute.DisplayName);
Assert.Equal("@bind-MyProperty", requiredAttribute.Name);
Assert.Equal(RequiredAttributeDescriptor.NameComparisonMode.FullMatch, requiredAttribute.NameComparison);
Assert.Null(requiredAttribute.Value);
Assert.Equal(RequiredAttributeDescriptor.ValueComparisonMode.None, requiredAttribute.ValueComparison);
var attribute = Assert.Single(bind.BoundAttributes);
// Invariants
Assert.Empty(attribute.Diagnostics);
Assert.False(attribute.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, attribute.Kind);
Assert.False(attribute.IsDefaultKind());
Assert.False(attribute.HasIndexer);
Assert.Null(attribute.IndexerNamePrefix);
Assert.Null(attribute.IndexerTypeName);
Assert.False(attribute.IsIndexerBooleanProperty);
Assert.False(attribute.IsIndexerStringProperty);
Assert.Equal(
"Binds the provided expression to the 'MyProperty' property and a change event " +
"delegate to the 'MyPropertyChanged' property of the component.",
attribute.Documentation);
Assert.Equal("@bind-MyProperty", attribute.Name);
Assert.Equal("MyProperty", attribute.GetPropertyName());
Assert.Equal("Microsoft.AspNetCore.Components.EventCallback<System.String> Test.MyComponent.MyProperty", attribute.DisplayName);
// Defined from the property type
Assert.Equal("Microsoft.AspNetCore.Components.EventCallback<System.String>", attribute.TypeName);
Assert.False(attribute.IsStringProperty);
Assert.False(attribute.IsBooleanProperty);
Assert.False(attribute.IsEnum);
}
[Fact]
public void Execute_NoMatchedPropertiesOnComponent_IgnoresComponent()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
namespace Test
{
public class MyComponent : IComponent
{
public void Attach(RenderHandle renderHandle) { }
public Task SetParametersAsync(ParameterView parameters)
{
return Task.CompletedTask;
}
public string MyProperty { get; set; }
public Action<string> MyPropertyChangedNotMatch { get; set; }
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
// We run after component discovery and depend on the results.
var componentProvider = new ComponentTagHelperDescriptorProvider();
componentProvider.Execute(context);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 0);
Assert.Empty(matches);
}
[Fact]
public void Execute_BindOnElement_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using Microsoft.AspNetCore.Components;
namespace Test
{
[BindElement(""div"", null, ""myprop"", ""myevent"")]
public class BindAttributes
{
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 0);
var bind = Assert.Single(matches);
// These are features Bind Tags Helpers don't use. Verifying them once here and
// then ignoring them.
Assert.Empty(bind.AllowedChildTags);
Assert.Null(bind.TagOutputHint);
// These are features that are invariants of all Bind Tag Helpers. Verifying them once
// here and then ignoring them.
Assert.Empty(bind.Diagnostics);
Assert.False(bind.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, bind.Kind);
Assert.Equal(bool.TrueString, bind.Metadata[TagHelperMetadata.Common.ClassifyAttributesOnly]);
Assert.Equal(ComponentMetadata.Bind.RuntimeName, bind.Metadata[TagHelperMetadata.Runtime.Name]);
Assert.False(bind.IsDefaultKind());
Assert.False(bind.KindUsesDefaultTagHelperRuntime());
Assert.False(bind.IsComponentOrChildContentTagHelper());
Assert.True(bind.CaseSensitive);
Assert.Equal("myprop", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("myevent", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.False(bind.IsInputElementBindTagHelper());
Assert.False(bind.IsInputElementFallbackBindTagHelper());
Assert.Equal(
"Binds the provided expression to the 'myprop' attribute and a change event " +
"delegate to the 'myevent' attribute.",
bind.Documentation);
// These are all trivially derived from the assembly/namespace/type name
Assert.Equal("Microsoft.AspNetCore.Components", bind.AssemblyName);
Assert.Equal("Bind", bind.Name);
Assert.Equal("Test.BindAttributes", bind.DisplayName);
Assert.Equal("Test.BindAttributes", bind.GetTypeName());
// The tag matching rule for a bind-Component is always the component name + the attribute name
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Empty(rule.Diagnostics);
Assert.False(rule.HasErrors);
Assert.Null(rule.ParentTag);
Assert.Equal("div", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
var requiredAttribute = Assert.Single(rule.Attributes);
Assert.Empty(requiredAttribute.Diagnostics);
Assert.Equal("@bind", requiredAttribute.DisplayName);
Assert.Equal("@bind", requiredAttribute.Name);
Assert.Equal(RequiredAttributeDescriptor.NameComparisonMode.FullMatch, requiredAttribute.NameComparison);
Assert.Null(requiredAttribute.Value);
Assert.Equal(RequiredAttributeDescriptor.ValueComparisonMode.None, requiredAttribute.ValueComparison);
var attribute = Assert.Single(bind.BoundAttributes, a => a.Name.StartsWith("@bind", StringComparison.Ordinal));
// Invariants
Assert.Empty(attribute.Diagnostics);
Assert.False(attribute.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, attribute.Kind);
Assert.False(attribute.IsDefaultKind());
Assert.False(attribute.HasIndexer);
Assert.Null(attribute.IndexerNamePrefix);
Assert.Null(attribute.IndexerTypeName);
Assert.False(attribute.IsIndexerBooleanProperty);
Assert.False(attribute.IsIndexerStringProperty);
Assert.Equal(
"Binds the provided expression to the 'myprop' attribute and a change event " +
"delegate to the 'myevent' attribute.",
attribute.Documentation);
Assert.Equal("@bind", attribute.Name);
Assert.Equal("Bind", attribute.GetPropertyName());
Assert.Equal("object Test.BindAttributes.Bind", attribute.DisplayName);
// Defined from the property type
Assert.Equal("System.Object", attribute.TypeName);
Assert.False(attribute.IsStringProperty);
Assert.False(attribute.IsBooleanProperty);
Assert.False(attribute.IsEnum);
var parameter = Assert.Single(attribute.BoundAttributeParameters, a => a.Name.Equals("format"));
// Invariants
Assert.Empty(parameter.Diagnostics);
Assert.False(parameter.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, parameter.Kind);
Assert.False(parameter.IsDefaultKind());
Assert.Equal(
"Specifies a format to convert the value specified by the '@bind' attribute. " +
"The format string can currently only be used with expressions of type <code>DateTime</code>.",
parameter.Documentation);
Assert.Equal("format", parameter.Name);
Assert.Equal("Format_myprop", parameter.GetPropertyName());
Assert.Equal(":format", parameter.DisplayName);
// Defined from the property type
Assert.Equal("System.String", parameter.TypeName);
Assert.True(parameter.IsStringProperty);
Assert.False(parameter.IsBooleanProperty);
Assert.False(parameter.IsEnum);
parameter = Assert.Single(attribute.BoundAttributeParameters, a => a.Name.Equals("culture"));
// Invariants
Assert.Empty(parameter.Diagnostics);
Assert.False(parameter.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, parameter.Kind);
Assert.False(parameter.IsDefaultKind());
Assert.Equal(
"Specifies the culture to use for conversions.",
parameter.Documentation);
Assert.Equal("culture", parameter.Name);
Assert.Equal("Culture", parameter.GetPropertyName());
Assert.Equal(":culture", parameter.DisplayName);
// Defined from the property type
Assert.Equal("System.Globalization.CultureInfo", parameter.TypeName);
Assert.False(parameter.IsStringProperty);
Assert.False(parameter.IsBooleanProperty);
Assert.False(parameter.IsEnum);
}
[Fact]
public void Execute_BindOnElementWithSuffix_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using Microsoft.AspNetCore.Components;
namespace Test
{
[BindElement(""div"", ""myprop"", ""myprop"", ""myevent"")]
public class BindAttributes
{
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 0);
var bind = Assert.Single(matches);
Assert.Equal("myprop", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("myevent", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.False(bind.IsInputElementBindTagHelper());
Assert.False(bind.IsInputElementFallbackBindTagHelper());
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Equal("div", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
var requiredAttribute = Assert.Single(rule.Attributes);
Assert.Equal("@bind-myprop", requiredAttribute.DisplayName);
Assert.Equal("@bind-myprop", requiredAttribute.Name);
var attribute = Assert.Single(bind.BoundAttributes, a => a.Name.StartsWith("@bind", StringComparison.Ordinal));
Assert.Equal("@bind-myprop", attribute.Name);
Assert.Equal("Bind_myprop", attribute.GetPropertyName());
Assert.Equal("object Test.BindAttributes.Bind_myprop", attribute.DisplayName);
attribute = Assert.Single(bind.BoundAttributes, a => a.Name.StartsWith("format", StringComparison.Ordinal));
Assert.Equal("format-myprop", attribute.Name);
Assert.Equal("Format_myprop", attribute.GetPropertyName());
Assert.Equal("string Test.BindAttributes.Format_myprop", attribute.DisplayName);
}
[Fact]
public void Execute_BindOnInputElementWithoutTypeAttribute_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using Microsoft.AspNetCore.Components;
namespace Test
{
[BindInputElement(null, null, ""myprop"", ""myevent"", false, null)]
public class BindAttributes
{
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 0);
var bind = Assert.Single(matches);
Assert.Equal("myprop", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("myevent", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.False(bind.Metadata.ContainsKey(ComponentMetadata.Bind.TypeAttribute));
Assert.True(bind.IsInputElementBindTagHelper());
Assert.True(bind.IsInputElementFallbackBindTagHelper());
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Equal("input", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
var requiredAttribute = Assert.Single(rule.Attributes);
Assert.Equal("@bind", requiredAttribute.DisplayName);
Assert.Equal("@bind", requiredAttribute.Name);
var attribute = Assert.Single(bind.BoundAttributes, a => a.Name.StartsWith("@bind", StringComparison.Ordinal));
Assert.Equal("@bind", attribute.Name);
Assert.Equal("Bind", attribute.GetPropertyName());
Assert.Equal("object Test.BindAttributes.Bind", attribute.DisplayName);
var parameter = Assert.Single(attribute.BoundAttributeParameters, a => a.Name.Equals("format"));
Assert.Equal("format", parameter.Name);
Assert.Equal("Format_myprop", parameter.GetPropertyName());
Assert.Equal(":format", parameter.DisplayName);
}
[Fact]
public void Execute_BindOnInputElementWithTypeAttribute_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using Microsoft.AspNetCore.Components;
namespace Test
{
[BindInputElement(""checkbox"", null, ""myprop"", ""myevent"", false, null)]
public class BindAttributes
{
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 0);
var bind = Assert.Single(matches);
Assert.Equal("myprop", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("myevent", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.Equal("checkbox", bind.Metadata[ComponentMetadata.Bind.TypeAttribute]);
Assert.True(bind.IsInputElementBindTagHelper());
Assert.False(bind.IsInputElementFallbackBindTagHelper());
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Equal("input", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
Assert.Collection(
rule.Attributes,
a =>
{
Assert.Equal("type", a.DisplayName);
Assert.Equal("type", a.Name);
Assert.Equal(RequiredAttributeDescriptor.NameComparisonMode.FullMatch, a.NameComparison);
Assert.Equal("checkbox", a.Value);
Assert.Equal(RequiredAttributeDescriptor.ValueComparisonMode.FullMatch, a.ValueComparison);
},
a =>
{
Assert.Equal("@bind", a.DisplayName);
Assert.Equal("@bind", a.Name);
});
var attribute = Assert.Single(bind.BoundAttributes, a => a.Name.StartsWith("@bind", StringComparison.Ordinal));
Assert.Equal("@bind", attribute.Name);
Assert.Equal("Bind", attribute.GetPropertyName());
Assert.Equal("object Test.BindAttributes.Bind", attribute.DisplayName);
var parameter = Assert.Single(attribute.BoundAttributeParameters, a => a.Name.Equals("format"));
Assert.Equal("format", parameter.Name);
Assert.Equal("Format_myprop", parameter.GetPropertyName());
Assert.Equal(":format", parameter.DisplayName);
}
[Fact]
public void Execute_BindOnInputElementWithTypeAttributeAndSuffix_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using Microsoft.AspNetCore.Components;
namespace Test
{
[BindInputElement(""checkbox"", ""somevalue"", ""myprop"", ""myevent"", false, null)]
public class BindAttributes
{
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 0);
var bind = Assert.Single(matches);
Assert.Equal("myprop", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("myevent", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.Equal("checkbox", bind.Metadata[ComponentMetadata.Bind.TypeAttribute]);
Assert.True(bind.IsInputElementBindTagHelper());
Assert.False(bind.IsInputElementFallbackBindTagHelper());
Assert.False(bind.IsInvariantCultureBindTagHelper());
Assert.Null(bind.GetFormat());
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Equal("input", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
Assert.Collection(
rule.Attributes,
a =>
{
Assert.Equal("type", a.DisplayName);
Assert.Equal("type", a.Name);
Assert.Equal(RequiredAttributeDescriptor.NameComparisonMode.FullMatch, a.NameComparison);
Assert.Equal("checkbox", a.Value);
Assert.Equal(RequiredAttributeDescriptor.ValueComparisonMode.FullMatch, a.ValueComparison);
},
a =>
{
Assert.Equal("@bind-somevalue", a.DisplayName);
Assert.Equal("@bind-somevalue", a.Name);
});
var attribute = Assert.Single(bind.BoundAttributes, a => a.Name.StartsWith("@bind", StringComparison.Ordinal));
Assert.Equal("@bind-somevalue", attribute.Name);
Assert.Equal("Bind_somevalue", attribute.GetPropertyName());
Assert.Equal("object Test.BindAttributes.Bind_somevalue", attribute.DisplayName);
var parameter = Assert.Single(attribute.BoundAttributeParameters, a => a.Name.Equals("format"));
Assert.Equal("format", parameter.Name);
Assert.Equal("Format_somevalue", parameter.GetPropertyName());
Assert.Equal(":format", parameter.DisplayName);
}
[Fact]
public void Execute_BindOnInputElementWithTypeAttributeAndSuffixAndInvariantCultureAndFormat_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation.AddSyntaxTrees(Parse(@"
using Microsoft.AspNetCore.Components;
namespace Test
{
[BindInputElement(""number"", null, ""value"", ""onchange"", isInvariantCulture: true, format: ""0.00"")]
public class BindAttributes
{
}
}
"));
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var matches = GetBindTagHelpers(context);
matches = AssertAndExcludeFullyQualifiedNameMatchComponents(matches, expectedCount: 0);
var bind = Assert.Single(matches);
Assert.Equal("value", bind.Metadata[ComponentMetadata.Bind.ValueAttribute]);
Assert.Equal("onchange", bind.Metadata[ComponentMetadata.Bind.ChangeAttribute]);
Assert.Equal("number", bind.Metadata[ComponentMetadata.Bind.TypeAttribute]);
Assert.True(bind.IsInputElementBindTagHelper());
Assert.False(bind.IsInputElementFallbackBindTagHelper());
Assert.True(bind.IsInvariantCultureBindTagHelper());
Assert.Equal("0.00", bind.GetFormat());
}
[Fact]
public void Execute_BindFallback_CreatesDescriptor()
{
// Arrange
var compilation = BaseCompilation;
Assert.Empty(compilation.GetDiagnostics());
var context = TagHelperDescriptorProviderContext.Create();
context.SetCompilation(compilation);
var provider = new BindTagHelperDescriptorProvider();
// Act
provider.Execute(context);
// Assert
var bind = Assert.Single(context.Results, r => r.IsFallbackBindTagHelper());
// These are features Bind Tags Helpers don't use. Verifying them once here and
// then ignoring them.
Assert.Empty(bind.AllowedChildTags);
Assert.Null(bind.TagOutputHint);
// These are features that are invariants of all Bind Tag Helpers. Verifying them once
// here and then ignoring them.
Assert.Empty(bind.Diagnostics);
Assert.False(bind.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, bind.Kind);
Assert.Equal(bool.TrueString, bind.Metadata[TagHelperMetadata.Common.ClassifyAttributesOnly]);
Assert.Equal(ComponentMetadata.Bind.RuntimeName, bind.Metadata[TagHelperMetadata.Runtime.Name]);
Assert.False(bind.IsDefaultKind());
Assert.False(bind.KindUsesDefaultTagHelperRuntime());
Assert.False(bind.IsComponentOrChildContentTagHelper());
Assert.True(bind.CaseSensitive);
Assert.False(bind.Metadata.ContainsKey(ComponentMetadata.Bind.ValueAttribute));
Assert.False(bind.Metadata.ContainsKey(ComponentMetadata.Bind.ChangeAttribute));
Assert.True(bind.IsFallbackBindTagHelper());
Assert.Equal(
"Binds the provided expression to an attribute and a change event, based on the naming of " +
"the bind attribute. For example: <code>@bind-value=\"...\"</code> and <code>@bind-value:event=\"onchange\"</code> will assign the " +
"current value of the expression to the 'value' attribute, and assign a delegate that attempts " +
"to set the value to the 'onchange' attribute.",
bind.Documentation);
// These are all trivially derived from the assembly/namespace/type name
Assert.Equal("Microsoft.AspNetCore.Components", bind.AssemblyName);
Assert.Equal("Bind", bind.Name);
Assert.Equal("Microsoft.AspNetCore.Components.Bind", bind.DisplayName);
Assert.Equal("Microsoft.AspNetCore.Components.Bind", bind.GetTypeName());
// The tag matching rule for a bind-Component is always the component name + the attribute name
var rule = Assert.Single(bind.TagMatchingRules);
Assert.Empty(rule.Diagnostics);
Assert.False(rule.HasErrors);
Assert.Null(rule.ParentTag);
Assert.Equal("*", rule.TagName);
Assert.Equal(TagStructure.Unspecified, rule.TagStructure);
var requiredAttribute = Assert.Single(rule.Attributes);
Assert.Empty(requiredAttribute.Diagnostics);
Assert.Equal("@bind-...", requiredAttribute.DisplayName);
Assert.Equal("@bind-", requiredAttribute.Name);
Assert.Equal(RequiredAttributeDescriptor.NameComparisonMode.PrefixMatch, requiredAttribute.NameComparison);
Assert.Null(requiredAttribute.Value);
Assert.Equal(RequiredAttributeDescriptor.ValueComparisonMode.None, requiredAttribute.ValueComparison);
var attribute = Assert.Single(bind.BoundAttributes, a => a.Name.StartsWith("@bind", StringComparison.Ordinal));
// Invariants
Assert.Empty(attribute.Diagnostics);
Assert.False(attribute.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, attribute.Kind);
Assert.False(attribute.IsDefaultKind());
Assert.False(attribute.IsIndexerBooleanProperty);
Assert.False(attribute.IsIndexerStringProperty);
Assert.True(attribute.HasIndexer);
Assert.Equal("@bind-", attribute.IndexerNamePrefix);
Assert.Equal("System.Object", attribute.IndexerTypeName);
Assert.Equal(
"Binds the provided expression to an attribute and a change event, based on the naming of " +
"the bind attribute. For example: <code>@bind-value=\"...\"</code> and <code>@bind-value:event=\"onchange\"</code> will assign the " +
"current value of the expression to the 'value' attribute, and assign a delegate that attempts " +
"to set the value to the 'onchange' attribute.",
attribute.Documentation);
Assert.Equal("@bind-...", attribute.Name);
Assert.Equal("Bind", attribute.GetPropertyName());
Assert.Equal(
"System.Collections.Generic.Dictionary<string, object> Microsoft.AspNetCore.Components.Bind.Bind",
attribute.DisplayName);
// Defined from the property type
Assert.Equal("System.Collections.Generic.Dictionary<string, object>", attribute.TypeName);
Assert.False(attribute.IsStringProperty);
Assert.False(attribute.IsBooleanProperty);
Assert.False(attribute.IsEnum);
var parameter = Assert.Single(attribute.BoundAttributeParameters, a => a.Name.Equals("format"));
// Invariants
Assert.Empty(parameter.Diagnostics);
Assert.False(parameter.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, parameter.Kind);
Assert.False(parameter.IsDefaultKind());
Assert.Equal(
"Specifies a format to convert the value specified by the corresponding bind attribute. " +
"For example: <code>@bind-value:format=\"...\"</code> will apply a format string to the value " +
"specified in <code>@bind-value=\"...\"</code>. The format string can currently only be used with " +
"expressions of type <code>DateTime</code>.",
parameter.Documentation);
Assert.Equal("format", parameter.Name);
Assert.Equal("Format", parameter.GetPropertyName());
Assert.Equal(":format", parameter.DisplayName);
// Defined from the property type
Assert.Equal("System.String", parameter.TypeName);
Assert.True(parameter.IsStringProperty);
Assert.False(parameter.IsBooleanProperty);
Assert.False(parameter.IsEnum);
parameter = Assert.Single(attribute.BoundAttributeParameters, a => a.Name.Equals("culture"));
// Invariants
Assert.Empty(parameter.Diagnostics);
Assert.False(parameter.HasErrors);
Assert.Equal(ComponentMetadata.Bind.TagHelperKind, parameter.Kind);
Assert.False(parameter.IsDefaultKind());
Assert.Equal(
"Specifies the culture to use for conversions.",
parameter.Documentation);
Assert.Equal("culture", parameter.Name);
Assert.Equal("Culture", parameter.GetPropertyName());
Assert.Equal(":culture", parameter.DisplayName);
// Defined from the property type
Assert.Equal("System.Globalization.CultureInfo", parameter.TypeName);
Assert.False(parameter.IsStringProperty);
Assert.False(parameter.IsBooleanProperty);
Assert.False(parameter.IsEnum);
}
private static TagHelperDescriptor[] GetBindTagHelpers(TagHelperDescriptorProviderContext context)
{
return ExcludeBuiltInComponents(context).Where(t => t.IsBindTagHelper()).ToArray();
}
}
}
| |
using System;
using Csla;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERCLevel;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D11_City_Child (editable child object).<br/>
/// This is a generated base class of <see cref="D11_City_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D10_City"/> collection.
/// </remarks>
[Serializable]
public partial class D11_City_Child : BusinessBase<D11_City_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D11_City_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D11_City_Child"/> object.</returns>
internal static D11_City_Child NewD11_City_Child()
{
return DataPortal.CreateChild<D11_City_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="D11_City_Child"/> object, based on given parameters.
/// </summary>
/// <param name="city_ID1">The City_ID1 parameter of the D11_City_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="D11_City_Child"/> object.</returns>
internal static D11_City_Child GetD11_City_Child(int city_ID1)
{
return DataPortal.FetchChild<D11_City_Child>(city_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D11_City_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D11_City_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D11_City_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D11_City_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="city_ID1">The City ID1.</param>
protected void Child_Fetch(int city_ID1)
{
var args = new DataPortalHookArgs(city_ID1);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<ID11_City_ChildDal>();
var data = dal.Fetch(city_ID1);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="D11_City_Child"/> object from the given <see cref="D11_City_ChildDto"/>.
/// </summary>
/// <param name="data">The D11_City_ChildDto to use.</param>
private void Fetch(D11_City_ChildDto data)
{
// Value properties
LoadProperty(City_Child_NameProperty, data.City_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D11_City_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D10_City parent)
{
var dto = new D11_City_ChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<ID11_City_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D11_City_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D10_City parent)
{
if (!IsDirty)
return;
var dto = new D11_City_ChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<ID11_City_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="D11_City_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D10_City parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<ID11_City_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.City_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/**
* 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.
*
* Contains some contributions under the Thrift Software License.
* Please see doc/old-thrift-license.txt in the Thrift distribution for
* details.
*/
using System;
using System.Net.Sockets;
namespace Thrift.Transport
{
public class TSocket : TStreamTransport
{
private TcpClient client = null;
private string host = null;
private int port = 0;
private int timeout = 0;
public TSocket(TcpClient client)
{
this.client = client;
if (IsOpen)
{
inputStream = client.GetStream();
outputStream = client.GetStream();
}
}
public TSocket(string host, int port)
: this(host, port, 0)
{
}
public TSocket(string host, int port, int timeout)
{
this.host = host;
this.port = port;
this.timeout = timeout;
InitSocket();
}
private void InitSocket()
{
this.client = TSocketVersionizer.CreateTcpClient();
this.client.ReceiveTimeout = client.SendTimeout = timeout;
this.client.Client.NoDelay = true;
}
public int Timeout
{
set
{
client.ReceiveTimeout = client.SendTimeout = timeout = value;
}
}
public TcpClient TcpClient
{
get
{
return client;
}
}
public string Host
{
get
{
return host;
}
}
public int Port
{
get
{
return port;
}
}
public override bool IsOpen
{
get
{
if (client == null)
{
return false;
}
return client.Connected;
}
}
public override void Open()
{
if (IsOpen)
{
throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
}
if (string.IsNullOrEmpty(host))
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host");
}
if (port <= 0)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
}
if (client == null)
{
InitSocket();
}
if (timeout == 0) // no timeout -> infinite
{
client.Connect(host, port);
}
else // we have a timeout -> use it
{
ConnectHelper hlp = new ConnectHelper(client);
IAsyncResult asyncres = client.BeginConnect(host, port, new AsyncCallback(ConnectCallback), hlp);
bool bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && client.Connected;
if (!bConnected)
{
lock (hlp.Mutex)
{
if (hlp.CallbackDone)
{
asyncres.AsyncWaitHandle.Close();
client.Close();
}
else
{
hlp.DoCleanup = true;
client = null;
}
}
throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out");
}
}
inputStream = client.GetStream();
outputStream = client.GetStream();
}
static void ConnectCallback(IAsyncResult asyncres)
{
ConnectHelper hlp = asyncres.AsyncState as ConnectHelper;
lock (hlp.Mutex)
{
hlp.CallbackDone = true;
try
{
if (hlp.Client.Client != null)
hlp.Client.EndConnect(asyncres);
}
catch (Exception)
{
// catch that away
}
if (hlp.DoCleanup)
{
try
{
asyncres.AsyncWaitHandle.Close();
}
catch (Exception) { }
try
{
if (hlp.Client is IDisposable)
((IDisposable)hlp.Client).Dispose();
}
catch (Exception) { }
hlp.Client = null;
}
}
}
private class ConnectHelper
{
public object Mutex = new object();
public bool DoCleanup = false;
public bool CallbackDone = false;
public TcpClient Client;
public ConnectHelper(TcpClient client)
{
Client = client;
}
}
public override void Close()
{
base.Close();
if (client != null)
{
client.Close();
client = null;
}
}
#region " IDisposable Support "
private bool _IsDisposed;
// IDisposable
protected override void Dispose(bool disposing)
{
if (!_IsDisposed)
{
if (disposing)
{
if (client != null)
((IDisposable)client).Dispose();
base.Dispose(disposing);
}
}
_IsDisposed = true;
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Cache.Query.Continuous
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Resource;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
using CQU = ContinuousQueryUtils;
/// <summary>
/// Continuous query handle interface.
/// </summary>
internal interface IContinuousQueryHandleImpl : IDisposable
{
/// <summary>
/// Process callback.
/// </summary>
/// <param name="stream">Stream.</param>
/// <returns>Result.</returns>
void Apply(IBinaryStream stream);
}
/// <summary>
/// Continuous query handle.
/// </summary>
internal class ContinuousQueryHandleImpl<TK, TV> : IContinuousQueryHandleImpl, IContinuousQueryFilter,
IContinuousQueryHandle<ICacheEntry<TK, TV>>
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Keep binary flag. */
private readonly bool _keepBinary;
/** Real listener. */
private readonly ICacheEntryEventListener<TK, TV> _lsnr;
/** Real filter. */
private readonly ICacheEntryEventFilter<TK, TV> _filter;
/** GC handle. */
private long _hnd;
/** Native query. */
private volatile IUnmanagedTarget _nativeQry;
/** Initial query cursor. */
private volatile IQueryCursor<ICacheEntry<TK, TV>> _initialQueryCursor;
/** Disposed flag. */
private bool _disposed;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="qry">Query.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="keepBinary">Keep binary flag.</param>
public ContinuousQueryHandleImpl(ContinuousQuery<TK, TV> qry, Marshaller marsh, bool keepBinary)
{
_marsh = marsh;
_keepBinary = keepBinary;
_lsnr = qry.Listener;
_filter = qry.Filter;
}
/// <summary>
/// Start execution.
/// </summary>
/// <param name="grid">Ignite instance.</param>
/// <param name="writer">Writer.</param>
/// <param name="cb">Callback invoked when all necessary data is written to stream.</param>
/// <param name="qry">Query.</param>
public void Start(Ignite grid, BinaryWriter writer, Func<IUnmanagedTarget> cb,
ContinuousQuery<TK, TV> qry)
{
// 1. Inject resources.
ResourceProcessor.Inject(_lsnr, grid);
ResourceProcessor.Inject(_filter, grid);
// 2. Allocate handle.
_hnd = grid.HandleRegistry.Allocate(this);
// 3. Write data to stream.
writer.WriteLong(_hnd);
writer.WriteBoolean(qry.Local);
writer.WriteBoolean(_filter != null);
var filterHolder = _filter == null || qry.Local ? null :
new ContinuousQueryFilterHolder(_filter, _keepBinary);
writer.WriteObject(filterHolder);
writer.WriteInt(qry.BufferSize);
writer.WriteLong((long)qry.TimeInterval.TotalMilliseconds);
writer.WriteBoolean(qry.AutoUnsubscribe);
// 4. Call Java.
_nativeQry = cb();
// 5. Initial query.
var nativeInitialQryCur = UU.ContinuousQueryGetInitialQueryCursor(_nativeQry);
_initialQueryCursor = nativeInitialQryCur == null
? null
: new QueryCursor<TK, TV>(nativeInitialQryCur, _marsh, _keepBinary);
}
/** <inheritdoc /> */
public void Apply(IBinaryStream stream)
{
ICacheEntryEvent<TK, TV>[] evts = CQU.ReadEvents<TK, TV>(stream, _marsh, _keepBinary);
_lsnr.OnEvent(evts);
}
/** <inheritdoc /> */
public bool Evaluate(IBinaryStream stream)
{
Debug.Assert(_filter != null, "Evaluate should not be called if filter is not set.");
ICacheEntryEvent<TK, TV> evt = CQU.ReadEvent<TK, TV>(stream, _marsh, _keepBinary);
return _filter.Evaluate(evt);
}
/** <inheritdoc /> */
public void Inject(Ignite grid)
{
throw new NotSupportedException("Should not be called.");
}
/** <inheritdoc /> */
public long Allocate()
{
throw new NotSupportedException("Should not be called.");
}
/** <inheritdoc /> */
public void Release()
{
_marsh.Ignite.HandleRegistry.Release(_hnd);
}
/** <inheritdoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> GetInitialQueryCursor()
{
lock (this)
{
if (_disposed)
throw new ObjectDisposedException("Continuous query handle has been disposed.");
var cur = _initialQueryCursor;
if (cur == null)
throw new InvalidOperationException("GetInitialQueryCursor() can be called only once.");
_initialQueryCursor = null;
return cur;
}
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "There is no finalizer.")]
public void Dispose()
{
lock (this)
{
if (_disposed || _nativeQry == null)
return;
try
{
UU.ContinuousQueryClose(_nativeQry);
}
finally
{
_nativeQry.Dispose();
_disposed = true;
}
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using FileHelpers.Events;
namespace FileHelpers.DataLink
{
#region " Delegates "
/// <summary>
/// Delegate used by the <see cref="DatabaseStorage"/> to get the SQL for
/// the insert or update statement.
/// </summary>
/// <param name="record">The record to insert</param>
/// <return>The SQL string to insert the record.</return>
public delegate string InsertSqlHandler(object record);
/// <summary>
/// Delegate used by the <see cref="DatabaseStorage"/> to fill the values
/// of a new record from the db (you only need to assign the values.
/// </summary>
/// <param name="record">The record to fill.</param>
/// <param name="fieldValues">
/// The values read from the database, you need to use these to fill the record.
/// </param>
public delegate void FillRecordHandler(object record, object[] fieldValues);
#endregion
/// <summary>
/// This class implements the <see cref="DataStorage"/> and is the base
/// class for Data Base storages.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public abstract class DatabaseStorage : DataStorage
{
#region Constructors
/// <summary>Default constructor.</summary>
/// <param name="recordType">The Record Type.</param>
protected DatabaseStorage(Type recordType)
: base(recordType) {}
#endregion
#region FillRecord
/// <summary>
/// This method receives the fields values as an array and returns
/// a record object.
/// </summary>
/// <param name="fieldValues">The record fields values.</param>
/// <returns>The record object.</returns>
private object FillRecord(object[] fieldValues)
{
if (FillRecordCallback == null) {
//?FillRecordCallbackIsNull"You can't extract records with a null FillRecordCallback. Check the docs for help."
throw new BadUsageException("FileHelperMsg_FillRecordCallbackIsNull", null);
}
object res = mRecordInfo.Operations.CreateRecordHandler();
FillRecordCallback(res, fieldValues);
return res;
}
#endregion
#region SelectSql
/// <summary>
/// Must return the Select SQL used to Fetch the records to Extract.
/// </summary>
/// <returns>The SQL statement.</returns>
private string GetSelectSql()
{
if (mSelectSql == null ||
mSelectSql == string.Empty) {
//?SelectSqlPropIsEmpty"The SelectSql property is empty, please set it before trying to get the records."
throw new BadUsageException("FileHelperMsg_SelectSqlPropIsEmpty", null);
}
return mSelectSql;
}
private string mSelectSql = string.Empty;
/// <summary>
/// Get or set the SQL statement used to get the records.
/// </summary>
public string SelectSql
{
get { return mSelectSql; }
set { mSelectSql = value; }
}
#endregion
#region GetInsertSql
/// <summary>
/// Return a SQL string with the insert statement for the records.
/// </summary>
/// <param name="record">The record to insert.</param>
/// <returns>The SQL string to used to insert the record.</returns>
private string GetInsertSql(object record)
{
if (mInsertSqlCallback == null) {
//?GetInsertSqlCallbackIsNull"You can't insert records with a null GetInsertSqlCallback. Check the docs for help."
throw new BadUsageException("FileHelperMsg_GetInsertSqlCallbackIsNull", null);
}
return mInsertSqlCallback(record);
}
#endregion
#region MustOverride Methods
/// <summary>Create connection object for the datasource.</summary>
/// <returns>An Connection Object.</returns>
protected abstract IDbConnection CreateConnection();
#endregion
#region Connections
private IDbConnection mConn;
private void InitConnection()
{
if (mConn == null)
mConn = CreateConnection();
}
#endregion
#region Commands
private int mCommandTimeout = 30;
/// <summary>
/// Get or set the SQL CommandTimeout used to get and insert the records.
/// </summary>
public int CommandTimeout
{
get { return mCommandTimeout; }
set { mCommandTimeout = value; }
}
#endregion
#region " SelectRecords "
/// <summary>
/// Must return the records from the DataSource (DB, Excel, etc)
/// </summary>
/// <returns>The extracted records.</returns>
public override object[] ExtractRecords()
{
InitConnection();
ArrayList res = new ArrayList();
try {
if (mConn.State != ConnectionState.Open)
mConn.Open();
IDbCommand command = mConn.CreateCommand();
command.Connection = mConn;
command.CommandText = GetSelectSql();
command.CommandTimeout = mCommandTimeout;
IDataReader reader = command.ExecuteReader();
object currentObj;
object[] values = new object[reader.FieldCount];
OnProgress(new ProgressEventArgs(0, -1));
int recordNumber = 0;
while (reader.Read()) {
recordNumber++;
OnProgress(new ProgressEventArgs(recordNumber, -1));
reader.GetValues(values);
currentObj = FillRecord(values);
res.Add(currentObj);
}
reader.Close();
}
finally {
if (mConn.State != ConnectionState.Closed)
mConn.Close();
}
return (object[]) res.ToArray(RecordType);
}
#endregion
#region ExecuteInBatch
/// <summary>
/// Indicates if the underlying Connection allows more than one
/// instruction per execute.
/// </summary>
protected virtual bool ExecuteInBatch
{
get { return false; }
}
#endregion
#region " InsertRecords "
/// <summary>
/// Insert the records in a DataSource (DB, Excel, etc)
/// </summary>
/// <param name="records">The records to insert.</param>
public override void InsertRecords(object[] records)
{
IDbTransaction trans = null;
try {
InitConnection();
if (mConn.State != ConnectionState.Open)
mConn.Open();
string SQL = String.Empty;
trans = InitTransaction(mConn);
OnProgress(new ProgressEventArgs(0, records.Length));
int recordNumber = 0;
int batchCount = 0;
foreach (object record in records) {
// Insert Logic Here, must check duplicates
recordNumber++;
batchCount++;
OnProgress(new ProgressEventArgs(recordNumber, records.Length));
SQL += GetInsertSql(record) + " ";
if (ExecuteInBatch) {
if (batchCount >= mExecuteInBatchSize) {
ExecuteAndLeaveOpen(SQL);
SQL = String.Empty;
batchCount = 0;
}
}
else {
ExecuteAndLeaveOpen(SQL);
SQL = String.Empty;
}
}
if (SQL != null &&
SQL.Length != 0) {
ExecuteAndLeaveOpen(SQL);
SQL = String.Empty;
}
CommitTransaction(trans);
}
catch {
RollBackTransaction(trans);
throw;
}
finally {
try {
mConn.Close();
mConn.Dispose();
mConn = null;
}
catch {}
}
}
#endregion
#region " ExecuteNonQuery (HelperMethods) "
private int ExecuteAndLeaveOpen(string sql)
{
InitConnection();
IDbCommand command = mConn.CreateCommand();
command.Connection = mConn;
command.CommandText = sql;
command.CommandTimeout = mCommandTimeout;
return command.ExecuteNonQuery();
}
private int ExecuteAndClose(string sql)
{
int res = -1;
InitConnection();
try {
if (mConn.State != ConnectionState.Open)
mConn.Open();
IDbCommand command = mConn.CreateCommand();
command.Connection = mConn;
command.CommandText = sql;
command.CommandTimeout = mCommandTimeout;
res = command.ExecuteNonQuery();
}
finally {
if (mConn.State != ConnectionState.Closed)
mConn.Close();
}
return res;
}
#endregion
#region InsertSqlCallback
private InsertSqlHandler mInsertSqlCallback;
/// <summary>
/// Delegate used to get the SQL for the insert or update statement.
/// </summary>
public InsertSqlHandler InsertSqlCallback
{
get { return mInsertSqlCallback; }
set { mInsertSqlCallback = value; }
}
#endregion
#region FillRecordCallback
private FillRecordHandler mFillRecordCallback;
/// <summary>
/// Delegate used to fill the values of a new record from the db.
/// </summary>
public FillRecordHandler FillRecordCallback
{
get { return mFillRecordCallback; }
set { mFillRecordCallback = value; }
}
#endregion
#region ExecuteInBatchSize
private int mExecuteInBatchSize = 100;
/// <summary>
/// Indicates the max number of instruction for each execution. High
/// numbers helps reduce the round trips to the db and so
/// improves performance.
/// </summary>
public int ExecuteInBatchSize
{
get { return mExecuteInBatchSize; }
set
{
if (value < 1)
//?ExecuteInBatchSizeIsZero"ExecuteInBatchSize must be >= 1"
throw new BadUsageException("FileHelperMsg_ExecuteInBatchSizeIsZero", null);
mExecuteInBatchSize = value;
}
}
#endregion
private TransactionMode mTransactionMode = TransactionMode.NoTransaction;
/// <summary>
/// Define the Transaction Level used when inserting records.
/// </summary>
public TransactionMode TransactionMode
{
get { return mTransactionMode; }
set { mTransactionMode = value; }
}
private IDbTransaction InitTransaction(IDbConnection conn)
{
if (mTransactionMode == TransactionMode.NoTransaction)
return null;
switch (mTransactionMode) {
case TransactionMode.UseDefault:
return conn.BeginTransaction();
case TransactionMode.UseChaosLevel:
return conn.BeginTransaction(IsolationLevel.Chaos);
case TransactionMode.UseReadCommitted:
return conn.BeginTransaction(IsolationLevel.ReadCommitted);
case TransactionMode.UseReadUnCommitted:
return conn.BeginTransaction(IsolationLevel.ReadUncommitted);
case TransactionMode.UseRepeatableRead:
return conn.BeginTransaction(IsolationLevel.RepeatableRead);
case TransactionMode.UseSerializable:
return conn.BeginTransaction(IsolationLevel.Serializable);
}
return null;
}
private void CommitTransaction(IDbTransaction trans)
{
if (trans == null)
return;
trans.Commit();
}
private void RollBackTransaction(IDbTransaction trans)
{
if (trans == null)
return;
trans.Rollback();
}
private string mConnectionString = String.Empty;
/// <summary>
/// The connection string used for this storage.
/// </summary>
public string ConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
}
}
| |
// 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>
/// Asset Relationship
///<para>SObject Name: AssetRelationship</para>
///<para>Custom Object: False</para>
///</summary>
public class SfAssetRelationship : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "AssetRelationship"; }
}
///<summary>
/// Asset Relationship ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Deleted
/// <para>Name: IsDeleted</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isDeleted")]
[Updateable(false), Createable(false)]
public bool? IsDeleted { get; set; }
///<summary>
/// Asset Relationship Number
/// <para>Name: AssetRelationshipNumber</para>
/// <para>SF Type: string</para>
/// <para>AutoNumber field</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "assetRelationshipNumber")]
[Updateable(false), Createable(false)]
public string AssetRelationshipNumber { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// 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>
/// Last Referenced Date
/// <para>Name: LastReferencedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastReferencedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastReferencedDate { get; set; }
///<summary>
/// Asset ID
/// <para>Name: AssetId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "assetId")]
[Updateable(false), Createable(true)]
public string AssetId { get; set; }
///<summary>
/// ReferenceTo: Asset
/// <para>RelationshipName: Asset</para>
///</summary>
[JsonProperty(PropertyName = "asset")]
[Updateable(false), Createable(false)]
public SfAsset Asset { get; set; }
///<summary>
/// Asset ID
/// <para>Name: RelatedAssetId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "relatedAssetId")]
public string RelatedAssetId { get; set; }
///<summary>
/// ReferenceTo: Asset
/// <para>RelationshipName: RelatedAsset</para>
///</summary>
[JsonProperty(PropertyName = "relatedAsset")]
[Updateable(false), Createable(false)]
public SfAsset RelatedAsset { get; set; }
///<summary>
/// From Date
/// <para>Name: FromDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fromDate")]
public DateTimeOffset? FromDate { get; set; }
///<summary>
/// To Date
/// <para>Name: ToDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "toDate")]
public DateTimeOffset? ToDate { get; set; }
///<summary>
/// Relationship Type
/// <para>Name: RelationshipType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "relationshipType")]
public string RelationshipType { get; set; }
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using dnlib.DotNet.Emit;
namespace dnlib.DotNet.Writer {
/// <summary>
/// Returns tokens of token types, strings and signatures
/// </summary>
public interface ITokenProvider : IWriterError {
/// <summary>
/// Gets the token of <paramref name="o"/>
/// </summary>
/// <param name="o">A token type or a string or a signature</param>
/// <returns>The token</returns>
MDToken GetToken(object o);
/// <summary>
/// Gets a <c>StandAloneSig</c> token
/// </summary>
/// <param name="locals">All locals</param>
/// <param name="origToken">The original token or <c>0</c> if none</param>
/// <returns>A <c>StandAloneSig</c> token or <c>0</c> if <paramref name="locals"/> is
/// empty.</returns>
MDToken GetToken(IList<TypeSig> locals, uint origToken);
}
/// <summary>
/// Writes CIL method bodies
/// </summary>
public sealed class MethodBodyWriter : MethodBodyWriterBase {
readonly ITokenProvider helper;
MethodDef method;
CilBody cilBody;
bool keepMaxStack;
uint codeSize;
uint maxStack;
byte[] code;
byte[] extraSections;
uint localVarSigTok;
/// <summary>
/// Gets the code as a byte array. This is valid only after calling <see cref="Write()"/>.
/// The size of this array is not necessarily a multiple of 4, even if there are exception
/// handlers present. See also <see cref="GetFullMethodBody()"/>
/// </summary>
public byte[] Code => code;
/// <summary>
/// Gets the extra sections (exception handlers) as a byte array or <c>null</c> if there
/// are no exception handlers. This is valid only after calling <see cref="Write()"/>
/// </summary>
public byte[] ExtraSections => extraSections;
/// <summary>
/// Gets the token of the locals
/// </summary>
public uint LocalVarSigTok => localVarSigTok;
/// <summary>
/// Constructor
/// </summary>
/// <param name="helper">Helps this instance</param>
/// <param name="method">The method</param>
public MethodBodyWriter(ITokenProvider helper, MethodDef method)
: this(helper, method, false) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="helper">Helps this instance</param>
/// <param name="method">The method</param>
/// <param name="keepMaxStack">Keep the original max stack value that has been initialized
/// in <paramref name="method"/></param>
public MethodBodyWriter(ITokenProvider helper, MethodDef method, bool keepMaxStack)
: base(method.Body.Instructions, method.Body.ExceptionHandlers) {
this.helper = helper;
this.method = method;
this.keepMaxStack = keepMaxStack;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="helper">Helps this instance</param>
/// <param name="cilBody">The CIL method body</param>
public MethodBodyWriter(ITokenProvider helper, CilBody cilBody)
: this(helper, cilBody, false) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="helper">Helps this instance</param>
/// <param name="cilBody">The CIL method body</param>
/// <param name="keepMaxStack">Keep the original max stack value that has been initialized
/// in <paramref name="cilBody"/></param>
public MethodBodyWriter(ITokenProvider helper, CilBody cilBody, bool keepMaxStack)
: base(cilBody.Instructions, cilBody.ExceptionHandlers) {
this.helper = helper;
this.cilBody = cilBody;
this.keepMaxStack = keepMaxStack;
}
internal MethodBodyWriter(ITokenProvider helper) {
this.helper = helper;
}
internal void Reset(MethodDef method, bool keepMaxStack) {
this.method = method;
this.keepMaxStack = keepMaxStack;
cilBody = method.Body;
codeSize = 0;
maxStack = 0;
code = null;
extraSections = null;
localVarSigTok = 0;
Reset(cilBody.Instructions, cilBody.ExceptionHandlers);
}
/// <summary>
/// Writes the method body
/// </summary>
public void Write() {
codeSize = InitializeInstructionOffsets();
maxStack = keepMaxStack ? cilBody.MaxStack : GetMaxStack();
if (NeedFatHeader())
WriteFatHeader();
else
WriteTinyHeader();
if (exceptionHandlers.Count > 0)
WriteExceptionHandlers();
}
/// <summary>
/// Gets the code and (possible) exception handlers in one array. The exception handlers
/// are 4-byte aligned.
/// </summary>
/// <returns>The code and any exception handlers</returns>
public byte[] GetFullMethodBody() {
int padding = Utils.AlignUp(code.Length, 4) - code.Length;
var bytes = new byte[code.Length + (extraSections is null ? 0 : padding + extraSections.Length)];
Array.Copy(code, 0, bytes, 0, code.Length);
if (extraSections is not null)
Array.Copy(extraSections, 0, bytes, code.Length + padding, extraSections.Length);
return bytes;
}
bool NeedFatHeader() {
//TODO: If locals has cust attrs or custom debug infos, we also need a fat header
return codeSize > 0x3F ||
exceptionHandlers.Count > 0 ||
cilBody.HasVariables ||
maxStack > 8;
}
void WriteFatHeader() {
if (maxStack > ushort.MaxValue) {
Error("MaxStack is too big");
maxStack = ushort.MaxValue;
}
ushort flags = 0x3003;
if (exceptionHandlers.Count > 0)
flags |= 8;
if (cilBody.InitLocals)
flags |= 0x10;
code = new byte[12 + codeSize];
var writer = new ArrayWriter(code);
writer.WriteUInt16(flags);
writer.WriteUInt16((ushort)maxStack);
writer.WriteUInt32(codeSize);
writer.WriteUInt32(localVarSigTok = helper.GetToken(GetLocals(), cilBody.LocalVarSigTok).Raw);
if (WriteInstructions(ref writer) != codeSize)
Error("Didn't write all code bytes");
}
IList<TypeSig> GetLocals() {
var localsSig = new TypeSig[cilBody.Variables.Count];
for (int i = 0; i < cilBody.Variables.Count; i++)
localsSig[i] = cilBody.Variables[i].Type;
return localsSig;
}
void WriteTinyHeader() {
localVarSigTok = 0;
code = new byte[1 + codeSize];
var writer = new ArrayWriter(code);
writer.WriteByte((byte)((codeSize << 2) | 2));
if (WriteInstructions(ref writer) != codeSize)
Error("Didn't write all code bytes");
}
void WriteExceptionHandlers() {
if (NeedFatExceptionClauses())
extraSections = WriteFatExceptionClauses();
else
extraSections = WriteSmallExceptionClauses();
}
bool NeedFatExceptionClauses() {
// Size must fit in a byte, and since one small exception record is 12 bytes
// and header is 4 bytes: x*12+4 <= 255 ==> x <= 20
var exceptionHandlers = this.exceptionHandlers;
if (exceptionHandlers.Count > 20)
return true;
for (int i = 0; i < exceptionHandlers.Count; i++) {
var eh = exceptionHandlers[i];
if (!FitsInSmallExceptionClause(eh.TryStart, eh.TryEnd))
return true;
if (!FitsInSmallExceptionClause(eh.HandlerStart, eh.HandlerEnd))
return true;
}
return false;
}
bool FitsInSmallExceptionClause(Instruction start, Instruction end) {
uint offs1 = GetOffset2(start);
uint offs2 = GetOffset2(end);
if (offs2 < offs1)
return false;
return offs1 <= ushort.MaxValue && offs2 - offs1 <= byte.MaxValue;
}
uint GetOffset2(Instruction instr) {
if (instr is null)
return codeSize;
return GetOffset(instr);
}
byte[] WriteFatExceptionClauses() {
const int maxExceptionHandlers = (0x00FFFFFF - 4) / 24;
var exceptionHandlers = this.exceptionHandlers;
int numExceptionHandlers = exceptionHandlers.Count;
if (numExceptionHandlers > maxExceptionHandlers) {
Error("Too many exception handlers");
numExceptionHandlers = maxExceptionHandlers;
}
var data = new byte[numExceptionHandlers * 24 + 4];
var writer = new ArrayWriter(data);
writer.WriteUInt32((((uint)numExceptionHandlers * 24 + 4) << 8) | 0x41);
for (int i = 0; i < numExceptionHandlers; i++) {
var eh = exceptionHandlers[i];
uint offs1, offs2;
writer.WriteUInt32((uint)eh.HandlerType);
offs1 = GetOffset2(eh.TryStart);
offs2 = GetOffset2(eh.TryEnd);
if (offs2 <= offs1)
Error("Exception handler: TryEnd <= TryStart");
writer.WriteUInt32(offs1);
writer.WriteUInt32(offs2 - offs1);
offs1 = GetOffset2(eh.HandlerStart);
offs2 = GetOffset2(eh.HandlerEnd);
if (offs2 <= offs1)
Error("Exception handler: HandlerEnd <= HandlerStart");
writer.WriteUInt32(offs1);
writer.WriteUInt32(offs2 - offs1);
if (eh.IsCatch)
writer.WriteUInt32(helper.GetToken(eh.CatchType).Raw);
else if (eh.IsFilter)
writer.WriteUInt32(GetOffset2(eh.FilterStart));
else
writer.WriteInt32(0);
}
if (writer.Position != data.Length)
throw new InvalidOperationException();
return data;
}
byte[] WriteSmallExceptionClauses() {
const int maxExceptionHandlers = (0xFF - 4) / 12;
var exceptionHandlers = this.exceptionHandlers;
int numExceptionHandlers = exceptionHandlers.Count;
if (numExceptionHandlers > maxExceptionHandlers) {
Error("Too many exception handlers");
numExceptionHandlers = maxExceptionHandlers;
}
var data = new byte[numExceptionHandlers * 12 + 4];
var writer = new ArrayWriter(data);
writer.WriteUInt32((((uint)numExceptionHandlers * 12 + 4) << 8) | 1);
for (int i = 0; i < numExceptionHandlers; i++) {
var eh = exceptionHandlers[i];
uint offs1, offs2;
writer.WriteUInt16((ushort)eh.HandlerType);
offs1 = GetOffset2(eh.TryStart);
offs2 = GetOffset2(eh.TryEnd);
if (offs2 <= offs1)
Error("Exception handler: TryEnd <= TryStart");
writer.WriteUInt16((ushort)offs1);
writer.WriteByte((byte)(offs2 - offs1));
offs1 = GetOffset2(eh.HandlerStart);
offs2 = GetOffset2(eh.HandlerEnd);
if (offs2 <= offs1)
Error("Exception handler: HandlerEnd <= HandlerStart");
writer.WriteUInt16((ushort)offs1);
writer.WriteByte((byte)(offs2 - offs1));
if (eh.IsCatch)
writer.WriteUInt32(helper.GetToken(eh.CatchType).Raw);
else if (eh.IsFilter)
writer.WriteUInt32(GetOffset2(eh.FilterStart));
else
writer.WriteInt32(0);
}
if (writer.Position != data.Length)
throw new InvalidOperationException();
return data;
}
/// <inheritdoc/>
protected override void ErrorImpl(string message) {
if (method is not null && helper is IWriterError2 writerError2)
writerError2.Error(message + " At method {0} ({1:X8}).", method, method.MDToken.Raw);
else
helper.Error(message);
}
/// <inheritdoc/>
protected override void WriteInlineField(ref ArrayWriter writer, Instruction instr) => writer.WriteUInt32(helper.GetToken(instr.Operand).Raw);
/// <inheritdoc/>
protected override void WriteInlineMethod(ref ArrayWriter writer, Instruction instr) => writer.WriteUInt32(helper.GetToken(instr.Operand).Raw);
/// <inheritdoc/>
protected override void WriteInlineSig(ref ArrayWriter writer, Instruction instr) => writer.WriteUInt32(helper.GetToken(instr.Operand).Raw);
/// <inheritdoc/>
protected override void WriteInlineString(ref ArrayWriter writer, Instruction instr) => writer.WriteUInt32(helper.GetToken(instr.Operand).Raw);
/// <inheritdoc/>
protected override void WriteInlineTok(ref ArrayWriter writer, Instruction instr) => writer.WriteUInt32(helper.GetToken(instr.Operand).Raw);
/// <inheritdoc/>
protected override void WriteInlineType(ref ArrayWriter writer, Instruction instr) => writer.WriteUInt32(helper.GetToken(instr.Operand).Raw);
}
}
| |
using System;
using System.Threading;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Used by MockRAMDirectory to create an output stream that
/// will throw anSystem.IO.IOException on fake disk full, track max
/// disk space actually used, and maybe throw random
///System.IO.IOExceptions.
/// </summary>
public class MockIndexOutputWrapper : IndexOutput
{
private MockDirectoryWrapper Dir;
private readonly IndexOutput @delegate;
private bool First = true;
internal readonly string Name;
internal byte[] SingleByte = new byte[1];
/// <summary>
/// Construct an empty output buffer. </summary>
public MockIndexOutputWrapper(MockDirectoryWrapper dir, IndexOutput @delegate, string name)
{
this.Dir = dir;
this.Name = name;
this.@delegate = @delegate;
}
private void CheckCrashed()
{
// If MockRAMDir crashed since we were opened, then don't write anything
if (Dir.Crashed)
{
throw new System.IO.IOException("MockRAMDirectory was crashed; cannot write to " + Name);
}
}
private void CheckDiskFull(byte[] b, int offset, DataInput @in, long len)
{
long freeSpace = Dir.MaxSize == 0 ? 0 : Dir.MaxSize - Dir.GetSizeInBytes();
long realUsage = 0;
// Enforce disk full:
if (Dir.MaxSize != 0 && freeSpace <= len)
{
// Compute the real disk free. this will greatly slow
// down our test but makes it more accurate:
realUsage = Dir.RecomputedActualSizeInBytes;
freeSpace = Dir.MaxSize - realUsage;
}
if (Dir.MaxSize != 0 && freeSpace <= len)
{
if (freeSpace > 0)
{
realUsage += freeSpace;
if (b != null)
{
@delegate.WriteBytes(b, offset, (int)freeSpace);
}
else
{
@delegate.CopyBytes(@in, len);
}
}
if (realUsage > Dir.MaxUsedSize)
{
Dir.MaxUsedSize = realUsage;
}
string message = "fake disk full at " + Dir.RecomputedActualSizeInBytes + " bytes when writing " + Name + " (file length=" + @delegate.Length;
if (freeSpace > 0)
{
message += "; wrote " + freeSpace + " of " + len + " bytes";
}
message += ")";
/*if (LuceneTestCase.VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": MDW: now throw fake disk full");
(new Exception()).printStackTrace(System.out);
}*/
throw new System.IO.IOException(message);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
Dir.MaybeThrowDeterministicException();
}
finally
{
@delegate.Dispose();
if (Dir.TrackDiskUsage_Renamed)
{
// Now compute actual disk usage & track the maxUsedSize
// in the MockDirectoryWrapper:
long size = Dir.RecomputedActualSizeInBytes;
if (size > Dir.MaxUsedSize)
{
Dir.MaxUsedSize = size;
}
}
Dir.RemoveIndexOutput(this, Name);
}
}
}
public override void Flush()
{
Dir.MaybeThrowDeterministicException();
@delegate.Flush();
}
public override void WriteByte(byte b)
{
SingleByte[0] = b;
WriteBytes(SingleByte, 0, 1);
}
public override void WriteBytes(byte[] b, int offset, int len)
{
CheckCrashed();
CheckDiskFull(b, offset, null, len);
if (Dir.RandomState.Next(200) == 0)
{
int half = len / 2;
@delegate.WriteBytes(b, offset, half);
Thread.Sleep(0);
@delegate.WriteBytes(b, offset + half, len - half);
}
else
{
@delegate.WriteBytes(b, offset, len);
}
Dir.MaybeThrowDeterministicException();
if (First)
{
// Maybe throw random exception; only do this on first
// write to a new file:
First = false;
Dir.MaybeThrowIOException(Name);
}
}
public override long GetFilePointer()
{
return @delegate.GetFilePointer();
}
[Obsolete("(4.1) this method will be removed in Lucene 5.0")]
public override void Seek(long pos)
{
@delegate.Seek(pos);
}
public override long Length
{
get
{
return @delegate.Length;
}
set
{
@delegate.Length = value;
}
}
public override void CopyBytes(DataInput input, long numBytes)
{
CheckCrashed();
CheckDiskFull(null, 0, input, numBytes);
@delegate.CopyBytes(input, numBytes);
Dir.MaybeThrowDeterministicException();
}
public override long Checksum
{
get
{
return @delegate.Checksum;
}
}
public override string ToString()
{
return "MockIndexOutputWrapper(" + @delegate + ")";
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
/*
// ===========================================================================
Defines structs that package an aggregate member together with
generic type argument information.
// ===========================================================================*/
/******************************************************************************
SymWithType and its cousins. These package an aggregate member (field,
prop, event, or meth) together with the particular instantiation of the
aggregate (the AggregateType).
The default constructor does nothing so these are not safe to use
uninitialized. Note that when they are used as member of an EXPR they
are automatically zero filled by newExpr.
******************************************************************************/
internal class SymWithType
{
private AggregateType _ats;
private Symbol _sym;
public SymWithType()
{
}
public SymWithType(Symbol sym, AggregateType ats)
{
Set(sym, ats);
}
public virtual void Clear()
{
_sym = null;
_ats = null;
}
public AggregateType Ats
{
get { return _ats; }
}
public Symbol Sym
{
get { return _sym; }
}
public new AggregateType GetType()
{
// This conflicts with object.GetType. Turn every usage of this
// into a get on Ats.
return Ats;
}
public static bool operator ==(SymWithType swt1, SymWithType swt2)
{
if (ReferenceEquals(swt1, swt2))
{
return true;
}
else if (ReferenceEquals(swt1, null))
{
return swt2._sym == null;
}
else if (ReferenceEquals(swt2, null))
{
return swt1._sym == null;
}
return swt1.Sym == swt2.Sym && swt1.Ats == swt2.Ats;
}
public static bool operator !=(SymWithType swt1, SymWithType swt2) => !(swt1 == swt2);
[ExcludeFromCodeCoverage] // == overload should always be the method called.
public override bool Equals(object obj)
{
Debug.Fail("Sub-optimal equality called. Check if this is correct.");
SymWithType other = obj as SymWithType;
if (other == null) return false;
return Sym == other.Sym && Ats == other.Ats;
}
[ExcludeFromCodeCoverage] // Never used as a key.
public override int GetHashCode()
{
Debug.Fail("If using this as a key, implement IEquatable<SymWithType>");
return (Sym?.GetHashCode() ?? 0) + (Ats?.GetHashCode() ?? 0);
}
// The SymWithType is considered NULL iff the Symbol is NULL.
public static implicit operator bool (SymWithType swt)
{
return swt != null;
}
// These assert that the Symbol is of the correct type.
public MethodOrPropertySymbol MethProp()
{
return Sym as MethodOrPropertySymbol;
}
public MethodSymbol Meth()
{
return Sym as MethodSymbol;
}
public PropertySymbol Prop()
{
return Sym as PropertySymbol;
}
public FieldSymbol Field()
{
return Sym as FieldSymbol;
}
public EventSymbol Event()
{
return Sym as EventSymbol;
}
public void Set(Symbol sym, AggregateType ats)
{
if (sym == null)
ats = null;
Debug.Assert(ats == null || sym.parent == ats.getAggregate());
_sym = sym;
_ats = ats;
}
}
internal class MethPropWithType : SymWithType
{
public MethPropWithType()
{
}
public MethPropWithType(MethodOrPropertySymbol mps, AggregateType ats)
{
Set(mps, ats);
}
}
internal sealed class MethWithType : MethPropWithType
{
public MethWithType()
{
}
public MethWithType(MethodSymbol meth, AggregateType ats)
{
Set(meth, ats);
}
}
internal sealed class PropWithType : MethPropWithType
{
public PropWithType(PropertySymbol prop, AggregateType ats)
{
Set(prop, ats);
}
public PropWithType(SymWithType swt)
{
Set(swt.Sym as PropertySymbol, swt.Ats);
}
}
internal sealed class EventWithType : SymWithType
{
public EventWithType(EventSymbol @event, AggregateType ats)
{
Set(@event, ats);
}
}
internal sealed class FieldWithType : SymWithType
{
public FieldWithType(FieldSymbol field, AggregateType ats)
{
Set(field, ats);
}
}
/******************************************************************************
MethPropWithInst and MethWithInst. These extend MethPropWithType with
the method type arguments. Properties will never have type args, but
methods and properties share a lot of code so it's convenient to allow
both here.
The default constructor does nothing so these are not safe to use
uninitialized. Note that when they are used as member of an EXPR they
are automatically zero filled by newExpr.
******************************************************************************/
internal class MethPropWithInst : MethPropWithType
{
public TypeArray TypeArgs { get; private set; }
public MethPropWithInst()
{
Set(null, null, null);
}
public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats)
: this(mps, ats, null)
{
}
public MethPropWithInst(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs)
{
Set(mps, ats, typeArgs);
}
public override void Clear()
{
base.Clear();
TypeArgs = null;
}
public void Set(MethodOrPropertySymbol mps, AggregateType ats, TypeArray typeArgs)
{
if (mps == null)
{
ats = null;
typeArgs = null;
}
Debug.Assert(ats == null || mps != null && mps.getClass() == ats.getAggregate());
base.Set(mps, ats);
TypeArgs = typeArgs;
}
}
internal sealed class MethWithInst : MethPropWithInst
{
public MethWithInst(MethodSymbol meth, AggregateType ats)
: this(meth, ats, null)
{
}
public MethWithInst(MethodSymbol meth, AggregateType ats, TypeArray typeArgs)
{
Set(meth, ats, typeArgs);
}
public MethWithInst(MethPropWithInst mpwi)
{
Set(mpwi.Sym.AsMethodSymbol(), mpwi.Ats, mpwi.TypeArgs);
}
}
}
| |
// 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.Contracts;
namespace System.Globalization
{
public partial class CompareInfo
{
internal unsafe CompareInfo(CultureInfo culture)
{
_name = culture._name;
InitSort(culture);
}
private void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
const uint LCMAP_SORTHANDLE = 0x20000000;
_name = culture._name;
_sortName = culture.SortName;
IntPtr handle;
int ret = Interop.mincore.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero);
_sortHandle = ret > 0 ? handle : IntPtr.Zero;
}
private static unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
string stringSource,
int offset,
int cchSource,
string value,
int cchValue,
bool bIgnoreCase)
{
fixed (char* pSource = stringSource)
fixed (char* pValue = value)
{
int ret = Interop.mincore.FindStringOrdinal(
dwFindStringOrdinalFlags,
pSource + offset,
cchSource,
pValue,
cchValue,
bIgnoreCase ? 1 : 0);
return ret < 0 ? ret : ret + offset;
}
}
internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int tmpHash = 0;
fixed (char* pSource = source)
{
if (Interop.mincore.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
LCMAP_HASH | (uint)GetNativeCompareFlags(options),
pSource, source.Length,
&tmpHash, sizeof(int),
null, null, _sortHandle) == 0)
{
Environment.FailFast("LCMapStringEx failed!");
}
}
return tmpHash;
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
// Use the OS to compare and then convert the result to expected value by subtracting 2
return Interop.mincore.CompareStringOrdinal(string1, count1, string2, count2, true) - 2;
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Contract.Assert(string1 != null);
Contract.Assert(string2 != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pString1 = string1)
fixed (char* pString2 = string2)
{
int result = Interop.mincore.CompareStringEx(
pLocaleName,
(uint)GetNativeCompareFlags(options),
pString1 + offset1,
length1,
pString2 + offset2,
length2,
null,
null,
_sortHandle);
if (result == 0)
{
Environment.FailFast("CompareStringEx failed");
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
}
private unsafe int FindString(
uint dwFindNLSStringFlags,
string lpStringSource,
int startSource,
int cchSource,
string lpStringValue,
int startValue,
int cchValue)
{
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pSource = lpStringSource)
fixed (char* pValue = lpStringValue)
{
char* pS = pSource + startSource;
char* pV = pValue + startValue;
return Interop.mincore.FindNLSStringEx(
pLocaleName,
dwFindNLSStringFlags,
pS,
cchSource,
pV,
cchValue,
null,
null,
null,
_sortHandle);
}
}
private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false);
}
else
{
int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options),
source,
startIndex,
count,
target,
0,
target.Length);
if (retValue >= 0)
{
return retValue + startIndex;
}
}
return -1;
}
private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
// TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
// and add a precondition that target is not empty.
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true);
}
else
{
int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options),
source,
startIndex - count + 1,
count,
target,
0,
target.Length);
if (retValue >= 0)
{
return retValue + startIndex - (count - 1);
}
}
return -1;
}
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(prefix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
prefix,
0,
prefix.Length) >= 0;
}
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(suffix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
suffix,
0,
suffix.Length) >= 0;
}
// PAL ends here
[NonSerialized]
private readonly IntPtr _sortHandle;
private const uint LCMAP_HASH = 0x00040000;
private const int FIND_STARTSWITH = 0x00100000;
private const int FIND_ENDSWITH = 0x00200000;
private const int FIND_FROMSTART = 0x00400000;
private const int FIND_FROMEND = 0x00800000;
// TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false?
private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex)
{
int retValue = -1;
int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
#if !TEST_CODEGEN_OPTIMIZATION
fixed (char* pSource = source, spTarget = target)
{
char* spSubSource = pSource + sourceStartIndex;
#else
String.StringPointer spSubSource = source.GetStringPointer(sourceStartIndex);
String.StringPointer spTarget = target.GetStringPointer();
#endif
if (findLastIndex)
{
int startPattern = (sourceCount - 1) - targetCount + 1;
if (startPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex - sourceCount + 1;
}
}
else
{
int endPattern = (sourceCount - 1) - targetCount + 1;
if (endPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex;
}
}
#if !TEST_CODEGEN_OPTIMIZATION
}
return retValue;
#endif // TEST_CODEGEN_OPTIMIZATION
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
{
if (source==null) { throw new ArgumentNullException("source"); }
Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
}
throw new NotImplementedException();
}
private unsafe static bool IsSortable(char *text, int length)
{
// CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
// return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length));
throw new NotImplementedException();
}
private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal
private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
private static int GetNativeCompareFlags(CompareOptions options)
{
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
// TODO: Can we try for GetNativeCompareFlags to never
// take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special
// in some places.
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.IgnoreWidth |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
return nativeCompareFlags;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public abstract class ImmutableDictionaryTestBase : ImmutablesTestBase
{
[Fact]
public virtual void EmptyTest()
{
this.EmptyTestHelper(Empty<int, bool>(), 5);
}
[Fact]
public void EnumeratorTest()
{
this.EnumeratorTestHelper(this.Empty<int, GenericParameterHelper>());
}
[Fact]
public void ContainsTest()
{
this.ContainsTestHelper(Empty<int, string>(), 5, "foo");
}
[Fact]
public void RemoveTest()
{
this.RemoveTestHelper(Empty<int, GenericParameterHelper>(), 5);
}
[Fact]
public void KeysTest()
{
this.KeysTestHelper(Empty<int, bool>(), 5);
}
[Fact]
public void ValuesTest()
{
this.ValuesTestHelper(Empty<int, bool>(), 5);
}
[Fact]
public void AddAscendingTest()
{
this.AddAscendingTestHelper(Empty<int, GenericParameterHelper>());
}
[Fact]
public void AddRangeTest()
{
var map = Empty<int, GenericParameterHelper>();
map = map.AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper())));
CollectionAssertAreEquivalent(map.Select(kv => kv.Key).ToList(), Enumerable.Range(1, 100).ToList());
this.VerifyAvlTreeState(map);
Assert.Equal(100, map.Count);
// Test optimization for empty map.
var map2 = Empty<int, GenericParameterHelper>();
var jointMap = map2.AddRange(map);
Assert.Same(map, jointMap);
jointMap = map2.AddRange(map.ToReadOnlyDictionary());
Assert.Same(map, jointMap);
jointMap = map2.AddRange(map.ToBuilder());
Assert.Same(map, jointMap);
}
[Fact]
public void AddDescendingTest()
{
this.AddDescendingTestHelper(Empty<int, GenericParameterHelper>());
}
[Fact]
public void AddRemoveRandomDataTest()
{
this.AddRemoveRandomDataTestHelper(Empty<double, GenericParameterHelper>());
}
[Fact]
public void AddRemoveEnumerableTest()
{
this.AddRemoveEnumerableTestHelper(Empty<int, int>());
}
[Fact]
public void SetItemTest()
{
var map = this.Empty<string, int>()
.SetItem("Microsoft", 100)
.SetItem("Corporation", 50);
Assert.Equal(2, map.Count);
map = map.SetItem("Microsoft", 200);
Assert.Equal(2, map.Count);
Assert.Equal(200, map["Microsoft"]);
// Set it to the same thing again and make sure it's all good.
var sameMap = map.SetItem("Microsoft", 200);
Assert.Same(map, sameMap);
}
[Fact]
public void SetItemsTest()
{
var template = new Dictionary<string, int>
{
{ "Microsoft", 100 },
{ "Corporation", 50 },
};
var map = this.Empty<string, int>().SetItems(template);
Assert.Equal(2, map.Count);
var changes = new Dictionary<string, int>
{
{ "Microsoft", 150 },
{ "Dogs", 90 },
};
map = map.SetItems(changes);
Assert.Equal(3, map.Count);
Assert.Equal(150, map["Microsoft"]);
Assert.Equal(50, map["Corporation"]);
Assert.Equal(90, map["Dogs"]);
map = map.SetItems(
new[] {
new KeyValuePair<string, int>("Microsoft", 80),
new KeyValuePair<string, int>("Microsoft", 70),
});
Assert.Equal(3, map.Count);
Assert.Equal(70, map["Microsoft"]);
Assert.Equal(50, map["Corporation"]);
Assert.Equal(90, map["Dogs"]);
map = this.Empty<string, int>().SetItems(new[] { // use an array for code coverage
new KeyValuePair<string, int>("a", 1), new KeyValuePair<string, int>("b", 2),
new KeyValuePair<string, int>("a", 3),
});
Assert.Equal(2, map.Count);
Assert.Equal(3, map["a"]);
Assert.Equal(2, map["b"]);
}
[Fact]
public void ContainsKeyTest()
{
this.ContainsKeyTestHelper(Empty<int, GenericParameterHelper>(), 1, new GenericParameterHelper());
}
[Fact]
public void IndexGetNonExistingKeyThrowsTest()
{
Assert.Throws<KeyNotFoundException>(() => this.Empty<int, int>()[3]);
}
[Fact]
public void IndexGetTest()
{
var map = this.Empty<int, int>().Add(3, 5);
Assert.Equal(5, map[3]);
}
[Fact]
public void DictionaryRemoveThrowsTest()
{
IDictionary<int, int> map = this.Empty<int, int>().Add(5, 3).ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => map.Remove(5));
}
[Fact]
public void DictionaryAddThrowsTest()
{
IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => map.Add(5, 3));
}
[Fact]
public void DictionaryIndexSetThrowsTest()
{
IDictionary<int, int> map = this.Empty<int, int>().ToReadOnlyDictionary();
Assert.Throws<NotSupportedException>(() => map[3] = 5);
}
[ActiveIssue(780)]
[Fact]
public void EqualsTest()
{
Assert.False(Empty<int, int>().Equals(null));
Assert.False(Empty<int, int>().Equals("hi"));
Assert.True(Empty<int, int>().Equals(Empty<int, int>()));
Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 2)));
Assert.False(Empty<int, int>().Add(3, 2).Equals(Empty<int, int>().Add(3, 1)));
Assert.False(Empty<int, int>().Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
Assert.False(Empty<int, int>().Add(3, 1).Add(5, 1).Equals(Empty<int, int>().Add(3, 1)));
Assert.False(Empty<int, int>().Add(3, 1).Equals(Empty<int, int>().Add(3, 1).Add(5, 1)));
Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>()));
Assert.True(Empty<int, int>().Equals(Empty<int, int>().ToReadOnlyDictionary()));
Assert.True(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().ToReadOnlyDictionary()));
Assert.False(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary().Equals(Empty<int, int>()));
Assert.False(Empty<int, int>().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
Assert.False(Empty<int, int>().ToReadOnlyDictionary().Equals(Empty<int, int>().Add(3, 1).ToReadOnlyDictionary()));
}
/// <summary>
/// Verifies that the GetHashCode method returns the standard one.
/// </summary>
[Fact]
public void GetHashCodeTest()
{
var dictionary = Empty<string, int>();
Assert.Equal(EqualityComparer<object>.Default.GetHashCode(dictionary), dictionary.GetHashCode());
}
[Fact]
public void ICollectionOfKVMembers()
{
var dictionary = (ICollection<KeyValuePair<string, int>>)Empty<string, int>();
Assert.Throws<NotSupportedException>(() => dictionary.Add(new KeyValuePair<string, int>()));
Assert.Throws<NotSupportedException>(() => dictionary.Remove(new KeyValuePair<string, int>()));
Assert.Throws<NotSupportedException>(() => dictionary.Clear());
Assert.True(dictionary.IsReadOnly);
}
[Fact]
public void ICollectionMembers()
{
((ICollection)Empty<string, int>()).CopyTo(new object[0], 0);
var dictionary = (ICollection)Empty<string, int>().Add("a", 1);
Assert.True(dictionary.IsSynchronized);
Assert.NotNull(dictionary.SyncRoot);
Assert.Same(dictionary.SyncRoot, dictionary.SyncRoot);
var array = new object[2];
dictionary.CopyTo(array, 1);
Assert.Null(array[0]);
Assert.Equal(new DictionaryEntry("a", 1), (DictionaryEntry)array[1]);
}
[Fact]
public void IDictionaryOfKVMembers()
{
var dictionary = (IDictionary<string, int>)Empty<string, int>().Add("c", 3);
Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1));
Assert.Throws<NotSupportedException>(() => dictionary.Remove("a"));
Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2);
Assert.Throws<KeyNotFoundException>(() => dictionary["a"]);
Assert.Equal(3, dictionary["c"]);
}
[Fact]
public void IDictionaryMembers()
{
var dictionary = (IDictionary)Empty<string, int>().Add("c", 3);
Assert.Throws<NotSupportedException>(() => dictionary.Add("a", 1));
Assert.Throws<NotSupportedException>(() => dictionary.Remove("a"));
Assert.Throws<NotSupportedException>(() => dictionary["a"] = 2);
Assert.Throws<NotSupportedException>(() => dictionary.Clear());
Assert.False(dictionary.Contains("a"));
Assert.True(dictionary.Contains("c"));
Assert.Throws<KeyNotFoundException>(() => dictionary["a"]);
Assert.Equal(3, dictionary["c"]);
Assert.True(dictionary.IsFixedSize);
Assert.True(dictionary.IsReadOnly);
Assert.Equal(new[] { "c" }, dictionary.Keys.Cast<string>().ToArray());
Assert.Equal(new[] { 3 }, dictionary.Values.Cast<int>().ToArray());
}
[Fact]
public void IDictionaryEnumerator()
{
var dictionary = (IDictionary)Empty<string, int>().Add("a", 1);
var enumerator = dictionary.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Entry, enumerator.Current);
Assert.Equal(enumerator.Key, enumerator.Entry.Key);
Assert.Equal(enumerator.Value, enumerator.Entry.Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.True(enumerator.MoveNext());
Assert.Equal(enumerator.Key, ((DictionaryEntry)enumerator.Current).Key);
Assert.Equal(enumerator.Value, ((DictionaryEntry)enumerator.Current).Value);
Assert.Equal("a", enumerator.Key);
Assert.Equal(1, enumerator.Value);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.False(enumerator.MoveNext());
}
[Fact]
public void TryGetKey()
{
var dictionary = Empty<int>(StringComparer.OrdinalIgnoreCase)
.Add("a", 1);
string actualKey;
Assert.True(dictionary.TryGetKey("a", out actualKey));
Assert.Equal("a", actualKey);
Assert.True(dictionary.TryGetKey("A", out actualKey));
Assert.Equal("a", actualKey);
Assert.False(dictionary.TryGetKey("b", out actualKey));
Assert.Equal("b", actualKey);
}
protected void EmptyTestHelper<K, V>(IImmutableDictionary<K, V> empty, K someKey)
{
Assert.Same(empty, empty.Clear());
Assert.Equal(0, empty.Count);
Assert.Equal(0, empty.Count());
Assert.Equal(0, empty.Keys.Count());
Assert.Equal(0, empty.Values.Count());
Assert.Same(EqualityComparer<V>.Default, GetValueComparer(empty));
Assert.False(empty.ContainsKey(someKey));
Assert.False(empty.Contains(new KeyValuePair<K, V>(someKey, default(V))));
Assert.Equal(default(V), empty.GetValueOrDefault(someKey));
V value;
Assert.False(empty.TryGetValue(someKey, out value));
Assert.Equal(default(V), value);
}
private IImmutableDictionary<TKey, TValue> AddTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) where TKey : IComparable<TKey>
{
Contract.Requires(map != null);
Contract.Requires(key != null);
IImmutableDictionary<TKey, TValue> addedMap = map.Add(key, value);
Assert.NotSame(map, addedMap);
////Assert.Equal(map.Count + 1, addedMap.Count);
Assert.False(map.ContainsKey(key));
Assert.True(addedMap.ContainsKey(key));
AssertAreSame(value, addedMap.GetValueOrDefault(key));
this.VerifyAvlTreeState(addedMap);
return addedMap;
}
protected void AddAscendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
{
Contract.Requires(map != null);
for (int i = 0; i < 10; i++)
{
map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
}
Assert.Equal(10, map.Count);
for (int i = 0; i < 10; i++)
{
Assert.True(map.ContainsKey(i));
}
}
protected void AddDescendingTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
{
for (int i = 10; i > 0; i--)
{
map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
}
Assert.Equal(10, map.Count);
for (int i = 10; i > 0; i--)
{
Assert.True(map.ContainsKey(i));
}
}
protected void AddRemoveRandomDataTestHelper(IImmutableDictionary<double, GenericParameterHelper> map)
{
Contract.Requires(map != null);
double[] inputs = GenerateDummyFillData();
for (int i = 0; i < inputs.Length; i++)
{
map = this.AddTestHelper(map, inputs[i], new GenericParameterHelper());
}
Assert.Equal(inputs.Length, map.Count);
for (int i = 0; i < inputs.Length; i++)
{
Assert.True(map.ContainsKey(inputs[i]));
}
for (int i = 0; i < inputs.Length; i++)
{
map = map.Remove(inputs[i]);
this.VerifyAvlTreeState(map);
}
Assert.Equal(0, map.Count);
}
protected void AddRemoveEnumerableTestHelper(IImmutableDictionary<int, int> empty)
{
Contract.Requires(empty != null);
Assert.Same(empty, empty.RemoveRange(Enumerable.Empty<int>()));
Assert.Same(empty, empty.AddRange(Enumerable.Empty<KeyValuePair<int, int>>()));
var list = new List<KeyValuePair<int, int>> { new KeyValuePair<int, int>(3, 5), new KeyValuePair<int, int>(8, 10) };
var nonEmpty = empty.AddRange(list);
this.VerifyAvlTreeState(nonEmpty);
var halfRemoved = nonEmpty.RemoveRange(Enumerable.Range(1, 5));
Assert.Equal(1, halfRemoved.Count);
Assert.True(halfRemoved.ContainsKey(8));
this.VerifyAvlTreeState(halfRemoved);
}
protected void AddExistingKeySameValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2)
{
Contract.Requires(map != null);
Contract.Requires(key != null);
Contract.Requires(GetValueComparer(map).Equals(value1, value2));
map = map.Add(key, value1);
Assert.Same(map, map.Add(key, value2));
Assert.Same(map, map.AddRange(new[] { new KeyValuePair<TKey, TValue>(key, value2) }));
}
/// <summary>
/// Verifies that adding a key-value pair where the key already is in the map but with a different value throws.
/// </summary>
/// <typeparam name="TKey">The type of key in the map.</typeparam>
/// <typeparam name="TValue">The type of value in the map.</typeparam>
/// <param name="map">The map to manipulate.</param>
/// <param name="key">The key to add.</param>
/// <param name="value1">The first value to add.</param>
/// <param name="value2">The second value to add.</param>
/// <remarks>
/// Adding a key-value pair to a map where that key already exists, but with a different value, cannot fit the
/// semantic of "adding", either by just returning or mutating the value on the existing key. Throwing is the only reasonable response.
/// </remarks>
protected void AddExistingKeyDifferentValueTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value1, TValue value2)
{
Contract.Requires(map != null);
Contract.Requires(key != null);
Contract.Requires(!GetValueComparer(map).Equals(value1, value2));
var map1 = map.Add(key, value1);
var map2 = map.Add(key, value2);
Assert.Throws<ArgumentException>(() => map1.Add(key, value2));
Assert.Throws<ArgumentException>(() => map2.Add(key, value1));
}
protected void ContainsKeyTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.ContainsKey(key));
Assert.True(map.Add(key, value).ContainsKey(key));
}
protected void ContainsTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key, TValue value)
{
Assert.False(map.Contains(new KeyValuePair<TKey, TValue>(key, value)));
Assert.False(map.Contains(key, value));
Assert.True(map.Add(key, value).Contains(new KeyValuePair<TKey, TValue>(key, value)));
Assert.True(map.Add(key, value).Contains(key, value));
}
protected void RemoveTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
{
// no-op remove
Assert.Same(map, map.Remove(key));
Assert.Same(map, map.RemoveRange(Enumerable.Empty<TKey>()));
// substantial remove
var addedMap = map.Add(key, default(TValue));
var removedMap = addedMap.Remove(key);
Assert.NotSame(addedMap, removedMap);
Assert.False(removedMap.ContainsKey(key));
}
protected void KeysTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
{
Assert.Equal(0, map.Keys.Count());
Assert.Equal(0, map.ToReadOnlyDictionary().Keys.Count());
var nonEmpty = map.Add(key, default(TValue));
Assert.Equal(1, nonEmpty.Keys.Count());
Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Keys.Count());
KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Keys, key);
}
protected void ValuesTestHelper<TKey, TValue>(IImmutableDictionary<TKey, TValue> map, TKey key)
{
Assert.Equal(0, map.Values.Count());
Assert.Equal(0, map.ToReadOnlyDictionary().Values.Count());
var nonEmpty = map.Add(key, default(TValue));
Assert.Equal(1, nonEmpty.Values.Count());
Assert.Equal(1, nonEmpty.ToReadOnlyDictionary().Values.Count());
KeysOrValuesTestHelper(((IDictionary<TKey, TValue>)nonEmpty).Values, default(TValue));
}
protected void EnumeratorTestHelper(IImmutableDictionary<int, GenericParameterHelper> map)
{
for (int i = 0; i < 10; i++)
{
map = this.AddTestHelper(map, i, new GenericParameterHelper(i));
}
int j = 0;
foreach (KeyValuePair<int, GenericParameterHelper> pair in map)
{
Assert.Equal(j, pair.Key);
Assert.Equal(j, pair.Value.Data);
j++;
}
var list = map.ToList();
Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(list, ImmutableSetTest.ToListNonGeneric<KeyValuePair<int, GenericParameterHelper>>(map));
// Apply some less common uses to the enumerator to test its metal.
using (var enumerator = map.GetEnumerator())
{
enumerator.Reset(); // reset isn't usually called before MoveNext
ManuallyEnumerateTest(list, enumerator);
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
// this time only partially enumerate
enumerator.Reset();
enumerator.MoveNext();
enumerator.Reset();
ManuallyEnumerateTest(list, enumerator);
}
var manualEnum = map.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
while (manualEnum.MoveNext()) { }
Assert.False(manualEnum.MoveNext());
Assert.Throws<InvalidOperationException>(() => manualEnum.Current);
}
protected abstract IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>();
protected abstract IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer);
protected abstract IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
internal abstract IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary);
private static void KeysOrValuesTestHelper<T>(ICollection<T> collection, T containedValue)
{
Requires.NotNull(collection, "collection");
Assert.True(collection.Contains(containedValue));
Assert.Throws<NotSupportedException>(() => collection.Add(default(T)));
Assert.Throws<NotSupportedException>(() => collection.Clear());
var nonGeneric = (ICollection)collection;
Assert.NotNull(nonGeneric.SyncRoot);
Assert.Same(nonGeneric.SyncRoot, nonGeneric.SyncRoot);
Assert.True(nonGeneric.IsSynchronized);
Assert.True(collection.IsReadOnly);
Assert.Throws<ArgumentNullException>(() => nonGeneric.CopyTo(null, 0));
var array = new T[collection.Count + 1];
nonGeneric.CopyTo(array, 1);
Assert.Equal(default(T), array[0]);
Assert.Equal(array.Skip(1), nonGeneric.Cast<T>().ToArray());
}
private void VerifyAvlTreeState<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
var rootNode = this.GetRootNode(dictionary);
rootNode.VerifyBalanced();
rootNode.VerifyHeightIsWithinTolerance(dictionary.Count);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
namespace System.Xml
{
internal partial class XmlWellFormedWriter : XmlWriter
{
//
// Private types
//
class NamespaceResolverProxy : IXmlNamespaceResolver
{
XmlWellFormedWriter wfWriter;
internal NamespaceResolverProxy(XmlWellFormedWriter wfWriter)
{
this.wfWriter = wfWriter;
}
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
throw NotImplemented.ByDesign;
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return wfWriter.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return wfWriter.LookupPrefix(namespaceName);
}
}
partial struct ElementScope
{
internal int prevNSTop;
internal string prefix;
internal string localName;
internal string namespaceUri;
internal XmlSpace xmlSpace;
internal string xmlLang;
internal void Set(string prefix, string localName, string namespaceUri, int prevNSTop)
{
this.prevNSTop = prevNSTop;
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.xmlSpace = (System.Xml.XmlSpace)(int)-1;
this.xmlLang = null;
}
internal void WriteEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteEndElement(prefix, localName, namespaceUri);
}
internal void WriteFullEndElement(XmlRawWriter rawWriter)
{
rawWriter.WriteFullEndElement(prefix, localName, namespaceUri);
}
}
enum NamespaceKind
{
Written,
NeedToWrite,
Implied,
Special,
}
partial struct Namespace
{
internal string prefix;
internal string namespaceUri;
internal NamespaceKind kind;
internal int prevNsIndex;
internal void Set(string prefix, string namespaceUri, NamespaceKind kind)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.kind = kind;
this.prevNsIndex = -1;
}
internal void WriteDecl(XmlWriter writer, XmlRawWriter rawWriter)
{
Debug.Assert(kind == NamespaceKind.NeedToWrite);
if (null != rawWriter)
{
rawWriter.WriteNamespaceDeclaration(prefix, namespaceUri);
}
else
{
if (prefix.Length == 0)
{
writer.WriteStartAttribute(string.Empty, XmlConst.NsXmlNs, XmlConst.ReservedNsXmlNs);
}
else
{
writer.WriteStartAttribute(XmlConst.NsXmlNs, prefix, XmlConst.ReservedNsXmlNs);
}
writer.WriteString(namespaceUri);
writer.WriteEndAttribute();
}
}
}
struct AttrName
{
internal string prefix;
internal string namespaceUri;
internal string localName;
internal int prev;
internal void Set(string prefix, string localName, string namespaceUri)
{
this.prefix = prefix;
this.namespaceUri = namespaceUri;
this.localName = localName;
this.prev = 0;
}
internal bool IsDuplicate(string prefix, string localName, string namespaceUri)
{
return ((this.localName == localName)
&& ((this.prefix == prefix) || (this.namespaceUri == namespaceUri)));
}
}
enum SpecialAttribute
{
No = 0,
DefaultXmlns,
PrefixedXmlns,
XmlSpace,
XmlLang
}
partial class AttributeValueCache
{
enum ItemType
{
EntityRef,
CharEntity,
SurrogateCharEntity,
Whitespace,
String,
StringChars,
Raw,
RawChars,
ValueString,
}
class Item
{
internal ItemType type;
internal object data;
internal Item() { }
internal void Set(ItemType type, object data)
{
this.type = type;
this.data = data;
}
}
class BufferChunk
{
internal char[] buffer;
internal int index;
internal int count;
internal BufferChunk(char[] buffer, int index, int count)
{
this.buffer = buffer;
this.index = index;
this.count = count;
}
}
StringBuilder stringValue = new StringBuilder();
string singleStringValue; // special-case for a single WriteString call
Item[] items;
int firstItem;
int lastItem = -1;
internal string StringValue
{
get
{
if (singleStringValue != null)
{
return singleStringValue;
}
else
{
return stringValue.ToString();
}
}
}
internal void WriteEntityRef(string name)
{
if (singleStringValue != null)
{
StartComplexValue();
}
switch (name)
{
case "lt":
stringValue.Append('<');
break;
case "gt":
stringValue.Append('>');
break;
case "quot":
stringValue.Append('"');
break;
case "apos":
stringValue.Append('\'');
break;
case "amp":
stringValue.Append('&');
break;
default:
stringValue.Append('&');
stringValue.Append(name);
stringValue.Append(';');
break;
}
AddItem(ItemType.EntityRef, name);
}
internal void WriteCharEntity(char ch)
{
if (singleStringValue != null)
{
StartComplexValue();
}
stringValue.Append(ch);
AddItem(ItemType.CharEntity, ch);
}
internal void WriteSurrogateCharEntity(char lowChar, char highChar)
{
if (singleStringValue != null)
{
StartComplexValue();
}
stringValue.Append(highChar);
stringValue.Append(lowChar);
AddItem(ItemType.SurrogateCharEntity, new char[] { lowChar, highChar });
}
internal void WriteWhitespace(string ws)
{
if (singleStringValue != null)
{
StartComplexValue();
}
stringValue.Append(ws);
AddItem(ItemType.Whitespace, ws);
}
internal void WriteString(string text)
{
if (singleStringValue != null)
{
StartComplexValue();
}
else
{
// special-case for a single WriteString
if (lastItem == -1)
{
singleStringValue = text;
return;
}
}
stringValue.Append(text);
AddItem(ItemType.String, text);
}
internal void WriteChars(char[] buffer, int index, int count)
{
if (singleStringValue != null)
{
StartComplexValue();
}
stringValue.Append(buffer, index, count);
AddItem(ItemType.StringChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(char[] buffer, int index, int count)
{
if (singleStringValue != null)
{
StartComplexValue();
}
stringValue.Append(buffer, index, count);
AddItem(ItemType.RawChars, new BufferChunk(buffer, index, count));
}
internal void WriteRaw(string data)
{
if (singleStringValue != null)
{
StartComplexValue();
}
stringValue.Append(data);
AddItem(ItemType.Raw, data);
}
internal void WriteValue(string value)
{
if (singleStringValue != null)
{
StartComplexValue();
}
stringValue.Append(value);
AddItem(ItemType.ValueString, value);
}
internal void Replay(XmlWriter writer)
{
if (singleStringValue != null)
{
writer.WriteString(singleStringValue);
return;
}
BufferChunk bufChunk;
for (int i = firstItem; i <= lastItem; i++)
{
Item item = items[i];
switch (item.type)
{
case ItemType.EntityRef:
writer.WriteEntityRef((string)item.data);
break;
case ItemType.CharEntity:
writer.WriteCharEntity((char)item.data);
break;
case ItemType.SurrogateCharEntity:
char[] chars = (char[])item.data;
writer.WriteSurrogateCharEntity(chars[0], chars[1]);
break;
case ItemType.Whitespace:
writer.WriteWhitespace((string)item.data);
break;
case ItemType.String:
writer.WriteString((string)item.data);
break;
case ItemType.StringChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.Raw:
writer.WriteRaw((string)item.data);
break;
case ItemType.RawChars:
bufChunk = (BufferChunk)item.data;
writer.WriteChars(bufChunk.buffer, bufChunk.index, bufChunk.count);
break;
case ItemType.ValueString:
writer.WriteValue((string)item.data);
break;
default:
Debug.Assert(false, "Unexpected ItemType value.");
break;
}
}
}
// This method trims whitespaces from the beginning and the end of the string and cached writer events
internal void Trim()
{
// if only one string value -> trim the write spaces directly
if (singleStringValue != null)
{
singleStringValue = XmlConvertEx.TrimString(singleStringValue);
return;
}
// trim the string in StringBuilder
string valBefore = stringValue.ToString();
string valAfter = XmlConvertEx.TrimString(valBefore);
if (valBefore != valAfter)
{
stringValue = new StringBuilder(valAfter);
}
// trim the beginning of the recorded writer events
XmlCharType xmlCharType = XmlCharType.Instance;
int i = firstItem;
while (i == firstItem && i <= lastItem)
{
Item item = items[i];
switch (item.type)
{
case ItemType.Whitespace:
firstItem++;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvertEx.TrimStringStart((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the firstItem index to exclude it from the Replay
firstItem++;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
int endIndex = bufChunk.index + bufChunk.count;
while (bufChunk.index < endIndex && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index]))
{
bufChunk.index++;
bufChunk.count--;
}
if (bufChunk.index == endIndex)
{
// no characters left -> move the firstItem index to exclude it from the Replay
firstItem++;
}
break;
}
i++;
}
// trim the end of the recorded writer events
i = lastItem;
while (i == lastItem && i >= firstItem)
{
Item item = items[i];
switch (item.type)
{
case ItemType.Whitespace:
lastItem--;
break;
case ItemType.String:
case ItemType.Raw:
case ItemType.ValueString:
item.data = XmlConvertEx.TrimStringEnd((string)item.data);
if (((string)item.data).Length == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
lastItem--;
}
break;
case ItemType.StringChars:
case ItemType.RawChars:
BufferChunk bufChunk = (BufferChunk)item.data;
while (bufChunk.count > 0 && xmlCharType.IsWhiteSpace(bufChunk.buffer[bufChunk.index + bufChunk.count - 1]))
{
bufChunk.count--;
}
if (bufChunk.count == 0)
{
// no characters left -> move the lastItem index to exclude it from the Replay
lastItem--;
}
break;
}
i--;
}
}
internal void Clear()
{
singleStringValue = null;
lastItem = -1;
firstItem = 0;
stringValue.Length = 0;
}
private void StartComplexValue()
{
Debug.Assert(singleStringValue != null);
Debug.Assert(lastItem == -1);
stringValue.Append(singleStringValue);
AddItem(ItemType.String, singleStringValue);
singleStringValue = null;
}
void AddItem(ItemType type, object data)
{
int newItemIndex = lastItem + 1;
if (items == null)
{
items = new Item[4];
}
else if (items.Length == newItemIndex)
{
Item[] newItems = new Item[newItemIndex * 2];
Array.Copy(items, newItems, newItemIndex);
items = newItems;
}
if (items[newItemIndex] == null)
{
items[newItemIndex] = new Item();
}
items[newItemIndex].Set(type, data);
lastItem = newItemIndex;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Internal.Cryptography.Pal.Native;
using static Interop.Crypt32;
namespace Internal.Cryptography.Pal
{
internal partial class FindPal : IFindPal
{
private readonly StorePal _storePal;
private readonly X509Certificate2Collection _copyTo;
private readonly bool _validOnly;
internal FindPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly)
{
_storePal = (StorePal)StorePal.LinkFromCertificateCollection(findFrom);
_copyTo = copyTo;
_validOnly = validOnly;
}
internal static IFindPal OpenPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly)
{
return new FindPal(findFrom, copyTo, validOnly);
}
public string NormalizeOid(string maybeOid, OidGroup expectedGroup)
{
string oidValue = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_NAME_KEY, maybeOid, expectedGroup, fallBackToAllGroups: true).OID;
if (oidValue == null)
{
oidValue = maybeOid;
ValidateOidValue(oidValue);
}
return oidValue;
}
public unsafe void FindByThumbprint(byte[] thumbPrint)
{
fixed (byte* pThumbPrint = thumbPrint)
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(thumbPrint.Length, pThumbPrint);
FindCore(CertFindType.CERT_FIND_HASH, &blob);
}
}
public unsafe void FindBySubjectName(string subjectName)
{
fixed (char* pSubjectName = subjectName)
{
FindCore(CertFindType.CERT_FIND_SUBJECT_STR, pSubjectName);
}
}
public void FindBySubjectDistinguishedName(string subjectDistinguishedName)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
string actual = GetCertNameInfo(pCertContext, CertNameType.CERT_NAME_RDN_TYPE, CertNameFlags.None);
return subjectDistinguishedName.Equals(actual, StringComparison.OrdinalIgnoreCase);
});
}
public unsafe void FindByIssuerName(string issuerName)
{
fixed (char* pIssuerName = issuerName)
{
FindCore(CertFindType.CERT_FIND_ISSUER_STR, pIssuerName);
}
}
public void FindByIssuerDistinguishedName(string issuerDistinguishedName)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
string actual = GetCertNameInfo(pCertContext, CertNameType.CERT_NAME_RDN_TYPE, CertNameFlags.CERT_NAME_ISSUER_FLAG);
return issuerDistinguishedName.Equals(actual, StringComparison.OrdinalIgnoreCase);
});
}
public unsafe void FindBySerialNumber(BigInteger hexValue, BigInteger decimalValue)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
byte[] actual = pCertContext.CertContext->pCertInfo->SerialNumber.ToByteArray();
GC.KeepAlive(pCertContext);
// Convert to BigInteger as the comparison must not fail due to spurious leading zeros
BigInteger actualAsBigInteger = PositiveBigIntegerFromByteArray(actual);
return hexValue.Equals(actualAsBigInteger) || decimalValue.Equals(actualAsBigInteger);
});
}
public void FindByTimeValid(DateTime dateTime)
{
FindByTime(dateTime, 0);
}
public void FindByTimeNotYetValid(DateTime dateTime)
{
FindByTime(dateTime, -1);
}
public void FindByTimeExpired(DateTime dateTime)
{
FindByTime(dateTime, 1);
}
private unsafe void FindByTime(DateTime dateTime, int compareResult)
{
FILETIME fileTime = FILETIME.FromDateTime(dateTime);
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
int comparison = Interop.crypt32.CertVerifyTimeValidity(ref fileTime,
pCertContext.CertContext->pCertInfo);
GC.KeepAlive(pCertContext);
return comparison == compareResult;
});
}
public unsafe void FindByTemplateName(string templateName)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
// The template name can have 2 different formats: V1 format (<= Win2K) is just a string
// V2 format (XP only) can be a friendly name or an OID.
// An example of Template Name can be "ClientAuth".
bool foundMatch = false;
CERT_INFO* pCertInfo = pCertContext.CertContext->pCertInfo;
{
CERT_EXTENSION* pV1Template = Interop.crypt32.CertFindExtension(Oids.EnrollCertTypeExtension,
pCertInfo->cExtension, pCertInfo->rgExtension);
if (pV1Template != null)
{
byte[] extensionRawData = pV1Template->Value.ToByteArray();
if (!extensionRawData.DecodeObjectNoThrow(
CryptDecodeObjectStructType.X509_UNICODE_ANY_STRING,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_NAME_VALUE));
CERT_NAME_VALUE* pNameValue = (CERT_NAME_VALUE*)pvDecoded;
string actual = Marshal.PtrToStringUni(new IntPtr(pNameValue->Value.pbData));
if (templateName.Equals(actual, StringComparison.OrdinalIgnoreCase))
foundMatch = true;
}))
{
return false;
}
}
}
if (!foundMatch)
{
CERT_EXTENSION* pV2Template = Interop.crypt32.CertFindExtension(Oids.CertificateTemplate,
pCertInfo->cExtension, pCertInfo->rgExtension);
if (pV2Template != null)
{
byte[] extensionRawData = pV2Template->Value.ToByteArray();
if (!extensionRawData.DecodeObjectNoThrow(
CryptDecodeObjectStructType.X509_CERTIFICATE_TEMPLATE,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_TEMPLATE_EXT));
CERT_TEMPLATE_EXT* pTemplateExt = (CERT_TEMPLATE_EXT*)pvDecoded;
string actual = Marshal.PtrToStringAnsi(pTemplateExt->pszObjId);
string expectedOidValue =
Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_NAME_KEY, templateName,
OidGroup.Template, fallBackToAllGroups: true).OID;
if (expectedOidValue == null)
expectedOidValue = templateName;
if (expectedOidValue.Equals(actual, StringComparison.OrdinalIgnoreCase))
foundMatch = true;
}))
{
return false;
}
}
}
GC.KeepAlive(pCertContext);
return foundMatch;
});
}
public unsafe void FindByApplicationPolicy(string oidValue)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
int numOids;
int cbData = 0;
if (!Interop.crypt32.CertGetValidUsages(1, ref pCertContext, out numOids, null, ref cbData))
return false;
// -1 means the certificate is good for all usages.
if (numOids == -1)
return true;
fixed (byte* pOidsPointer = new byte[cbData])
{
if (!Interop.crypt32.CertGetValidUsages(1, ref pCertContext, out numOids, pOidsPointer, ref cbData))
return false;
IntPtr* pOids = (IntPtr*)pOidsPointer;
for (int i = 0; i < numOids; i++)
{
string actual = Marshal.PtrToStringAnsi(pOids[i]);
if (oidValue.Equals(actual, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
});
}
public unsafe void FindByCertificatePolicy(string oidValue)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
CERT_INFO* pCertInfo = pCertContext.CertContext->pCertInfo;
CERT_EXTENSION* pCertExtension = Interop.crypt32.CertFindExtension(Oids.CertPolicies,
pCertInfo->cExtension, pCertInfo->rgExtension);
if (pCertExtension == null)
return false;
bool foundMatch = false;
byte[] extensionRawData = pCertExtension->Value.ToByteArray();
if (!extensionRawData.DecodeObjectNoThrow(
CryptDecodeObjectStructType.X509_CERT_POLICIES,
delegate (void* pvDecoded, int cbDecoded)
{
Debug.Assert(cbDecoded >= sizeof(CERT_POLICIES_INFO));
CERT_POLICIES_INFO* pCertPoliciesInfo = (CERT_POLICIES_INFO*)pvDecoded;
for (int i = 0; i < pCertPoliciesInfo->cPolicyInfo; i++)
{
CERT_POLICY_INFO* pCertPolicyInfo = &(pCertPoliciesInfo->rgPolicyInfo[i]);
string actual = Marshal.PtrToStringAnsi(pCertPolicyInfo->pszPolicyIdentifier);
if (oidValue.Equals(actual, StringComparison.OrdinalIgnoreCase))
{
foundMatch = true;
break;
}
}
}
))
{
return false;
}
GC.KeepAlive(pCertContext);
return foundMatch;
});
}
public unsafe void FindByExtension(string oidValue)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
CERT_INFO* pCertInfo = pCertContext.CertContext->pCertInfo;
CERT_EXTENSION* pCertExtension = Interop.crypt32.CertFindExtension(oidValue, pCertInfo->cExtension, pCertInfo->rgExtension);
GC.KeepAlive(pCertContext);
return pCertExtension != null;
});
}
public unsafe void FindByKeyUsage(X509KeyUsageFlags keyUsage)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
CERT_INFO* pCertInfo = pCertContext.CertContext->pCertInfo;
X509KeyUsageFlags actual;
if (!Interop.crypt32.CertGetIntendedKeyUsage(CertEncodingType.All, pCertInfo, out actual, sizeof(X509KeyUsageFlags)))
return true; // no key usage means it is valid for all key usages.
GC.KeepAlive(pCertContext);
return (actual & keyUsage) == keyUsage;
});
}
public void FindBySubjectKeyIdentifier(byte[] keyIdentifier)
{
FindCore(
delegate (SafeCertContextHandle pCertContext)
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_IDENTIFIER_PROP_ID, null, ref cbData))
return false;
byte[] actual = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(pCertContext, CertContextPropId.CERT_KEY_IDENTIFIER_PROP_ID, actual, ref cbData))
return false;
return keyIdentifier.ContentsEqual(actual);
});
}
public void Dispose()
{
_storePal.Dispose();
}
private unsafe void FindCore(Func<SafeCertContextHandle, bool> filter)
{
FindCore(CertFindType.CERT_FIND_ANY, null, filter);
}
private unsafe void FindCore(CertFindType dwFindType, void* pvFindPara, Func<SafeCertContextHandle, bool> filter = null)
{
SafeCertStoreHandle findResults = Interop.crypt32.CertOpenStore(
CertStoreProvider.CERT_STORE_PROV_MEMORY,
CertEncodingType.All,
IntPtr.Zero,
CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG | CertStoreFlags.CERT_STORE_CREATE_NEW_FLAG,
null);
if (findResults.IsInvalid)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();
SafeCertContextHandle pCertContext = null;
while (Interop.crypt32.CertFindCertificateInStore(_storePal.SafeCertStoreHandle, dwFindType, pvFindPara, ref pCertContext))
{
if (filter != null && !filter(pCertContext))
continue;
if (_validOnly)
{
if (!VerifyCertificateIgnoringErrors(pCertContext))
continue;
}
if (!Interop.crypt32.CertAddCertificateLinkToStore(findResults, pCertContext, CertStoreAddDisposition.CERT_STORE_ADD_ALWAYS, IntPtr.Zero))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
using (StorePal resultsStore = new StorePal(findResults))
{
resultsStore.CopyTo(_copyTo);
}
}
private static bool VerifyCertificateIgnoringErrors(SafeCertContextHandle pCertContext)
{
// This needs to be kept in sync with IsCertValid in the
// Unix/OpenSSL PAL version (and potentially any other PALs that come about)
ChainPal chainPal = ChainPal.BuildChain(
false,
CertificatePal.FromHandle(pCertContext.DangerousGetHandle()),
null, //extraStore
null, //applicationPolicy
null, //certificatePolicy
X509RevocationMode.NoCheck,
X509RevocationFlag.ExcludeRoot,
null,
X509ChainTrustMode.System,
DateTime.Now,
new TimeSpan(0, 0, 0));
if (chainPal == null)
return false;
using (chainPal)
{
Exception verificationException;
bool? verified = chainPal.Verify(X509VerificationFlags.NoFlag, out verificationException);
if (!verified.GetValueOrDefault())
return false;
}
return true;
}
private static unsafe string GetCertNameInfo(SafeCertContextHandle pCertContext, CertNameType dwNameType, CertNameFlags dwNameFlags)
{
Debug.Assert(dwNameType != CertNameType.CERT_NAME_ATTR_TYPE);
return Interop.crypt32.CertGetNameString(
pCertContext,
dwNameType,
dwNameFlags,
CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG);
}
}
}
| |
namespace java.util
{
[global::MonoJavaBridge.JavaClass()]
public partial class Date : java.lang.Object, java.io.Serializable, java.lang.Cloneable, java.lang.Comparable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Date()
{
InitJNI();
}
protected Date(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _equals15358;
public override bool equals(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Date._equals15358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._equals15358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _toString15359;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Date._toString15359)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._toString15359)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _hashCode15360;
public override int hashCode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._hashCode15360);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._hashCode15360);
}
internal static global::MonoJavaBridge.MethodId _clone15361;
public virtual new global::java.lang.Object clone()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Date._clone15361)) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._clone15361)) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _compareTo15362;
public virtual int compareTo(java.util.Date arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._compareTo15362, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._compareTo15362, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _compareTo15363;
public virtual int compareTo(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._compareTo15363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._compareTo15363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _after15364;
public virtual bool after(java.util.Date arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Date._after15364, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._after15364, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _before15365;
public virtual bool before(java.util.Date arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::java.util.Date._before15365, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._before15365, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _parse15366;
public static long parse(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticLongMethod(java.util.Date.staticClass, global::java.util.Date._parse15366, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setTime15367;
public virtual void setTime(long arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Date._setTime15367, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._setTime15367, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getTime15368;
public virtual long getTime()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::java.util.Date._getTime15368);
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getTime15368);
}
internal static global::MonoJavaBridge.MethodId _getYear15369;
public virtual int getYear()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getYear15369);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getYear15369);
}
internal static global::MonoJavaBridge.MethodId _getMonth15370;
public virtual int getMonth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getMonth15370);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getMonth15370);
}
internal static global::MonoJavaBridge.MethodId _getDate15371;
public virtual int getDate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getDate15371);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getDate15371);
}
internal static global::MonoJavaBridge.MethodId _getHours15372;
public virtual int getHours()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getHours15372);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getHours15372);
}
internal static global::MonoJavaBridge.MethodId _getMinutes15373;
public virtual int getMinutes()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getMinutes15373);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getMinutes15373);
}
internal static global::MonoJavaBridge.MethodId _getSeconds15374;
public virtual int getSeconds()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getSeconds15374);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getSeconds15374);
}
internal static global::MonoJavaBridge.MethodId _UTC15375;
public static long UTC(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticLongMethod(java.util.Date.staticClass, global::java.util.Date._UTC15375, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
internal static global::MonoJavaBridge.MethodId _setDate15376;
public virtual void setDate(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Date._setDate15376, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._setDate15376, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setMonth15377;
public virtual void setMonth(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Date._setMonth15377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._setMonth15377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setHours15378;
public virtual void setHours(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Date._setHours15378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._setHours15378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setMinutes15379;
public virtual void setMinutes(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Date._setMinutes15379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._setMinutes15379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setSeconds15380;
public virtual void setSeconds(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Date._setSeconds15380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._setSeconds15380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setYear15381;
public virtual void setYear(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::java.util.Date._setYear15381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._setYear15381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDay15382;
public virtual int getDay()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getDay15382);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getDay15382);
}
internal static global::MonoJavaBridge.MethodId _toLocaleString15383;
public virtual global::java.lang.String toLocaleString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Date._toLocaleString15383)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._toLocaleString15383)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _toGMTString15384;
public virtual global::java.lang.String toGMTString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.util.Date._toGMTString15384)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._toGMTString15384)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getTimezoneOffset15385;
public virtual int getTimezoneOffset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::java.util.Date._getTimezoneOffset15385);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.util.Date.staticClass, global::java.util.Date._getTimezoneOffset15385);
}
internal static global::MonoJavaBridge.MethodId _Date15386;
public Date() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Date.staticClass, global::java.util.Date._Date15386);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Date15387;
public Date(long arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Date.staticClass, global::java.util.Date._Date15387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Date15388;
public Date(int arg0, int arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Date.staticClass, global::java.util.Date._Date15388, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Date15389;
public Date(int arg0, int arg1, int arg2, int arg3, int arg4) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Date.staticClass, global::java.util.Date._Date15389, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Date15390;
public Date(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Date.staticClass, global::java.util.Date._Date15390, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Date15391;
public Date(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.util.Date.staticClass, global::java.util.Date._Date15391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.util.Date.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/Date"));
global::java.util.Date._equals15358 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "equals", "(Ljava/lang/Object;)Z");
global::java.util.Date._toString15359 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "toString", "()Ljava/lang/String;");
global::java.util.Date._hashCode15360 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "hashCode", "()I");
global::java.util.Date._clone15361 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "clone", "()Ljava/lang/Object;");
global::java.util.Date._compareTo15362 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "compareTo", "(Ljava/util/Date;)I");
global::java.util.Date._compareTo15363 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "compareTo", "(Ljava/lang/Object;)I");
global::java.util.Date._after15364 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "after", "(Ljava/util/Date;)Z");
global::java.util.Date._before15365 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "before", "(Ljava/util/Date;)Z");
global::java.util.Date._parse15366 = @__env.GetStaticMethodIDNoThrow(global::java.util.Date.staticClass, "parse", "(Ljava/lang/String;)J");
global::java.util.Date._setTime15367 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "setTime", "(J)V");
global::java.util.Date._getTime15368 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getTime", "()J");
global::java.util.Date._getYear15369 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getYear", "()I");
global::java.util.Date._getMonth15370 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getMonth", "()I");
global::java.util.Date._getDate15371 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getDate", "()I");
global::java.util.Date._getHours15372 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getHours", "()I");
global::java.util.Date._getMinutes15373 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getMinutes", "()I");
global::java.util.Date._getSeconds15374 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getSeconds", "()I");
global::java.util.Date._UTC15375 = @__env.GetStaticMethodIDNoThrow(global::java.util.Date.staticClass, "UTC", "(IIIIII)J");
global::java.util.Date._setDate15376 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "setDate", "(I)V");
global::java.util.Date._setMonth15377 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "setMonth", "(I)V");
global::java.util.Date._setHours15378 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "setHours", "(I)V");
global::java.util.Date._setMinutes15379 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "setMinutes", "(I)V");
global::java.util.Date._setSeconds15380 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "setSeconds", "(I)V");
global::java.util.Date._setYear15381 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "setYear", "(I)V");
global::java.util.Date._getDay15382 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getDay", "()I");
global::java.util.Date._toLocaleString15383 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "toLocaleString", "()Ljava/lang/String;");
global::java.util.Date._toGMTString15384 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "toGMTString", "()Ljava/lang/String;");
global::java.util.Date._getTimezoneOffset15385 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "getTimezoneOffset", "()I");
global::java.util.Date._Date15386 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "<init>", "()V");
global::java.util.Date._Date15387 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "<init>", "(J)V");
global::java.util.Date._Date15388 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "<init>", "(III)V");
global::java.util.Date._Date15389 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "<init>", "(IIIII)V");
global::java.util.Date._Date15390 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "<init>", "(IIIIII)V");
global::java.util.Date._Date15391 = @__env.GetMethodIDNoThrow(global::java.util.Date.staticClass, "<init>", "(Ljava/lang/String;)V");
}
}
}
| |
#region License, Terms and Conditions
//
// MetadataResult.cs
//
// Authors: Kori Francis <twitter.com/djbyter>, David Ball
// Copyright (C) 2010-2014 Clinical Support Systems, Inc. All rights reserved.
//
// 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.
//
#endregion
using System;
using System.Collections.Generic;
using System.Xml;
using ChargifyNET.Json;
namespace ChargifyNET
{
#region Imports
#endregion
/// <summary>
/// An array of Metadata
/// </summary>
public class MetadataResult : ChargifyBase, IMetadataResult
{
#region Field Keys
private const string TotalCountKey = "total-count";
private const string CurrentPageKey = "current-page";
private const string TotalPagesKey = "total-pages";
private const string PerPageKey = "per-page";
private const string MetadataKey = "metadata";
#endregion
#region Constructors
/// <summary>
/// Constructor
/// </summary>
public MetadataResult()
{
}
/// <summary>
/// Constructor (xml)
/// </summary>
/// <param name="metadataResultXml"></param>
public MetadataResult(string metadataResultXml)
{
// get the XML into an XML document
XmlDocument doc = new XmlDocument();
doc.LoadXml(metadataResultXml);
if (doc.ChildNodes.Count == 0)
throw new ArgumentException("XML not valid", nameof(metadataResultXml));
// loop through the child nodes of this node
foreach (XmlNode elementNode in doc.ChildNodes)
{
if (elementNode.Name == "results")
{
LoadFromNode(elementNode);
return;
}
}
// if we get here, then no metadata result data was found
throw new ArgumentException("XML does not contain metadata result information", nameof(metadataResultXml));
}
/// <summary>
/// Constructor (xml)
/// </summary>
/// <param name="metadataResultNode"></param>
public MetadataResult(XmlNode metadataResultNode)
{
if (metadataResultNode == null)
throw new ArgumentNullException(nameof(metadataResultNode));
if (metadataResultNode.Name != "results")
throw new ArgumentException("Not a vaild metadata results node", nameof(metadataResultNode));
if (metadataResultNode.ChildNodes.Count == 0)
throw new ArgumentException("XML not valid", nameof(metadataResultNode));
LoadFromNode(metadataResultNode);
}
/// <summary>
/// Constructor (json)
/// </summary>
/// <param name="metadataResultObject"></param>
public MetadataResult(JsonObject metadataResultObject)
{
if (metadataResultObject == null)
throw new ArgumentNullException(nameof(metadataResultObject));
if (metadataResultObject.Keys.Count <= 0)
throw new ArgumentException("Not a vaild metadata results object", nameof(metadataResultObject));
LoadFromJson(metadataResultObject);
}
private void LoadFromNode(XmlNode parentNode)
{
foreach (XmlNode dataNode in parentNode.ChildNodes)
{
switch (dataNode.Name)
{
case TotalCountKey:
_totalCount = dataNode.GetNodeContentAsInt();
break;
case CurrentPageKey:
_currentPage = dataNode.GetNodeContentAsInt();
break;
case TotalPagesKey:
_totalPages = dataNode.GetNodeContentAsInt();
break;
case PerPageKey:
_perPage = dataNode.GetNodeContentAsInt();
break;
case MetadataKey:
if (dataNode.FirstChild != null)
{
_metadata = new List<IMetadata>();
// There's no constructor that takes in an XmlNode, so parse it here.
foreach (XmlNode metadataNode in dataNode.ChildNodes)
{
var newObj = new Metadata();
var hasData = false;
foreach (XmlNode metadatumNode in metadataNode.ChildNodes)
{
switch (metadatumNode.Name)
{
case "resource-id":
hasData = true;
newObj.ResourceID = metadatumNode.GetNodeContentAsInt();
break;
case "name":
hasData = true;
newObj.Name = metadatumNode.GetNodeContentAsString();
break;
case "value":
hasData = true;
newObj.Value = metadatumNode.GetNodeContentAsString();
break;
}
}
if (hasData)
{
_metadata.Add(newObj);
}
}
}
break;
}
}
}
private void LoadFromJson(JsonObject obj)
{
foreach (string key in obj.Keys)
{
string theKey = key;
if (key.Contains("_"))
theKey = key.Replace("_", "-"); // Chargify seems to return different keys based on xml or json return type
switch (theKey)
{
case TotalCountKey:
_totalCount = obj.GetJSONContentAsInt(key);
break;
case CurrentPageKey:
_currentPage = obj.GetJSONContentAsInt(key);
break;
case TotalPagesKey:
_totalPages = obj.GetJSONContentAsInt(key);
break;
case PerPageKey:
_perPage = obj.GetJSONContentAsInt(key);
break;
case MetadataKey:
_metadata = new List<IMetadata>();
JsonArray viewObj = obj[key] as JsonArray;
if (viewObj?.Items != null && viewObj.Length > 0)
{
foreach (JsonValue item in viewObj.Items)
{
var newObj = new Metadata();
var hasData = false;
var itemObj = (JsonObject)item;
foreach (string subItemKey in itemObj.Keys)
{
switch (subItemKey)
{
case "resource_id":
hasData = true;
newObj.ResourceID = itemObj.GetJSONContentAsInt(subItemKey);
break;
case "name":
hasData = true;
newObj.Name = itemObj.GetJSONContentAsString(subItemKey);
break;
case "value":
hasData = true;
newObj.Value = itemObj.GetJSONContentAsString(subItemKey);
break;
}
}
if (hasData)
{
_metadata.Add(newObj);
}
}
}
break;
}
}
}
#endregion
#region IMetadataResult Members
/// <summary>
/// The total number of metadatum
/// </summary>
public int TotalCount
{
get
{
return _totalCount;
}
}
private int _totalCount = int.MinValue;
/// <summary>
/// The current page being returned
/// </summary>
public int CurrentPage
{
get
{
return _currentPage;
}
}
private int _currentPage = int.MinValue;
/// <summary>
/// The total number of pages (based on per-page and total count)
/// </summary>
public int TotalPages
{
get
{
return _totalPages;
}
}
private int _totalPages = int.MinValue;
/// <summary>
/// How many metadata are being returned per paged result
/// </summary>
public int PerPage
{
get
{
return _perPage;
}
}
private int _perPage = int.MinValue;
/// <summary>
/// The list of metadata contained in this response
/// </summary>
public List<IMetadata> Metadata
{
get
{
return _metadata;
}
}
private List<IMetadata> _metadata = new List<IMetadata>();
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace WalletWasabi.Fluent.Generators
{
[Generator]
public class AutoNotifyGenerator : ISourceGenerator
{
private const string AttributeText = @"// <auto-generated />
#nullable enable
using System;
namespace WalletWasabi.Fluent
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
sealed class AutoNotifyAttribute : Attribute
{
public AutoNotifyAttribute()
{
}
public string? PropertyName { get; set; }
public AccessModifier SetterModifier { get; set; } = AccessModifier.Public;
}
}";
private const string ModifierText = @"// <auto-generated />
namespace WalletWasabi.Fluent
{
public enum AccessModifier
{
None = 0,
Public = 1,
Protected = 2,
Private = 3,
Internal = 4
}
}";
public void Initialize(GeneratorInitializationContext context)
{
// System.Diagnostics.Debugger.Launch();
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
context.AddSource("AccessModifier", SourceText.From(ModifierText, Encoding.UTF8));
context.AddSource("AutoNotifyAttribute", SourceText.From(AttributeText, Encoding.UTF8));
if (context.SyntaxReceiver is not SyntaxReceiver receiver)
{
return;
}
var options = (context.Compilation as CSharpCompilation)?.SyntaxTrees[0].Options as CSharpParseOptions;
var compilation = context.Compilation.AddSyntaxTrees(
CSharpSyntaxTree.ParseText(SourceText.From(ModifierText, Encoding.UTF8), options),
CSharpSyntaxTree.ParseText(SourceText.From(AttributeText, Encoding.UTF8), options));
var attributeSymbol = compilation.GetTypeByMetadataName("WalletWasabi.Fluent.AutoNotifyAttribute");
if (attributeSymbol is null)
{
return;
}
var notifySymbol = compilation.GetTypeByMetadataName("ReactiveUI.ReactiveObject");
if (notifySymbol is null)
{
return;
}
List<IFieldSymbol> fieldSymbols = new ();
foreach (FieldDeclarationSyntax field in receiver.CandidateFields)
{
var semanticModel = compilation.GetSemanticModel(field.SyntaxTree);
foreach (VariableDeclaratorSyntax variable in field.Declaration.Variables)
{
if (semanticModel.GetDeclaredSymbol(variable) is not IFieldSymbol fieldSymbol)
{
continue;
}
var attributes = fieldSymbol.GetAttributes();
if (attributes.Any(ad => ad?.AttributeClass?.Equals(attributeSymbol, SymbolEqualityComparer.Default) ?? false))
{
fieldSymbols.Add(fieldSymbol);
}
}
}
// TODO: https://github.com/dotnet/roslyn/issues/49385
#pragma warning disable RS1024
var groupedFields = fieldSymbols.GroupBy(f => f.ContainingType);
#pragma warning restore RS1024
foreach (var group in groupedFields)
{
var classSource = ProcessClass(group.Key, group.ToList(), attributeSymbol, notifySymbol);
if (classSource is null)
{
continue;
}
context.AddSource($"{group.Key.Name}_AutoNotify.cs", SourceText.From(classSource, Encoding.UTF8));
}
}
private string? ProcessClass(INamedTypeSymbol classSymbol, List<IFieldSymbol> fields, ISymbol attributeSymbol, INamedTypeSymbol notifySymbol)
{
if (!classSymbol.ContainingSymbol.Equals(classSymbol.ContainingNamespace, SymbolEqualityComparer.Default))
{
return null;
}
string namespaceName = classSymbol.ContainingNamespace.ToDisplayString();
var addNotifyInterface = !classSymbol.Interfaces.Contains(notifySymbol);
var baseType = classSymbol.BaseType;
while (true)
{
if (baseType is null)
{
break;
}
if (SymbolEqualityComparer.Default.Equals(baseType, notifySymbol))
{
addNotifyInterface = false;
break;
}
baseType = baseType.BaseType;
}
var source = new StringBuilder();
var format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance
);
if (addNotifyInterface)
{
source.Append($@"// <auto-generated />
#nullable enable
using ReactiveUI;
namespace {namespaceName}
{{
public partial class {classSymbol.ToDisplayString(format)} : {notifySymbol.ToDisplayString()}
{{");
}
else
{
source.Append($@"// <auto-generated />
#nullable enable
using ReactiveUI;
namespace {namespaceName}
{{
public partial class {classSymbol.ToDisplayString(format)}
{{");
}
foreach (IFieldSymbol fieldSymbol in fields)
{
ProcessField(source, fieldSymbol, attributeSymbol);
}
source.Append($@"
}}
}}");
return source.ToString();
}
private static void ProcessField(StringBuilder source, IFieldSymbol fieldSymbol, ISymbol attributeSymbol)
{
var fieldName = fieldSymbol.Name;
var fieldType = fieldSymbol.Type;
var attributeData = fieldSymbol.GetAttributes().Single(ad => ad?.AttributeClass?.Equals(attributeSymbol, SymbolEqualityComparer.Default) ?? false);
var overridenNameOpt = attributeData.NamedArguments.SingleOrDefault(kvp => kvp.Key == "PropertyName").Value;
var propertyName = ChooseName(fieldName, overridenNameOpt);
if (propertyName is null || propertyName.Length == 0 || propertyName == fieldName)
{
// Issue a diagnostic that we can't process this field.
return;
}
var overridenSetterModifierOpt = attributeData.NamedArguments.SingleOrDefault(kvp => kvp.Key == "SetterModifier").Value;
var setterModifier = ChooseSetterModifier(overridenSetterModifierOpt);
if (setterModifier is null)
{
source.Append($@"
public {fieldType} {propertyName}
{{
get => {fieldName};
}}");
}
else
{
source.Append($@"
public {fieldType} {propertyName}
{{
get => {fieldName};
{setterModifier}set => this.RaiseAndSetIfChanged(ref {fieldName}, value);
}}");
}
static string? ChooseSetterModifier(TypedConstant overridenSetterModifierOpt)
{
if (!overridenSetterModifierOpt.IsNull && overridenSetterModifierOpt.Value is not null)
{
var value = (int)overridenSetterModifierOpt.Value;
return value switch
{
// None
0 => null,
// Public
1 => "",
// Protected
2 => "protected ",
// Private
3 => "private ",
// Internal
4 => "internal ",
// Default
_ => ""
};
}
else
{
return "";
}
}
static string? ChooseName(string fieldName, TypedConstant overridenNameOpt)
{
if (!overridenNameOpt.IsNull)
{
return overridenNameOpt.Value?.ToString();
}
fieldName = fieldName.TrimStart('_');
if (fieldName.Length == 0)
{
return string.Empty;
}
if (fieldName.Length == 1)
{
return fieldName.ToUpper();
}
#pragma warning disable IDE0057 // Use range operator
return fieldName.Substring(0, 1).ToUpper() + fieldName.Substring(1);
#pragma warning restore IDE0057 // Use range operator
}
}
private class SyntaxReceiver : ISyntaxReceiver
{
public List<FieldDeclarationSyntax> CandidateFields { get; } = new List<FieldDeclarationSyntax>();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is FieldDeclarationSyntax fieldDeclarationSyntax
&& fieldDeclarationSyntax.AttributeLists.Count > 0)
{
CandidateFields.Add(fieldDeclarationSyntax);
}
}
}
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using HETSAPI;
using System.Text;
using HETSAPI.Models;
using Newtonsoft.Json;
using System.Net;
namespace HETSAPI.Test
{
public class ProjectIntegrationTest : ApiIntegrationTestBase
{
[Fact]
/// <summary>
/// Integration test for ProjectsBulkPost
/// </summary>
public async void TestProjectsBulkPost()
{
var request = new HttpRequestMessage(HttpMethod.Post, "/api/projects/bulk");
request.Content = new StringContent("[]", Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
[Fact]
/// <summary>
/// Basic Integration test for Roles
/// </summary>
public async void TestProjectsBasic()
{
string initialName = "InitialName";
string changedName = "ChangedName";
// first test the POST.
var request = new HttpRequestMessage(HttpMethod.Post, "/api/projects");
// create a new object.
Project project = new Project();
project.Name = initialName;
string jsonString = project.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
project = JsonConvert.DeserializeObject<Project>(jsonString);
// get the id
var id = project.Id;
// change the name
project.Name = changedName;
// now do an update.
request = new HttpRequestMessage(HttpMethod.Put, "/api/projects/" + id);
request.Content = new StringContent(project.ToJson(), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// do a get.
request = new HttpRequestMessage(HttpMethod.Get, "/api/projects/" + id);
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
project = JsonConvert.DeserializeObject<Project>(jsonString);
// verify the change went through.
Assert.Equal(project.Name, changedName);
// do a delete.
request = new HttpRequestMessage(HttpMethod.Post, "/api/projects/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/projects/" + id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
[Fact]
/// <summary>
/// Test project contacts
/// </summary>
public async void TestProjectContacts()
{
string initialName = "InitialName";
string changedName = "ChangedName";
// first test the POST.
var request = new HttpRequestMessage(HttpMethod.Post, "/api/projects");
// create a new object.
Owner owner = new Owner();
owner.OrganizationName = initialName;
string jsonString = owner.ToJson();
request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
owner = JsonConvert.DeserializeObject<Owner>(jsonString);
// get the id
var id = owner.Id;
// change the name
owner.OrganizationName = changedName;
// get contacts should be empty.
request = new HttpRequestMessage(HttpMethod.Get, "/api/projects/" + id + "/contacts");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
List<Contact> contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString);
// verify the list is empty.
Assert.Equal(contacts.Count(), 0);
// add a contact.
Contact contact = new Contact();
contact.GivenName = initialName;
contacts.Add(contact);
request = new HttpRequestMessage(HttpMethod.Put, "/api/projects/" + id + "/contacts");
request.Content = new StringContent(JsonConvert.SerializeObject(contacts), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString);
// verify the list has one element.
Assert.Equal(contacts.Count, 1);
Assert.Equal(contacts[0].GivenName, initialName);
// get contacts should be 1
request = new HttpRequestMessage(HttpMethod.Get, "/api/projects/" + id + "/contacts");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString);
// verify the list has a record.
Assert.Equal(contacts.Count, 1);
Assert.Equal(contacts[0].GivenName, initialName);
// test removing the contact.
contacts.Clear();
request = new HttpRequestMessage(HttpMethod.Put, "/api/projects/" + id + "/contacts");
request.Content = new StringContent(JsonConvert.SerializeObject(contacts), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString);
// should be 0
Assert.Equal(contacts.Count, 0);
// test the get
request = new HttpRequestMessage(HttpMethod.Get, "/api/projects/" + id + "/contacts");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString);
// verify the list has no records.
Assert.Equal(contacts.Count, 0);
// test the post.
Contact newContact = new Contact();
newContact.OrganizationName = "asdf";
request = new HttpRequestMessage(HttpMethod.Post, "/api/projects/" + id + "/contacts");
request.Content = new StringContent(JsonConvert.SerializeObject(newContact), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
newContact = JsonConvert.DeserializeObject<Contact>(jsonString);
// should be 0
Assert.NotEqual(newContact.Id, 0);
request = new HttpRequestMessage(HttpMethod.Put, "/api/projects/" + id + "/contacts");
request.Content = new StringContent(JsonConvert.SerializeObject(contacts), Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// parse as JSON.
jsonString = await response.Content.ReadAsStringAsync();
contacts = JsonConvert.DeserializeObject<List<Contact>>(jsonString);
// should be 0
Assert.Equal(contacts.Count, 0);
// delete the owner.
request = new HttpRequestMessage(HttpMethod.Post, "/api/projects/" + id + "/delete");
response = await _client.SendAsync(request);
response.EnsureSuccessStatusCode();
// should get a 404 if we try a get now.
request = new HttpRequestMessage(HttpMethod.Get, "/api/projects/" + id);
response = await _client.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.NotFound);
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Microsoft.Xna.Framework.Graphics
{
internal partial class DXEffectObject
{
public enum D3DRENDERSTATETYPE
{
ZENABLE = 7,
FILLMODE = 8,
SHADEMODE = 9,
ZWRITEENABLE = 14,
ALPHATESTENABLE = 15,
LASTPIXEL = 16,
SRCBLEND = 19,
DESTBLEND = 20,
CULLMODE = 22,
ZFUNC = 23,
ALPHAREF = 24,
ALPHAFUNC = 25,
DITHERENABLE = 26,
ALPHABLENDENABLE = 27,
FOGENABLE = 28,
SPECULARENABLE = 29,
FOGCOLOR = 34,
FOGTABLEMODE = 35,
FOGSTART = 36,
FOGEND = 37,
FOGDENSITY = 38,
RANGEFOGENABLE = 48,
STENCILENABLE = 52,
STENCILFAIL = 53,
STENCILZFAIL = 54,
STENCILPASS = 55,
STENCILFUNC = 56,
STENCILREF = 57,
STENCILMASK = 58,
STENCILWRITEMASK = 59,
TEXTUREFACTOR = 60,
WRAP0 = 128,
WRAP1 = 129,
WRAP2 = 130,
WRAP3 = 131,
WRAP4 = 132,
WRAP5 = 133,
WRAP6 = 134,
WRAP7 = 135,
CLIPPING = 136,
LIGHTING = 137,
AMBIENT = 139,
FOGVERTEXMODE = 140,
COLORVERTEX = 141,
LOCALVIEWER = 142,
NORMALIZENORMALS = 143,
DIFFUSEMATERIALSOURCE = 145,
SPECULARMATERIALSOURCE = 146,
AMBIENTMATERIALSOURCE = 147,
EMISSIVEMATERIALSOURCE = 148,
VERTEXBLEND = 151,
CLIPPLANEENABLE = 152,
POINTSIZE = 154,
POINTSIZE_MIN = 155,
POINTSPRITEENABLE = 156,
POINTSCALEENABLE = 157,
POINTSCALE_A = 158,
POINTSCALE_B = 159,
POINTSCALE_C = 160,
MULTISAMPLEANTIALIAS = 161,
MULTISAMPLEMASK = 162,
PATCHEDGESTYLE = 163,
DEBUGMONITORTOKEN = 165,
POINTSIZE_MAX = 166,
INDEXEDVERTEXBLENDENABLE = 167,
COLORWRITEENABLE = 168,
TWEENFACTOR = 170,
BLENDOP = 171,
POSITIONDEGREE = 172,
NORMALDEGREE = 173,
SCISSORTESTENABLE = 174,
SLOPESCALEDEPTHBIAS = 175,
ANTIALIASEDLINEENABLE = 176,
MINTESSELLATIONLEVEL = 178,
MAXTESSELLATIONLEVEL = 179,
ADAPTIVETESS_X = 180,
ADAPTIVETESS_Y = 181,
ADAPTIVETESS_Z = 182,
ADAPTIVETESS_W = 183,
ENABLEADAPTIVETESSELLATION= 184,
TWOSIDEDSTENCILMODE = 185,
CCW_STENCILFAIL = 186,
CCW_STENCILZFAIL = 187,
CCW_STENCILPASS = 188,
CCW_STENCILFUNC = 189,
COLORWRITEENABLE1 = 190,
COLORWRITEENABLE2 = 191,
COLORWRITEENABLE3 = 192,
BLENDFACTOR = 193,
SRGBWRITEENABLE = 194,
DEPTHBIAS = 195,
WRAP8 = 198,
WRAP9 = 199,
WRAP10 = 200,
WRAP11 = 201,
WRAP12 = 202,
WRAP13 = 203,
WRAP14 = 204,
WRAP15 = 205,
SEPARATEALPHABLENDENABLE = 206,
SRCBLENDALPHA = 207,
DESTBLENDALPHA = 208,
BLENDOPALPHA = 209,
FORCE_DWORD = 0x7fffffff
}
public enum D3DTEXTURESTAGESTATETYPE
{
COLOROP = 1,
COLORARG1 = 2,
COLORARG2 = 3,
ALPHAOP = 4,
ALPHAARG1 = 5,
ALPHAARG2 = 6,
BUMPENVMAT00 = 7,
BUMPENVMAT01 = 8,
BUMPENVMAT10 = 9,
BUMPENVMAT11 = 10,
TEXCOORDINDEX = 11,
BUMPENVLSCALE = 22,
BUMPENVLOFFSET = 23,
TEXTURETRANSFORMFLAGS = 24,
COLORARG0 = 26,
ALPHAARG0 = 27,
RESULTARG = 28,
CONSTANT = 32,
FORCE_DWORD = 0x7fffffff
}
public enum D3DTRANSFORMSTATETYPE
{
VIEW = 2,
PROJECTION = 3,
TEXTURE0 = 16,
TEXTURE1 = 17,
TEXTURE2 = 18,
TEXTURE3 = 19,
TEXTURE4 = 20,
TEXTURE5 = 21,
TEXTURE6 = 22,
TEXTURE7 = 23,
WORLD = 256,
FORCE_DWORD = 0x7fffffff
}
public const int D3DX_PARAMETER_SHARED = 1;
public const int D3DX_PARAMETER_LITERAL = 2;
public const int D3DX_PARAMETER_ANNOTATION = 4;
public enum D3DXPARAMETER_CLASS
{
SCALAR,
VECTOR,
MATRIX_ROWS,
MATRIX_COLUMNS,
OBJECT,
STRUCT,
FORCE_DWORD = 0x7fffffff,
}
public enum D3DXPARAMETER_TYPE
{
VOID,
BOOL,
INT,
FLOAT,
STRING,
TEXTURE,
TEXTURE1D,
TEXTURE2D,
TEXTURE3D,
TEXTURECUBE,
SAMPLER,
SAMPLER1D,
SAMPLER2D,
SAMPLER3D,
SAMPLERCUBE,
PIXELSHADER,
VERTEXSHADER,
PIXELFRAGMENT,
VERTEXFRAGMENT,
UNSUPPORTED,
FORCE_DWORD = 0x7fffffff,
}
enum D3DSAMPLERSTATETYPE
{
ADDRESSU = 1,
ADDRESSV = 2,
ADDRESSW = 3,
BORDERCOLOR = 4,
MAGFILTER = 5,
MINFILTER = 6,
MIPFILTER = 7,
MIPMAPLODBIAS = 8,
MAXMIPLEVEL = 9,
MAXANISOTROPY = 10,
SRGBTEXTURE = 11,
ELEMENTINDEX = 12,
DMAPOFFSET = 13,
FORCE_DWORD = 0x7fffffff,
};
public enum STATE_CLASS
{
LIGHTENABLE,
FVF,
LIGHT,
MATERIAL,
NPATCHMODE,
PIXELSHADER,
RENDERSTATE,
SETSAMPLER,
SAMPLERSTATE,
TEXTURE,
TEXTURESTAGE,
TRANSFORM,
VERTEXSHADER,
SHADERCONST,
UNKNOWN,
};
public enum MATERIAL_TYPE
{
DIFFUSE,
AMBIENT,
SPECULAR,
EMISSIVE,
POWER,
};
public enum LIGHT_TYPE
{
TYPE,
DIFFUSE,
SPECULAR,
AMBIENT,
POSITION,
DIRECTION,
RANGE,
FALLOFF,
ATTENUATION0,
ATTENUATION1,
ATTENUATION2,
THETA,
PHI,
};
public enum SHADER_CONSTANT_TYPE
{
VSFLOAT,
VSBOOL,
VSINT,
PSFLOAT,
PSBOOL,
PSINT,
}
public enum STATE_TYPE
{
CONSTANT,
PARAMETER,
EXPRESSION,
EXPRESSIONINDEX,
}
public class d3dx_parameter
{
public string name;
public string semantic;
public object data;
public D3DXPARAMETER_CLASS class_;
public D3DXPARAMETER_TYPE type;
public uint rows;
public uint columns;
public uint element_count;
public uint annotation_count;
public uint member_count;
public uint flags;
public uint bytes;
public int bufferIndex = -1;
public int bufferOffset = -1;
public d3dx_parameter[] annotation_handles;
public d3dx_parameter[] member_handles;
public override string ToString()
{
if (rows > 0 || columns > 0)
return string.Format("{0} {1}{2}x{3} {4} : cb{5},{6}", class_, type, rows, columns, name, bufferIndex, bufferOffset);
else
return string.Format("{0} {1} {2}", class_, type, name);
}
}
public class d3dx_state
{
public uint operation;
public uint index;
public STATE_TYPE type;
public d3dx_parameter parameter;
}
public class d3dx_sampler
{
public uint state_count;
public d3dx_state[] states;
}
public class d3dx_pass
{
public string name;
public uint state_count;
public uint annotation_count;
public BlendState blendState;
public DepthStencilState depthStencilState;
public RasterizerState rasterizerState;
public d3dx_state[] states;
public d3dx_parameter[] annotation_handles;
}
public class d3dx_technique
{
public string name;
public uint pass_count;
public uint annotation_count;
public d3dx_parameter[] annotation_handles;
public d3dx_pass[] pass_handles;
}
public class state_info
{
public STATE_CLASS class_ { get; private set; }
public uint op { get; private set; }
public string name { get; private set; }
public state_info(STATE_CLASS class_, uint op, string name)
{
this.class_ = class_;
this.op = op;
this.name = name;
}
}
/// <summary>
/// The shared state definition table.
/// </summary>
public static readonly state_info[] state_table =
{
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ZENABLE, "ZENABLE"), /* 0x0 */
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FILLMODE, "FILLMODE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SHADEMODE, "SHADEMODE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ZWRITEENABLE, "ZWRITEENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ALPHATESTENABLE, "ALPHATESTENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.LASTPIXEL, "LASTPIXEL"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SRCBLEND, "SRCBLEND"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.DESTBLEND, "DESTBLEND"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.CULLMODE, "CULLMODE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ZFUNC, "ZFUNC"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ALPHAREF, "ALPHAREF"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ALPHAFUNC, "ALPHAFUNC"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.DITHERENABLE, "DITHERENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ALPHABLENDENABLE, "ALPHABLENDENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FOGENABLE, "FOGENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SPECULARENABLE, "SPECULARENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FOGCOLOR, "FOGCOLOR"), /* 0x10 */
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FOGTABLEMODE, "FOGTABLEMODE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FOGSTART, "FOGSTART"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FOGEND, "FOGEND"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FOGDENSITY, "FOGDENSITY"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.RANGEFOGENABLE, "RANGEFOGENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILENABLE, "STENCILENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILFAIL, "STENCILFAIL"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILZFAIL, "STENCILZFAIL"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILPASS, "STENCILPASS"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILFUNC, "STENCILFUNC"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILREF, "STENCILREF"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILMASK, "STENCILMASK"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.STENCILWRITEMASK, "STENCILWRITEMASK"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.TEXTUREFACTOR, "TEXTUREFACTOR"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP0, "WRAP0"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP1, "WRAP1"), /* 0x20 */
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP2, "WRAP2"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP3, "WRAP3"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP4, "WRAP4"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP5, "WRAP5"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP6, "WRAP6"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP7, "WRAP7"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP8, "WRAP8"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP9, "WRAP9"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP10, "WRAP10"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP11, "WRAP11"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP12, "WRAP12"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP13, "WRAP13"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP14, "WRAP14"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.WRAP15, "WRAP15"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.CLIPPING, "CLIPPING"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.LIGHTING, "LIGHTING"), /* 0x30 */
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.AMBIENT, "AMBIENT"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.FOGVERTEXMODE, "FOGVERTEXMODE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.COLORVERTEX, "COLORVERTEX"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.LOCALVIEWER, "LOCALVIEWER"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.NORMALIZENORMALS, "NORMALIZENORMALS"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.DIFFUSEMATERIALSOURCE, "DIFFUSEMATERIALSOURCE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SPECULARMATERIALSOURCE, "SPECULARMATERIALSOURCE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.AMBIENTMATERIALSOURCE, "AMBIENTMATERIALSOURCE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.EMISSIVEMATERIALSOURCE, "EMISSIVEMATERIALSOURCE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.VERTEXBLEND, "VERTEXBLEND"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.CLIPPLANEENABLE, "CLIPPLANEENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSIZE, "POINTSIZE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSIZE_MIN, "POINTSIZE_MIN"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSIZE_MAX, "POINTSIZE_MAX"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSPRITEENABLE, "POINTSPRITEENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSCALEENABLE, "POINTSCALEENABLE"), /* 0x40 */
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSCALE_A, "POINTSCALE_A"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSCALE_B, "POINTSCALE_B"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POINTSCALE_C, "POINTSCALE_C"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.MULTISAMPLEANTIALIAS, "MULTISAMPLEANTIALIAS"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.MULTISAMPLEMASK, "MULTISAMPLEMASK"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.PATCHEDGESTYLE, "PATCHEDGESTYLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.DEBUGMONITORTOKEN, "DEBUGMONITORTOKEN"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.INDEXEDVERTEXBLENDENABLE, "INDEXEDVERTEXBLENDENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.COLORWRITEENABLE, "COLORWRITEENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.TWEENFACTOR, "TWEENFACTOR"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.BLENDOP, "BLENDOP"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.POSITIONDEGREE, "POSITIONDEGREE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.NORMALDEGREE, "NORMALDEGREE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SCISSORTESTENABLE, "SCISSORTESTENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SLOPESCALEDEPTHBIAS, "SLOPESCALEDEPTHBIAS"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ANTIALIASEDLINEENABLE, "ANTIALIASEDLINEENABLE"), /* 0x50 */
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.MINTESSELLATIONLEVEL, "MINTESSELLATIONLEVEL"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.MAXTESSELLATIONLEVEL, "MAXTESSELLATIONLEVEL"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ADAPTIVETESS_X, "ADAPTIVETESS_X"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ADAPTIVETESS_Y, "ADAPTIVETESS_Y"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ADAPTIVETESS_Z, "ADAPTIVETESS_Z"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ADAPTIVETESS_W, "ADAPTIVETESS_W"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.ENABLEADAPTIVETESSELLATION, "ENABLEADAPTIVETESSELLATION"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.TWOSIDEDSTENCILMODE, "TWOSIDEDSTENCILMODE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.CCW_STENCILFAIL, "CCW_STENCILFAIL"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.CCW_STENCILZFAIL, "CCW_STENCILZFAIL"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.CCW_STENCILPASS, "CCW_STENCILPASS"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.CCW_STENCILFUNC, "CCW_STENCILFUNC"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.COLORWRITEENABLE1, "COLORWRITEENABLE1"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.COLORWRITEENABLE2, "COLORWRITEENABLE2"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.COLORWRITEENABLE3, "COLORWRITEENABLE3"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.BLENDFACTOR, "BLENDFACTOR"), /* 0x60 */
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SRGBWRITEENABLE, "SRGBWRITEENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.DEPTHBIAS, "DEPTHBIAS"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SEPARATEALPHABLENDENABLE, "SEPARATEALPHABLENDENABLE"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.SRCBLENDALPHA, "SRCBLENDALPHA"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.DESTBLENDALPHA, "DESTBLENDALPHA"),
new state_info(STATE_CLASS.RENDERSTATE, (uint)D3DRENDERSTATETYPE.BLENDOPALPHA, "BLENDOPALPHA"),
/* Texture stages */
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.COLOROP, "COLOROP"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.COLORARG0, "COLORARG0"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.COLORARG1, "COLORARG1"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.COLORARG2, "COLORARG2"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.ALPHAOP, "ALPHAOP"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.ALPHAARG0, "ALPHAARG0"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.ALPHAARG1, "ALPHAARG1"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.ALPHAARG2, "ALPHAARG2"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.RESULTARG, "RESULTARG"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.BUMPENVMAT00, "BUMPENVMAT00"), /* 0x70 */
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.BUMPENVMAT01, "BUMPENVMAT01"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.BUMPENVMAT10, "BUMPENVMAT10"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.BUMPENVMAT11, "BUMPENVMAT11"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.TEXCOORDINDEX, "TEXCOORDINDEX"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.BUMPENVLSCALE, "BUMPENVLSCALE"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.BUMPENVLOFFSET, "BUMPENVLOFFSET"),
new state_info(STATE_CLASS.TEXTURESTAGE, (uint)D3DTEXTURESTAGESTATETYPE.TEXTURETRANSFORMFLAGS, "TEXTURETRANSFORMFLAGS"),
/* */
new state_info(STATE_CLASS.UNKNOWN, 0, "UNKNOWN"),
/* NPatchMode */
new state_info(STATE_CLASS.NPATCHMODE, 0, "NPatchMode"),
/* */
new state_info(STATE_CLASS.UNKNOWN, 0, "UNKNOWN"),
/* Transform */
new state_info(STATE_CLASS.TRANSFORM, (uint)D3DTRANSFORMSTATETYPE.PROJECTION, "PROJECTION"),
new state_info(STATE_CLASS.TRANSFORM, (uint)D3DTRANSFORMSTATETYPE.VIEW, "VIEW"),
new state_info(STATE_CLASS.TRANSFORM, (uint)D3DTRANSFORMSTATETYPE.WORLD, "WORLD"),
new state_info(STATE_CLASS.TRANSFORM, (uint)D3DTRANSFORMSTATETYPE.TEXTURE0, "TEXTURE0"),
/* Material */
new state_info(STATE_CLASS.MATERIAL, (uint)MATERIAL_TYPE.DIFFUSE, "MaterialDiffuse"),
new state_info(STATE_CLASS.MATERIAL, (uint)MATERIAL_TYPE.AMBIENT, "MaterialAmbient"), /* 0x80 */
new state_info(STATE_CLASS.MATERIAL, (uint)MATERIAL_TYPE.SPECULAR, "MaterialSpecular"),
new state_info(STATE_CLASS.MATERIAL, (uint)MATERIAL_TYPE.EMISSIVE, "MaterialEmissive"),
new state_info(STATE_CLASS.MATERIAL, (uint)MATERIAL_TYPE.POWER, "MaterialPower"),
/* Light */
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.TYPE, "LightType"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.DIFFUSE, "LightDiffuse"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.SPECULAR, "LightSpecular"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.AMBIENT, "LightAmbient"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.POSITION, "LightPosition"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.DIRECTION, "LightDirection"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.RANGE, "LightRange"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.FALLOFF, "LightFallOff"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.ATTENUATION0, "LightAttenuation0"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.ATTENUATION1, "LightAttenuation1"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.ATTENUATION2, "LightAttenuation2"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.THETA, "LightTheta"),
new state_info(STATE_CLASS.LIGHT, (uint)LIGHT_TYPE.PHI, "LightPhi"), /* 0x90 */
/* Ligthenable */
new state_info(STATE_CLASS.LIGHTENABLE, 0, "LightEnable"),
/* Vertexshader */
new state_info(STATE_CLASS.VERTEXSHADER, 0, "Vertexshader"),
/* Pixelshader */
new state_info(STATE_CLASS.PIXELSHADER, 0, "Pixelshader"),
/* Shader constants */
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSFLOAT, "VertexShaderConstantF"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSBOOL, "VertexShaderConstantB"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSINT, "VertexShaderConstantI"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSFLOAT, "VertexShaderConstant"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSFLOAT, "VertexShaderConstant1"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSFLOAT, "VertexShaderConstant2"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSFLOAT, "VertexShaderConstant3"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.VSFLOAT, "VertexShaderConstant4"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSFLOAT, "PixelShaderConstantF"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSBOOL, "PixelShaderConstantB"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSINT, "PixelShaderConstantI"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSFLOAT, "PixelShaderConstant"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSFLOAT, "PixelShaderConstant1"), /* 0xa0 */
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSFLOAT, "PixelShaderConstant2"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSFLOAT, "PixelShaderConstant3"),
new state_info(STATE_CLASS.SHADERCONST, (uint)SHADER_CONSTANT_TYPE.PSFLOAT, "PixelShaderConstant4"),
/* Texture */
new state_info(STATE_CLASS.TEXTURE, 0, "Texture"),
/* Sampler states */
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.ADDRESSU, "AddressU"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.ADDRESSV, "AddressV"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.ADDRESSW, "AddressW"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.BORDERCOLOR, "BorderColor"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.MAGFILTER, "MagFilter"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.MINFILTER, "MinFilter"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.MIPFILTER, "MipFilter"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.MIPMAPLODBIAS, "MipMapLodBias"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.MAXMIPLEVEL, "MaxMipLevel"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.MAXANISOTROPY, "MaxAnisotropy"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.SRGBTEXTURE, "SRGBTexture"),
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.ELEMENTINDEX, "ElementIndex"), /* 0xb0 */
new state_info(STATE_CLASS.SAMPLERSTATE, (uint)D3DSAMPLERSTATETYPE.DMAPOFFSET, "DMAPOffset"),
/* Set sampler */
new state_info(STATE_CLASS.SETSAMPLER, 0, "Sampler"),
};
static public EffectParameterClass ToXNAParameterClass( D3DXPARAMETER_CLASS class_ )
{
switch (class_)
{
case DXEffectObject.D3DXPARAMETER_CLASS.SCALAR:
return EffectParameterClass.Scalar;
case DXEffectObject.D3DXPARAMETER_CLASS.VECTOR:
return EffectParameterClass.Vector;
case DXEffectObject.D3DXPARAMETER_CLASS.MATRIX_ROWS:
case DXEffectObject.D3DXPARAMETER_CLASS.MATRIX_COLUMNS:
return EffectParameterClass.Matrix;
case DXEffectObject.D3DXPARAMETER_CLASS.OBJECT:
return EffectParameterClass.Object;
case DXEffectObject.D3DXPARAMETER_CLASS.STRUCT:
return EffectParameterClass.Struct;
default:
throw new NotImplementedException();
}
}
static public EffectParameterType ToXNAParameterType(D3DXPARAMETER_TYPE type)
{
switch (type)
{
case DXEffectObject.D3DXPARAMETER_TYPE.BOOL:
return EffectParameterType.Bool;
case DXEffectObject.D3DXPARAMETER_TYPE.INT:
return EffectParameterType.Int32;
case DXEffectObject.D3DXPARAMETER_TYPE.FLOAT:
return EffectParameterType.Single;
case DXEffectObject.D3DXPARAMETER_TYPE.STRING:
return EffectParameterType.String;
case DXEffectObject.D3DXPARAMETER_TYPE.TEXTURE:
return EffectParameterType.Texture;
case DXEffectObject.D3DXPARAMETER_TYPE.TEXTURE1D:
return EffectParameterType.Texture1D;
case DXEffectObject.D3DXPARAMETER_TYPE.TEXTURE2D:
return EffectParameterType.Texture2D;
case DXEffectObject.D3DXPARAMETER_TYPE.TEXTURE3D:
return EffectParameterType.Texture3D;
case DXEffectObject.D3DXPARAMETER_TYPE.TEXTURECUBE:
return EffectParameterType.TextureCube;
default:
throw new NotImplementedException();
}
}
static internal VertexElementUsage ToXNAVertexElementUsage(MojoShader.MOJOSHADER_usage usage)
{
switch (usage)
{
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_POSITION:
return VertexElementUsage.Position;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_BLENDWEIGHT:
return VertexElementUsage.BlendWeight;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_BLENDINDICES:
return VertexElementUsage.BlendIndices;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_NORMAL:
return VertexElementUsage.Normal;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_POINTSIZE:
return VertexElementUsage.PointSize;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_TEXCOORD:
return VertexElementUsage.TextureCoordinate;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_TANGENT:
return VertexElementUsage.Tangent;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_BINORMAL:
return VertexElementUsage.Binormal;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_TESSFACTOR:
return VertexElementUsage.TessellateFactor;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_COLOR:
return VertexElementUsage.Color;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_FOG:
return VertexElementUsage.Fog;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_DEPTH:
return VertexElementUsage.Depth;
case MojoShader.MOJOSHADER_usage.MOJOSHADER_USAGE_SAMPLE:
return VertexElementUsage.Sample;
default:
throw new NotImplementedException();
}
}
internal static int GetShaderIndex(DXEffectObject.STATE_CLASS type, d3dx_state[] states)
{
foreach (var state in states)
{
var operation = DXEffectObject.state_table[state.operation];
if (operation.class_ != type)
continue;
if (state.type != DXEffectObject.STATE_TYPE.CONSTANT)
throw new NotSupportedException("We do not support shader expressions!");
return (int)state.parameter.data;
}
return -1;
}
public d3dx_parameter[] Objects { get; private set; }
public d3dx_parameter[] Parameters { get; private set; }
public d3dx_technique[] Techniques { get; private set; }
public List<DXShaderData> Shaders { get; private set; }
public List<DXConstantBufferData> ConstantBuffers { get; private set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if ARM
#define _TARGET_ARM_
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter
#define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define FEATURE_HFA
#elif ARM64
#define _TARGET_ARM64_
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter
#define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define ENREGISTERED_PARAMTYPE_MAXSIZE
#define FEATURE_HFA
#elif X86
#define _TARGET_X86_
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#define CALLINGCONVENTION_CALLEE_POPS
#elif AMD64
#if UNIXAMD64
#define UNIX_AMD64_ABI
#define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter
#else
#endif
#define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter
#define _TARGET_AMD64_
#define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers
#define ENREGISTERED_RETURNTYPE_MAXSIZE
#define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE
#define ENREGISTERED_PARAMTYPE_MAXSIZE
#elif WASM
#define _TARGET_WASM_
#else
#error Unknown architecture!
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime.Augments;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.Runtime.CallConverter;
using ArgIterator = Internal.Runtime.CallConverter.ArgIterator;
using CallingConvention = Internal.Runtime.CallConverter.CallingConvention;
namespace Internal.Runtime.TypeLoader
{
internal unsafe struct CallConversionParameters
{
internal class GCHandleContainer
{
internal UnsafeGCHandle _thisPtrHandle;
internal UnsafeGCHandle _dynamicInvokeArgHandle;
internal UnsafeGCHandle _returnObjectHandle;
internal GCHandleContainer()
{
// Allocations of pinned gc handles done only once during the lifetime of a thread
_thisPtrHandle = UnsafeGCHandle.Alloc(null, GCHandleType.Pinned);
_dynamicInvokeArgHandle = UnsafeGCHandle.Alloc(null, GCHandleType.Pinned);
_returnObjectHandle = UnsafeGCHandle.Alloc(null, GCHandleType.Pinned);
}
~GCHandleContainer()
{
// Free all the pinned objects when the thread dies to avoid gchandle leaks
_thisPtrHandle.Free();
_dynamicInvokeArgHandle.Free();
_returnObjectHandle.Free();
}
}
private struct DelegateData
{
internal Delegate _delegateObject;
internal object _firstParameter;
internal object _helperObject;
internal IntPtr _extraFunctionPointerOrData;
internal IntPtr _functionPointer;
// Computed fields
internal object _boxedFirstParameter;
internal object _multicastThisPointer;
internal int _multicastTargetCount;
}
internal CallConversionInfo _conversionInfo;
internal ArgIterator _callerArgs;
internal ArgIterator _calleeArgs;
internal byte* _callerTransitionBlock;
internal IntPtr _invokeReturnValue;
internal bool _copyReturnValue;
internal object[] _dynamicInvokeParams;
internal CallConverterThunk.DynamicInvokeByRefArgObjectWrapper[] _dynamicInvokeByRefObjectArgs;
private IntPtr _instantiatingStubArgument;
private IntPtr _functionPointerToCall;
private DelegateData _delegateData;
[ThreadStatic]
internal static GCHandleContainer s_pinnedGCHandles;
// Signature of the DynamicInvokeImpl method on delegates is always the same.
private static ArgIteratorData s_delegateDynamicInvokeImplArgIteratorData = new ArgIteratorData(true, false, new TypeHandle[]{
new TypeHandle(false, typeof(object).TypeHandle),
new TypeHandle(false, typeof(IntPtr).TypeHandle),
new TypeHandle(true, typeof(InvokeUtils.ArgSetupState).TypeHandle)
}, new TypeHandle(false, typeof(object).TypeHandle));
// Signature of all the InvokeRetXYZ reflection invoker stubs is always the same.
private static ArgIteratorData s_reflectionDynamicInvokeImplArgIteratorData = new ArgIteratorData(false, false, new TypeHandle[]{
new TypeHandle(false, typeof(object).TypeHandle),
new TypeHandle(false, typeof(IntPtr).TypeHandle),
new TypeHandle(true, typeof(InvokeUtils.ArgSetupState).TypeHandle),
new TypeHandle(false, typeof(bool).TypeHandle)
}, new TypeHandle(false, typeof(object).TypeHandle));
internal CallConversionParameters(CallConversionInfo conversionInfo, IntPtr callerTransitionBlockParam)
{
// Make sure the thred static variable has been initialized for this thread
s_pinnedGCHandles = s_pinnedGCHandles ?? new GCHandleContainer();
_conversionInfo = conversionInfo;
_callerTransitionBlock = (byte*)callerTransitionBlockParam.ToPointer();
_functionPointerToCall = conversionInfo.TargetFunctionPointer;
_instantiatingStubArgument = conversionInfo.InstantiatingStubArgument;
_delegateData = default(DelegateData);
_calleeArgs = default(ArgIterator);
_invokeReturnValue = IntPtr.Zero;
_copyReturnValue = true;
_dynamicInvokeParams = null;
_dynamicInvokeByRefObjectArgs = null;
//
// Setup input argument iterator for the caller
//
ArgIteratorData callerIteratorData;
if (conversionInfo.IsDelegateDynamicInvokeThunk)
callerIteratorData = s_delegateDynamicInvokeImplArgIteratorData;
else if (conversionInfo.IsReflectionDynamicInvokerThunk)
callerIteratorData = s_reflectionDynamicInvokeImplArgIteratorData;
else
callerIteratorData = conversionInfo.ArgIteratorData;
_callerArgs = new ArgIterator(callerIteratorData,
callerIteratorData.HasThis() ?
CallingConvention.ManagedInstance :
CallingConvention.ManagedStatic,
conversionInfo.CallerHasParamType,
conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget,
conversionInfo.CallerForcedByRefData,
false, false); // Setup input
bool forceCalleeHasParamType = false;
// If the callee MAY have a param type, we need to know before we create the callee arg iterator
// To do this we need to actually load the target address and see if it has the generic method pointer
// bit set.
if (conversionInfo.CalleeMayHaveParamType)
{
ArgIterator callerArgsLookupTargetFunctionPointer = new ArgIterator(conversionInfo.ArgIteratorData,
conversionInfo.ArgIteratorData.HasThis() ?
CallingConvention.ManagedInstance :
CallingConvention.ManagedStatic,
conversionInfo.CallerHasParamType,
conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget,
conversionInfo.CallerForcedByRefData,
false, false);
// Find the last valid caller offset. That's the offset of the target function pointer.
int ofsCallerValid = TransitionBlock.InvalidOffset;
while (true)
{
// Setup argument offsets.
int ofsCallerTemp = callerArgsLookupTargetFunctionPointer.GetNextOffset();
// Check to see if we've handled all the arguments that we are to pass to the callee.
if (TransitionBlock.InvalidOffset == ofsCallerTemp)
break;
ofsCallerValid = ofsCallerTemp;
}
if (ofsCallerValid == TransitionBlock.InvalidOffset)
throw new InvalidProgramException();
int stackSizeCaller = callerArgsLookupTargetFunctionPointer.GetArgSize();
Debug.Assert(stackSizeCaller == IntPtr.Size);
void* pSrc = _callerTransitionBlock + ofsCallerValid;
IntPtr tempFunctionPointer = *((IntPtr*)pSrc);
forceCalleeHasParamType = UpdateCalleeFunctionPointer(tempFunctionPointer);
}
// Retrieve target function pointer and instantiation argument for delegate thunks
if (conversionInfo.IsDelegateThunk)
{
Debug.Assert(_callerArgs.HasThis() && !_conversionInfo.IsUnboxingThunk);
IntPtr locationOfThisPointer = (IntPtr)(_callerTransitionBlock + ArgIterator.GetThisOffset());
_delegateData._delegateObject = (Delegate)Unsafe.As<IntPtr, Object>(ref *(IntPtr*)locationOfThisPointer);
Debug.Assert(_delegateData._delegateObject != null);
RuntimeAugments.GetDelegateData(
_delegateData._delegateObject,
out _delegateData._firstParameter,
out _delegateData._helperObject,
out _delegateData._extraFunctionPointerOrData,
out _delegateData._functionPointer);
if (conversionInfo.TargetDelegateFunctionIsExtraFunctionPointerOrDataField)
{
if (conversionInfo.IsOpenInstanceDelegateThunk)
{
_delegateData._boxedFirstParameter = BoxedCallerFirstArgument;
_callerArgs.Reset();
IntPtr resolvedTargetFunctionPointer = OpenMethodResolver.ResolveMethod(_delegateData._extraFunctionPointerOrData, _delegateData._boxedFirstParameter);
forceCalleeHasParamType = UpdateCalleeFunctionPointer(resolvedTargetFunctionPointer);
}
else
{
forceCalleeHasParamType = UpdateCalleeFunctionPointer(_delegateData._extraFunctionPointerOrData);
}
}
else if (conversionInfo.IsMulticastDelegate)
{
_delegateData._multicastTargetCount = (int)_delegateData._extraFunctionPointerOrData;
}
}
//
// Setup output argument iterator for the callee
//
_calleeArgs = new ArgIterator(conversionInfo.ArgIteratorData,
(conversionInfo.ArgIteratorData.HasThis() && !conversionInfo.IsStaticDelegateThunk) ?
CallingConvention.ManagedInstance :
CallingConvention.ManagedStatic,
forceCalleeHasParamType || conversionInfo.CalleeHasParamType,
false,
conversionInfo.CalleeForcedByRefData,
conversionInfo.IsOpenInstanceDelegateThunk,
conversionInfo.IsClosedStaticDelegate);
// The function pointer, 'hasParamType', and 'hasThis' flags for the callee arg iterator need to be computed/read from the caller's
// input arguments in the case of a reflection invoker thunk (the target method pointer and 'hasThis' flags are
// passed in as parameters from the caller, not loaded from a static method signature in native layout)
if (conversionInfo.IsReflectionDynamicInvokerThunk)
ComputeCalleeFlagsAndFunctionPointerForReflectionInvokeThunk();
#if CALLINGCONVENTION_CALLEE_POPS
// Ensure that the count of bytes in the stack is available
_callerArgs.CbStackPop();
#endif
}
private void ComputeCalleeFlagsAndFunctionPointerForReflectionInvokeThunk()
{
Debug.Assert(_conversionInfo.IsReflectionDynamicInvokerThunk);
Debug.Assert(!_callerArgs.Equals(default(ArgIterator)) && !_calleeArgs.Equals(default(ArgIterator)));
_callerArgs.GetNextOffset(); // Skip thisPtr
{
int ofsCaller = _callerArgs.GetNextOffset(); // methodToCall
Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller);
void** pSrc = (void**)(_callerTransitionBlock + ofsCaller);
IntPtr functionPointer = new IntPtr(*pSrc);
bool forceCalleeHasParamType = UpdateCalleeFunctionPointer(functionPointer);
_calleeArgs.SetHasParamTypeAndReset(forceCalleeHasParamType);
}
_callerArgs.GetNextOffset(); // Skip argSetupState
// targetIsThisCall
{
int ofsCaller = _callerArgs.GetNextOffset(); // targetIsThisCall
Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller);
bool* pSrc = (bool*)(_callerTransitionBlock + ofsCaller);
bool targetIsThisCall = *pSrc;
_calleeArgs.SetHasThisAndReset(targetIsThisCall);
}
_callerArgs.Reset();
}
internal void ResetPinnedObjects()
{
// Reset all pinned gchandles to null.
// Freeing of gchandles is done in the destructor of GCHandleContainer when the thread dies.
s_pinnedGCHandles._thisPtrHandle.Target = null;
s_pinnedGCHandles._dynamicInvokeArgHandle.Target = null;
s_pinnedGCHandles._returnObjectHandle.Target = null;
}
private bool UpdateCalleeFunctionPointer(IntPtr newFunctionPointer)
{
if (FunctionPointerOps.IsGenericMethodPointer(newFunctionPointer))
{
GenericMethodDescriptor* genericTarget = FunctionPointerOps.ConvertToGenericDescriptor(newFunctionPointer);
_instantiatingStubArgument = genericTarget->InstantiationArgument;
_functionPointerToCall = genericTarget->MethodFunctionPointer;
return true;
}
else
{
_functionPointerToCall = newFunctionPointer;
return false;
}
}
internal void PrepareNextMulticastDelegateCall(int currentIndex)
{
if (!_conversionInfo.IsMulticastDelegate)
{
Environment.FailFast("Thunk is not a multicast delegate thunk!");
}
Debug.Assert(currentIndex < _delegateData._multicastTargetCount);
Debug.Assert(!_delegateData.Equals(default(DelegateData)));
Debug.Assert(_delegateData._helperObject is Delegate[]);
Debug.Assert(_delegateData._multicastTargetCount <= ((Delegate[])_delegateData._helperObject).Length);
Delegate[] delegateArray = (Delegate[])_delegateData._helperObject;
Delegate currentDelegate = delegateArray[currentIndex];
object helperObject;
IntPtr extraFunctionPointerOrData;
IntPtr functionPointer;
RuntimeAugments.GetDelegateData(currentDelegate, out _delegateData._multicastThisPointer, out helperObject, out extraFunctionPointerOrData, out functionPointer);
bool forceCalleeHasParamType = UpdateCalleeFunctionPointer(functionPointer);
_calleeArgs.SetHasParamTypeAndReset(forceCalleeHasParamType);
_callerArgs.Reset();
}
internal int MulticastDelegateCallCount
{
get
{
Debug.Assert(_conversionInfo.IsMulticastDelegate);
return _delegateData._multicastTargetCount;
}
}
private object BoxedCallerFirstArgument
{
// Get the first argument that will be passed to the callee (if available), and box it if it's a value type.
// The first argument is an actual explicit argument passed to the callee... i.e. not a thispointer or instantiationStubArg
// NOTE: This method advances the caller ArgIterator and does NOT reset it. It's up to whoever calls this method
// to reset the caller ArgIterator if it needs to be reset
get
{
int ofsCaller = _callerArgs.GetNextOffset();
if (TransitionBlock.InvalidOffset == ofsCaller)
return null;
byte* pSrc = _callerTransitionBlock + ofsCaller;
TypeHandle thArgType;
_callerArgs.GetArgType(out thArgType);
Debug.Assert(!thArgType.IsNull());
if (!thArgType.IsValueType())
{
Debug.Assert(_callerArgs.GetArgSize() == IntPtr.Size);
// For Open non-virtual calls to instance methods on valuetypes, the first argument
// is a byref parameter. In that case, pass null to the resolution function.
if (_callerArgs.IsArgPassedByRef())
return null;
Debug.Assert(!_callerArgs.IsArgPassedByRef());
return Unsafe.As<IntPtr, Object>(ref *(IntPtr*)pSrc);
}
else
{
RuntimeTypeHandle argEEType = thArgType.GetRuntimeTypeHandle();
if (_callerArgs.IsArgPassedByRef())
{
return RuntimeAugments.Box(argEEType, new IntPtr(*((void**)pSrc)));
}
else
{
return RuntimeAugments.Box(argEEType, new IntPtr(pSrc));
}
}
}
}
internal IntPtr ClosedStaticDelegateThisPointer
{
get
{
Debug.Assert(_conversionInfo.IsClosedStaticDelegate && !_delegateData.Equals(default(DelegateData)));
Debug.Assert(_delegateData._helperObject != null);
s_pinnedGCHandles._thisPtrHandle.Target = _delegateData._helperObject;
return s_pinnedGCHandles._thisPtrHandle.GetRawTargetAddress();
}
}
internal void* ThisPointer
{
get
{
if (_conversionInfo.IsStaticDelegateThunk)
return null;
if (_callerArgs.HasThis() != _calleeArgs.HasThis())
{
// Note: the _callerArgs for a reflection dynamic invoker thunk will never have a thisPtr
// because it's a static method. The _calleeArgs may have a thisPtr if the target method
// being called is an instance method.
if (!_conversionInfo.IsReflectionDynamicInvokerThunk)
{
// Whether or not a given signature has a this parameter is not allowed to change across this thunk.
Environment.FailFast("HasThis on signatures must match");
}
}
if (_calleeArgs.HasThis())
{
void* thisPointer = null;
if (_conversionInfo.IsThisPointerInDelegateData || _conversionInfo.IsAnyDynamicInvokerThunk)
{
// Assert that we have extracted the delegate data
Debug.Assert(_conversionInfo.IsReflectionDynamicInvokerThunk || !_delegateData.Equals(default(DelegateData)));
if (_conversionInfo.IsAnyDynamicInvokerThunk || _conversionInfo.IsOpenInstanceDelegateThunk)
{
// Resilience to multiple or out of order calls
_callerArgs.Reset();
int ofsCaller = _callerArgs.GetNextOffset();
Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller);
void** pSrc = (void**)(_callerTransitionBlock + ofsCaller);
// No need to pin since the thisPtr is one of the arguments on the caller TB
return *pSrc;
}
else if (_conversionInfo.IsMulticastDelegate)
{
Debug.Assert(_delegateData._multicastThisPointer != null);
s_pinnedGCHandles._thisPtrHandle.Target = _delegateData._multicastThisPointer;
}
else
{
Debug.Assert(_delegateData._helperObject != null);
s_pinnedGCHandles._thisPtrHandle.Target = _delegateData._helperObject;
}
thisPointer = (void*)s_pinnedGCHandles._thisPtrHandle.GetRawTargetAddress();
}
else
{
thisPointer = *((void**)(_callerTransitionBlock + ArgIterator.GetThisOffset()));
if (_conversionInfo.IsUnboxingThunk)
{
thisPointer = (void*)(((IntPtr*)thisPointer) + 1);
}
}
return thisPointer;
}
return null;
}
}
internal void* CallerReturnBuffer
{
get
{
// If the return buffer is treated the same way for both calling conventions
if (_callerArgs.HasRetBuffArg() == _calleeArgs.HasRetBuffArg())
{
// Do nothing, or copy the ret buf arg around
if (_callerArgs.HasRetBuffArg())
{
return *((void**)(_callerTransitionBlock + _callerArgs.GetRetBuffArgOffset()));
}
}
else
{
// We'll need to create a return buffer, or assign into the return buffer when the actual call completes.
if (_calleeArgs.HasRetBuffArg())
{
TypeHandle thRetType;
bool forceByRefUnused;
void* callerRetBuffer = null;
if (_conversionInfo.IsAnyDynamicInvokerThunk)
{
// In the case of dynamic invoke thunks that use return buffers, we need to allocate a buffer for the return
// value, of the same type as the return value type handle in the callee's arguments.
Debug.Assert(!_callerArgs.HasRetBuffArg());
CorElementType returnType = _calleeArgs.GetReturnType(out thRetType, out forceByRefUnused);
Debug.Assert(!thRetType.IsNull());
RuntimeTypeHandle returnValueType = thRetType.IsValueType() ? thRetType.GetRuntimeTypeHandle() : typeof(object).TypeHandle;
s_pinnedGCHandles._returnObjectHandle.Target = RuntimeAugments.RawNewObject(returnValueType);
// The transition block has a space reserved for storing return buffer data. This is protected conservatively.
// Copy the address of the allocated object to the protected memory to be able to safely unpin it.
callerRetBuffer = _callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock();
*((void**)callerRetBuffer) = (void*)s_pinnedGCHandles._returnObjectHandle.GetRawTargetAddress();
// Unpin the allocated object (it's now protected in the caller's conservatively reported memory space)
s_pinnedGCHandles._returnObjectHandle.Target = null;
// Point the callerRetBuffer to the begining of the actual object's data (skipping the EETypePtr slot)
callerRetBuffer = (void*)(new IntPtr(*((void**)callerRetBuffer)) + IntPtr.Size);
}
else
{
// The transition block has a space reserved for storing return buffer data. This is protected conservatively
callerRetBuffer = _callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock();
// Make sure buffer is nulled out, and setup the return buffer location.
CorElementType returnType = _callerArgs.GetReturnType(out thRetType, out forceByRefUnused);
int returnSize = TypeHandle.GetElemSize(returnType, thRetType);
CallConverterThunk.memzeroPointerAligned((byte*)callerRetBuffer, returnSize);
}
Debug.Assert(callerRetBuffer != null);
return callerRetBuffer;
}
}
return null;
}
}
internal void* VarArgSigCookie
{
get
{
if (_calleeArgs.IsVarArg() != _callerArgs.IsVarArg())
{
// Whether or not a given signature has a this parameter is not allowed to change across this thunk.
Environment.FailFast("IsVarArg on signatures must match");
}
if (_calleeArgs.IsVarArg())
{
return *((void**)(_callerTransitionBlock + _callerArgs.GetVASigCookieOffset()));
}
return null;
}
}
internal IntPtr InstantiatingStubArgument
{
get
{
if (_calleeArgs.HasParamType() == _callerArgs.HasParamType())
{
if (_calleeArgs.HasParamType())
{
return new IntPtr(*((void**)(_callerTransitionBlock + _callerArgs.GetParamTypeArgOffset())));
}
}
else if (_calleeArgs.HasParamType())
{
Debug.Assert(_instantiatingStubArgument != IntPtr.Zero);
return _instantiatingStubArgument;
}
else
{
// Whether or not a given signature has a this parameter is not allowed to change across this thunk.
Environment.FailFast("Uninstantiating thunks are not allowed");
}
return IntPtr.Zero;
}
}
internal IntPtr FunctionPointerToCall
{
get
{
if (_conversionInfo.IsDelegateDynamicInvokeThunk)
{
// Resilience to multiple or out of order calls
{
_callerArgs.Reset();
_callerArgs.GetNextOffset(); // thisPtr
}
int ofsCaller = _callerArgs.GetNextOffset(); // methodToCall
Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller);
void** pSrc = (void**)(_callerTransitionBlock + ofsCaller);
return new IntPtr(*pSrc);
}
return _functionPointerToCall;
}
}
internal IntPtr InvokeObjectArrayDelegate(object[] arguments)
{
if (!_conversionInfo.IsObjectArrayDelegateThunk)
Environment.FailFast("Thunk is not an object array delegate thunk!");
Debug.Assert(!_delegateData.Equals(default(DelegateData)));
Func<object[], object> targetDelegate = _delegateData._helperObject as Func<object[], object>;
Debug.Assert(targetDelegate != null);
object result = targetDelegate(arguments ?? Array.Empty<object>());
TypeHandle thArgType;
bool forceByRefUnused;
_calleeArgs.GetReturnType(out thArgType, out forceByRefUnused);
Debug.Assert(!thArgType.IsNull());
unsafe
{
if (thArgType.IsValueType() && thArgType.GetRuntimeTypeHandle().ToEETypePtr()->IsNullable)
{
object nullableObj = RuntimeAugments.RawNewObject(thArgType.GetRuntimeTypeHandle());
s_pinnedGCHandles._returnObjectHandle.Target = nullableObj;
if (result != null)
{
RuntimeAugments.StoreValueTypeField(ref RuntimeAugments.GetRawData(nullableObj), result, thArgType.GetRuntimeTypeHandle());
}
}
else
{
s_pinnedGCHandles._returnObjectHandle.Target = result;
}
}
return s_pinnedGCHandles._returnObjectHandle.GetRawTargetAddress();
}
internal IntPtr GetArgSetupStateDataPointer()
{
if (!_conversionInfo.IsAnyDynamicInvokerThunk)
Environment.FailFast("Thunk is not a valid dynamic invoker thunk!");
// Resilience to multiple or out of order calls
{
_callerArgs.Reset();
_callerArgs.GetNextOffset(); // thisPtr
_callerArgs.GetNextOffset(); // methodToCall
}
int ofsCaller = _callerArgs.GetNextOffset(); //argSetupState
Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller);
void** pSrc = (void**)(_callerTransitionBlock + ofsCaller);
// No need to pin since the argSetupState is one of the arguments on the caller TB
return new IntPtr(*pSrc);
}
}
}
| |
// 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.AcceptanceTestsHttp
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for HttpRedirects.
/// </summary>
public static partial class HttpRedirectsExtensions
{
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HttpRedirectsHead300Headers Head300(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Head300Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsHead300Headers> Head300Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head300WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IList<string> Get300(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Get300Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 300 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<string>> Get300Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get300WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HttpRedirectsHead301Headers Head301(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Head301Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsHead301Headers> Head301Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head301WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HttpRedirectsGet301Headers Get301(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Get301Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 301 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsGet301Headers> Get301Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get301WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Put true Boolean value in request returns 301. This request should not be
/// automatically redirected, but should return the received 301 to the caller
/// for evaluation
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static HttpRedirectsPut301Headers Put301(this IHttpRedirects operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Put301Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put true Boolean value in request returns 301. This request should not be
/// automatically redirected, but should return the received 301 to the caller
/// for evaluation
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsPut301Headers> Put301Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Put301WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HttpRedirectsHead302Headers Head302(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Head302Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsHead302Headers> Head302Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head302WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HttpRedirectsGet302Headers Get302(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Get302Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Return 302 status code and redirect to /http/success/200
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsGet302Headers> Get302Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get302WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Patch true Boolean value in request returns 302. This request should not
/// be automatically redirected, but should return the received 302 to the
/// caller for evaluation
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static HttpRedirectsPatch302Headers Patch302(this IHttpRedirects operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Patch302Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch true Boolean value in request returns 302. This request should not
/// be automatically redirected, but should return the received 302 to the
/// caller for evaluation
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsPatch302Headers> Patch302Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Patch302WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Post true Boolean value in request returns 303. This request should be
/// automatically redirected usign a get, ultimately returning a 200 status
/// code
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static HttpRedirectsPost303Headers Post303(this IHttpRedirects operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Post303Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post true Boolean value in request returns 303. This request should be
/// automatically redirected usign a get, ultimately returning a 200 status
/// code
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsPost303Headers> Post303Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Post303WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Redirect with 307, resulting in a 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HttpRedirectsHead307Headers Head307(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Head307Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Redirect with 307, resulting in a 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsHead307Headers> Head307Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Head307WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Redirect get with 307, resulting in a 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static HttpRedirectsGet307Headers Get307(this IHttpRedirects operations)
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Get307Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Redirect get with 307, resulting in a 200 success
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsGet307Headers> Get307Async(this IHttpRedirects operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Get307WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Put redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static HttpRedirectsPut307Headers Put307(this IHttpRedirects operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Put307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsPut307Headers> Put307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Put307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Patch redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static HttpRedirectsPatch307Headers Patch307(this IHttpRedirects operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Patch307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsPatch307Headers> Patch307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Patch307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Post redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static HttpRedirectsPost307Headers Post307(this IHttpRedirects operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Post307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Post redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsPost307Headers> Post307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Post307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Delete redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
public static HttpRedirectsDelete307Headers Delete307(this IHttpRedirects operations, bool? booleanValue = default(bool?))
{
return Task.Factory.StartNew(s => ((IHttpRedirects)s).Delete307Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete redirected with 307, resulting in a 200 after redirect
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<HttpRedirectsDelete307Headers> Delete307Async(this IHttpRedirects operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.Delete307WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
}
}
| |
//
// ItunesPlayerImportDialogs.cs
//
// Author:
// Scott Peterson <lunchtimemama@gmail.com>
//
// Copyright (C) 2007 Scott Peterson
//
// 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 Gtk;
using Mono.Unix;
using Banshee.Base;
namespace Banshee.PlayerMigration
{
public class ItunesImportDialog : Dialog
{
private string library_uri;
protected readonly Button import_button;
protected readonly CheckButton ratings;
protected readonly CheckButton stats;
protected readonly CheckButton playlists;
public string LibraryUri
{
get { return library_uri; }
}
public bool Ratings
{
get { return ratings.Active; }
}
public bool Stats
{
get { return stats.Active; }
}
public bool Playliststs
{
get { return playlists.Active; }
}
public ItunesImportDialog () : base ()
{
// TODO add Help button and dialog/tooltip
Title = Catalog.GetString ("iTunes Importer");
Resizable = false;
VBox.BorderWidth = 8;
VBox.Spacing = 8;
Button cancel_button = new Button (Stock.Cancel);
cancel_button.Clicked += delegate { Respond (ResponseType.Cancel); };
cancel_button.ShowAll ();
AddActionWidget (cancel_button, ResponseType.Cancel);
cancel_button.CanDefault = true;
cancel_button.GrabFocus ();
DefaultResponse = ResponseType.Cancel;
import_button = new Button ();
import_button.Label = Catalog.GetString ("_Import");
import_button.UseUnderline = true;
import_button.Image = Image.NewFromIconName (Stock.Open, IconSize.Button);
import_button.Clicked += delegate { Respond (ResponseType.Ok); };
import_button.ShowAll ();
AddActionWidget (import_button, ResponseType.Ok);
VBox vbox = new VBox ();
ratings = new CheckButton (Catalog.GetString ("Import song ratings"));
ratings.Active = true;
vbox.PackStart (ratings);
stats = new CheckButton (Catalog.GetString ("Import play statistics (playcount, etc.)"));
stats.Active = true;
vbox.PackStart (stats);
playlists = new CheckButton (Catalog.GetString ("Import playlists"));
playlists.Active = true;
vbox.PackStart (playlists);
PackCheckboxes (vbox);
VBox.ShowAll ();
}
protected virtual void PackCheckboxes (VBox vbox)
{
string possible_location = System.IO.Path.Combine (System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), "iTunes"),
ItunesPlayerImportSource.LibraryFilename);
if (Banshee.IO.File.Exists (new SafeUri (possible_location))) {
library_uri = possible_location;
} else {
HBox hbox = new HBox ();
hbox.Spacing = 8;
Image image = new Image (IconTheme.Default.LoadIcon ("gtk-open", 18, 0));
hbox.PackStart (image);
Label label1 = new Label ();
label1.Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText(
String.Format( Catalog.GetString (@"Locate your ""{0}"" file..."),
ItunesPlayerImportSource.LibraryFilename)));
label1.SetAlignment (0.0f, 0.5f);
hbox.PackStart (label1);
Button browse_button = new Button (hbox);
browse_button.Clicked += OnBrowseButtonClicked;
VBox.PackStart (browse_button);
ratings.Sensitive = stats.Sensitive = playlists.Sensitive = import_button.Sensitive = false;
}
VBox.PackStart (vbox);
}
private void OnBrowseButtonClicked (object o, EventArgs args)
{
Button browse_button = o as Button;
using(FileChooserDialog file_chooser = new FileChooserDialog(
String.Format (Catalog.GetString (@"Locate ""{0}"""), ItunesPlayerImportSource.LibraryFilename),
this, FileChooserAction.Open,
Stock.Cancel, ResponseType.Cancel,
Stock.Open, ResponseType.Ok)) {
FileFilter filter = new FileFilter ();
filter.AddPattern ("*" + ItunesPlayerImportSource.LibraryFilename);
filter.Name = ItunesPlayerImportSource.LibraryFilename;
file_chooser.AddFilter (filter);
if (file_chooser.Run () == (int)ResponseType.Ok) {
browse_button.Sensitive = false;
ratings.Sensitive = stats.Sensitive = playlists.Sensitive = import_button.Sensitive = true;
library_uri = file_chooser.Filename;
}
file_chooser.Destroy ();
}
}
}
public class ItunesMusicDirectoryDialog : Dialog
{
private FileChooserWidget chooser;
public string UserMusicDirectory {
get { return chooser.Filename; }
}
public ItunesMusicDirectoryDialog (string itunes_music_directory) : base ()
{
Title = Catalog.GetString ("Locate iTunes Music Directory");
HeightRequest = 650;
WidthRequest = 814;
Button cancel_button = new Button (Stock.Cancel);
cancel_button.Clicked += delegate { Respond (ResponseType.Cancel); };
cancel_button.ShowAll ();
AddActionWidget (cancel_button, ResponseType.Cancel);
cancel_button.CanDefault = true;
cancel_button.GrabFocus ();
Button ok_button = new Button (Stock.Ok);
ok_button.Clicked += delegate { Respond (ResponseType.Ok); };
ok_button.ShowAll ();
AddActionWidget (ok_button, ResponseType.Ok);
VBox vbox = new VBox ();
vbox.BorderWidth = 8;
vbox.Spacing = 10;
HBox hbox = new HBox ();
hbox.Spacing = 10;
Image image = new Image (Stock.DialogWarning, IconSize.Dialog);
hbox.PackStart (image, false, true, 0);
Label message = new Label ();
message.Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText(
String.Format (Catalog.GetString(
"The iTunes library refers to your music directory as \"{0}\" but " +
"Banshee was not able to infer the location of this directory. Please locate it."),
itunes_music_directory)));
message.Justify = Justification.Left;
message.WidthRequest = 750;
message.LineWrap = true;
hbox.PackStart (message, true, true, 0);
vbox.PackStart (hbox, false, true, 0);
chooser = new FileChooserWidget (FileChooserAction.SelectFolder);
chooser.ShowAll ();
vbox.PackStart (chooser, true, true, 0);
VBox.PackStart (vbox);
DefaultResponse = ResponseType.Cancel;
VBox.ShowAll ();
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript {
using System;
using System.Reflection;
using System.Reflection.Emit;
internal abstract class EnumWrapper : IConvertible{
internal abstract Object value {
get;
}
internal abstract Type type {
get;
}
internal abstract String name {
get;
}
internal virtual IReflect classScopeOrType {
get {
return this.type;
}
}
TypeCode IConvertible.GetTypeCode(){
return Convert.GetTypeCode(this.value);
}
bool IConvertible.ToBoolean(IFormatProvider provider){
return ((IConvertible)this.value).ToBoolean(provider);
}
char IConvertible.ToChar(IFormatProvider provider){
return ((IConvertible)this.value).ToChar(provider);
}
sbyte IConvertible.ToSByte(IFormatProvider provider){
return ((IConvertible)this.value).ToSByte(provider);
}
byte IConvertible.ToByte(IFormatProvider provider){
return ((IConvertible)this.value).ToByte(provider);
}
short IConvertible.ToInt16(IFormatProvider provider){
return ((IConvertible)this.value).ToInt16(provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider){
return ((IConvertible)this.value).ToUInt16(provider);
}
int IConvertible.ToInt32(IFormatProvider provider){
return ((IConvertible)this.value).ToInt32(provider);
}
uint IConvertible.ToUInt32(IFormatProvider provider){
return ((IConvertible)this.value).ToUInt32(provider);
}
long IConvertible.ToInt64(IFormatProvider provider){
return ((IConvertible)this.value).ToInt64(provider);
}
ulong IConvertible.ToUInt64(IFormatProvider provider){
return ((IConvertible)this.value).ToUInt64(provider);
}
float IConvertible.ToSingle(IFormatProvider provider){
return ((IConvertible)this.value).ToSingle(provider);
}
double IConvertible.ToDouble(IFormatProvider provider){
return ((IConvertible)this.value).ToDouble(provider);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider){
return ((IConvertible)this.value).ToDecimal(provider);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider){
return ((IConvertible)this.value).ToDateTime(provider);
}
String IConvertible.ToString(IFormatProvider provider){
return ((IConvertible)this.value).ToString(provider);
}
Object IConvertible.ToType(Type conversionType, IFormatProvider provider){
return ((IConvertible)this.value).ToType(conversionType, provider);
}
internal Object ToNumericValue(){
return this.value;
}
public override String ToString(){
if (this.name != null) return this.name;
FieldInfo[] fields = this.type.GetFields(BindingFlags.Static|BindingFlags.Public);
foreach (FieldInfo field in fields)
if (StrictEquality.JScriptStrictEquals(this.value, field.GetValue(null))) return field.Name;
return Convert.ToString(this.value);
}
}
internal sealed class DeclaredEnumValue : EnumWrapper {
private String _name;
internal ClassScope _classScope;
internal Object _value;
internal DeclaredEnumValue(Object value, String name, ClassScope classScope){
this._name = name;
this._classScope = classScope;
this._value = value;
}
internal override Object value {
get {
return this._value;
}
}
internal override Type type {
get {
return this._classScope.GetTypeBuilderOrEnumBuilder();
}
}
internal override String name {
get {
return this._name;
}
}
internal override IReflect classScopeOrType {
get {
return this._classScope;
}
}
internal void CoerceToBaseType(Type bt, Context errCtx){
Object val = 0;
AST pval = ((AST)this.value).PartiallyEvaluate();
if (pval is ConstantWrapper)
val = ((ConstantWrapper)pval).Evaluate();
else
pval.context.HandleError(JSError.NotConst);
try{
this._value = Convert.CoerceT(val, bt);
}catch{
errCtx.HandleError(JSError.TypeMismatch);
this._value = Convert.CoerceT(0, bt);
}
}
}
internal sealed class MetadataEnumValue : EnumWrapper {
private Type _type;
private Object _value;
internal static Object GetEnumValue(Type type, Object value) {
Debug.Assert(type.IsEnum);
if (!type.Assembly.ReflectionOnly)
return Enum.ToObject(type, value);
return new MetadataEnumValue(type, value);
}
private MetadataEnumValue(Type type, Object value) {
this._type = type;
this._value = value;
}
internal override Object value {
get {
return this._value;
}
}
internal override Type type {
get {
return this._type;
}
}
internal override String name {
get {
String name = Enum.GetName(this._type, this._value);
if (name == null)
name = this._value.ToString();
return name;
}
}
}
}
| |
// Support for using externally created native textures, from Unity 4.2 upwards
#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0
#define AVPROWINDOWSMEDIA_UNITYFEATURE_EXTERNALTEXTURES
#endif
// Support for DirectX and OpenGL native texture updating, from Unity 4.0 upwards
#if UNITY_5_0 || UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0
#define AVPRO_UNITY_4_X
#endif
// Support for linear gamma, from Unity 3.5 upwards
#if AVPRO_UNITY_4_X || UNITY_3_5
#define AVPRO_UNITY_LINEARGAMMA
#endif
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System;
using System.Text;
using System.Runtime.InteropServices;
//-----------------------------------------------------------------------------
// Copyright 2012-2015 RenderHeads Ltd. All rights reserved.
//-----------------------------------------------------------------------------
[AddComponentMenu("AVPro Windows Media/Manager (required)")]
public class AVProWindowsMediaManager : MonoBehaviour
{
private static AVProWindowsMediaManager _instance;
// Format conversion
public Shader _shaderBGRA32;
public Shader _shaderYUY2;
public Shader _shaderYUY2_709;
public Shader _shaderUYVY;
public Shader _shaderYVYU;
public Shader _shaderHDYC;
public Shader _shaderNV12;
public Shader _shaderCopy;
public Shader _shaderHap_YCoCg;
private bool _isInitialised;
[HideInInspector] public bool _useExternalTextures = false;
//-------------------------------------------------------------------------
public static AVProWindowsMediaManager Instance
{
get
{
if (_instance == null)
{
_instance = (AVProWindowsMediaManager)GameObject.FindObjectOfType(typeof(AVProWindowsMediaManager));
if (_instance == null)
{
Debug.LogError("AVProWindowsMediaManager component required");
return null;
}
else
{
if (!_instance._isInitialised)
_instance.Init();
}
}
return _instance;
}
}
//-------------------------------------------------------------------------
void Awake()
{
if (!_isInitialised)
{
_instance = this;
Init();
}
}
void OnDestroy()
{
Deinit();
}
protected bool Init()
{
try
{
if (AVProWindowsMediaPlugin.Init())
{
Debug.Log("[AVProWindowsMedia] version " + AVProWindowsMediaPlugin.GetPluginVersion().ToString("F2") + " initialised");
}
else
{
Debug.LogError("[AVProWindowsMedia] failed to initialise.");
this.enabled = false;
Deinit();
return false;
}
}
catch (System.DllNotFoundException e)
{
Debug.Log("[AVProWindowsMedia] Unity couldn't find the DLL, did you move the 'Plugins' folder to the root of your project?");
throw e;
}
GetConversionMethod();
SetUnityFeatures();
// StartCoroutine("FinalRenderCapture");
_isInitialised = true;
return _isInitialised;
}
private void SetUnityFeatures()
{
#if !AVPROWINDOWSMEDIA_UNITYFEATURE_EXTERNALTEXTURES
_useExternalTextures = false;
#endif
AVProWindowsMediaPlugin.SetUnityFeatures(_useExternalTextures);
}
private void GetConversionMethod()
{
bool swapRedBlue = false;
if (SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 11"))
{
#if UNITY_5_0
// DX11 has red and blue channels swapped around
if (!SystemInfo.SupportsTextureFormat(TextureFormat.BGRA32))
swapRedBlue = true;
#else
swapRedBlue = true;
#endif
}
if (swapRedBlue)
{
Shader.DisableKeyword("SWAP_RED_BLUE_OFF");
Shader.EnableKeyword("SWAP_RED_BLUE_ON");
}
else
{
Shader.DisableKeyword("SWAP_RED_BLUE_ON");
Shader.EnableKeyword("SWAP_RED_BLUE_OFF");
}
Shader.DisableKeyword("AVPRO_GAMMACORRECTION");
Shader.EnableKeyword("AVPRO_GAMMACORRECTION_OFF");
#if AVPRO_UNITY_LINEARGAMMA
if (QualitySettings.activeColorSpace == ColorSpace.Linear)
{
Shader.DisableKeyword("AVPRO_GAMMACORRECTION_OFF");
Shader.EnableKeyword("AVPRO_GAMMACORRECTION");
}
#endif
}
private IEnumerator FinalRenderCapture()
{
while (Application.isPlaying)
{
GL.IssuePluginEvent(AVProWindowsMediaPlugin.PluginID | (int)AVProWindowsMediaPlugin.PluginEvent.UpdateAllTextures);
yield return new WaitForEndOfFrame();
}
}
void Update()
{
GL.IssuePluginEvent(AVProWindowsMediaPlugin.PluginID | (int)AVProWindowsMediaPlugin.PluginEvent.UpdateAllTextures);
}
public void Deinit()
{
// Clean up any open movies
AVProWindowsMediaMovie[] movies = (AVProWindowsMediaMovie[])FindObjectsOfType(typeof(AVProWindowsMediaMovie));
if (movies != null && movies.Length > 0)
{
for (int i = 0; i < movies.Length; i++)
{
movies[i].UnloadMovie();
}
}
_instance = null;
_isInitialised = false;
AVProWindowsMediaPlugin.Deinit();
}
public Shader GetPixelConversionShader(AVProWindowsMediaPlugin.VideoFrameFormat format, bool useBT709)
{
Shader result = null;
switch (format)
{
case AVProWindowsMediaPlugin.VideoFrameFormat.YUV_422_YUY2:
result = _shaderYUY2;
if (useBT709)
result = _shaderYUY2_709;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.YUV_422_UYVY:
result = _shaderUYVY;
if (useBT709)
result = _shaderHDYC;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.YUV_422_YVYU:
result = _shaderYVYU;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.YUV_422_HDYC:
result = _shaderHDYC;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.YUV_420_NV12:
result = _shaderNV12;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.Hap_RGB:
result = _shaderCopy;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.Hap_RGBA:
result = _shaderCopy;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.Hap_RGB_HQ:
result = _shaderHap_YCoCg;
break;
case AVProWindowsMediaPlugin.VideoFrameFormat.RAW_BGRA32:
result= _shaderBGRA32;
break;
default:
Debug.LogError("[AVProWindowsMedia] Unknown pixel format '" + format);
break;
}
return result;
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Non-generic interface for all members whose signatures don't require knowledge of
/// the type being built. The generic interface extends this one. Some methods return
/// either an IBuilder or an IMessage; in these cases the generic interface redeclares
/// the same method with a type-specific signature. Implementations are encouraged to
/// use explicit interface implemenation for the non-generic form. This mirrors
/// how IEnumerable and IEnumerable<T> work.
/// </summary>
public interface IBuilder : IBuilderLite
{
/// <summary>
/// Returns true iff all required fields in the message and all
/// embedded messages are set.
/// </summary>
new bool IsInitialized { get; }
/// <summary>
/// Only present in the nongeneric interface - useful for tests, but
/// not as much in real life.
/// </summary>
IBuilder SetField(FieldDescriptor field, object value);
/// <summary>
/// Only present in the nongeneric interface - useful for tests, but
/// not as much in real life.
/// </summary>
IBuilder SetRepeatedField(FieldDescriptor field, int index, object value);
/// <summary>
/// Behaves like the equivalent property in IMessage<T>.
/// The returned map may or may not reflect future changes to the builder.
/// Either way, the returned map is unmodifiable.
/// </summary>
IDictionary<FieldDescriptor, object> AllFields { get; }
/// <summary>
/// Allows getting and setting of a field.
/// <see cref="IMessage{TMessage, TBuilder}.Item(FieldDescriptor)"/>
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
object this[FieldDescriptor field] { get; set; }
/// <summary>
/// Get the message's type descriptor.
/// <see cref="IMessage{TMessage, TBuilder}.DescriptorForType"/>
/// </summary>
MessageDescriptor DescriptorForType { get; }
/// <summary>
/// <see cref="IMessage{TMessage, TBuilder}.GetRepeatedFieldCount"/>
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
int GetRepeatedFieldCount(FieldDescriptor field);
/// <summary>
/// Allows getting and setting of a repeated field value.
/// <see cref="IMessage{TMessage, TBuilder}.Item(FieldDescriptor, int)"/>
/// </summary>
object this[FieldDescriptor field, int index] { get; set; }
/// <summary>
/// <see cref="IMessage{TMessage, TBuilder}.HasField"/>
/// </summary>
bool HasField(FieldDescriptor field);
/// <summary>
/// <see cref="IMessage{TMessage, TBuilder}.UnknownFields"/>
/// </summary>
UnknownFieldSet UnknownFields { get; set; }
/// <summary>
/// Create a builder for messages of the appropriate type for the given field.
/// Messages built with this can then be passed to the various mutation properties
/// and methods.
/// </summary>
IBuilder CreateBuilderForField(FieldDescriptor field);
#region Methods which are like those of the generic form, but without any knowledge of the type parameters
IBuilder WeakAddRepeatedField(FieldDescriptor field, object value);
new IBuilder WeakClear();
IBuilder WeakClearField(FieldDescriptor field);
IBuilder WeakMergeFrom(IMessage message);
new IBuilder WeakMergeFrom(ByteString data);
new IBuilder WeakMergeFrom(ByteString data, ExtensionRegistry registry);
new IBuilder WeakMergeFrom(ICodedInputStream input);
new IBuilder WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry);
new IMessage WeakBuild();
new IMessage WeakBuildPartial();
new IBuilder WeakClone();
new IMessage WeakDefaultInstanceForType { get; }
#endregion
}
/// <summary>
/// Interface implemented by Protocol Message builders.
/// TODO(jonskeet): Consider "SetXXX" methods returning the builder, as well as the properties.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <typeparam name="TBuilder">Type of builder</typeparam>
public interface IBuilder<TMessage, TBuilder> : IBuilder, IBuilderLite<TMessage, TBuilder>
where TMessage : IMessage<TMessage, TBuilder>
where TBuilder : IBuilder<TMessage, TBuilder>
{
TBuilder SetUnknownFields(UnknownFieldSet unknownFields);
/// <summary>
/// Resets all fields to their default values.
/// </summary>
new TBuilder Clear();
/// <summary>
/// Merge the specified other message which may be a different implementation of
/// the same message descriptor.
/// </summary>
TBuilder MergeFrom(IMessage other);
/// <summary>
/// Constructs the final message. Once this is called, this Builder instance
/// is no longer valid, and calling any other method may throw a
/// NullReferenceException. If you need to continue working with the builder
/// after calling Build, call Clone first.
/// </summary>
/// <exception cref="UninitializedMessageException">the message
/// is missing one or more required fields; use BuildPartial to bypass
/// this check</exception>
new TMessage Build();
/// <summary>
/// Like Build(), but does not throw an exception if the message is missing
/// required fields. Instead, a partial message is returned.
/// </summary>
new TMessage BuildPartial();
/// <summary>
/// Clones this builder.
/// TODO(jonskeet): Explain depth of clone.
/// </summary>
new TBuilder Clone();
/// <summary>
/// Parses a message of this type from the input and merges it with this
/// message, as if using MergeFrom(IMessage<T>).
/// </summary>
/// <remarks>
/// Warning: This does not verify that all required fields are present
/// in the input message. If you call Build() without setting all
/// required fields, it will throw an UninitializedMessageException.
/// There are a few good ways to deal with this:
/// <list>
/// <item>Call IsInitialized to verify to verify that all required fields are
/// set before building.</item>
/// <item>Parse the message separately using one of the static ParseFrom
/// methods, then use MergeFrom(IMessage<T>) to merge it with
/// this one. ParseFrom will throw an InvalidProtocolBufferException
/// (an IOException) if some required fields are missing.
/// Use BuildPartial to build, which ignores missing required fields.
/// </list>
/// </remarks>
new TBuilder MergeFrom(ICodedInputStream input);
/// <summary>
/// Like MergeFrom(ICodedInputStream), but also parses extensions.
/// The extensions that you want to be able to parse must be registered
/// in <paramref name="extensionRegistry"/>. Extensions not in the registry
/// will be treated as unknown fields.
/// </summary>
new TBuilder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry);
/// <summary>
/// Get's the message's type's default instance.
/// <see cref="IMessage{TMessage}.DefaultInstanceForType" />
/// </summary>
new TMessage DefaultInstanceForType { get; }
/// <summary>
/// Clears the field. This is exactly equivalent to calling the generated
/// Clear method corresponding to the field.
/// </summary>
/// <param name="field"></param>
/// <returns></returns>
TBuilder ClearField(FieldDescriptor field);
/// <summary>
/// Appends the given value as a new element for the specified repeated field.
/// </summary>
/// <exception cref="ArgumentException">the field is not a repeated field,
/// the field does not belong to this builder's type, or the value is
/// of the incorrect type
/// </exception>
TBuilder AddRepeatedField(FieldDescriptor field, object value);
/// <summary>
/// Merge some unknown fields into the set for this message.
/// </summary>
TBuilder MergeUnknownFields(UnknownFieldSet unknownFields);
/// <summary>
/// Like MergeFrom(Stream), but does not read until the end of the file.
/// Instead, the size of the message (encoded as a varint) is read first,
/// then the message data. Use Message.WriteDelimitedTo(Stream) to
/// write messages in this format.
/// </summary>
/// <param name="input"></param>
new TBuilder MergeDelimitedFrom(Stream input);
/// <summary>
/// Like MergeDelimitedFrom(Stream) but supporting extensions.
/// </summary>
new TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry);
#region Convenience methods
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(ICodedInputStream).
/// </summary>
new TBuilder MergeFrom(ByteString data);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(ICodedInputStream, extensionRegistry).
/// </summary>
new TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(ICodedInputStream).
/// </summary>
new TBuilder MergeFrom(byte[] data);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(ICodedInputStream, extensionRegistry).
/// </summary>
new TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry);
/// <summary>
/// Parse <paramref name="input"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(ICodedInputStream). Note that this method always reads
/// the entire input (unless it throws an exception). If you want it to
/// stop earlier, you will need to wrap the input in a wrapper
/// stream which limits reading. Or, use IMessage.WriteDelimitedTo(Stream)
/// to write your message and MmergeDelimitedFrom(Stream) to read it.
/// Despite usually reading the entire stream, this method never closes the stream.
/// </summary>
new TBuilder MergeFrom(Stream input);
/// <summary>
/// Parse <paramref name="input"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(ICodedInputStream, extensionRegistry).
/// </summary>
new TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry);
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace APIcheck
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
public class JSON
{
public const int TOKEN_NONE = 0;
public const int TOKEN_CURLY_OPEN = 1;
public const int TOKEN_CURLY_CLOSE = 2;
public const int TOKEN_SQUARED_OPEN = 3;
public const int TOKEN_SQUARED_CLOSE = 4;
public const int TOKEN_COLON = 5;
public const int TOKEN_COMMA = 6;
public const int TOKEN_STRING = 7;
public const int TOKEN_NUMBER = 8;
public const int TOKEN_TRUE = 9;
public const int TOKEN_FALSE = 10;
public const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object JsonDecode(string json)
{
bool success = true;
return JsonDecode(json, ref success);
}
/// <summary>
/// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
/// </summary>
/// <param name="json">A JSON string.</param>
/// <param name="success">Successful parse?</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object JsonDecode(string json, ref bool success)
{
success = true;
if (json != null) {
char[] charArray = json.ToCharArray();
int index = 0;
object value = ParseValue(charArray, ref index, ref success);
return value;
} else {
return null;
}
}
/// <summary>
/// Converts a Hashtable / ArrayList object into a JSON string
/// </summary>
/// <param name="json">A Hashtable / ArrayList</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string JsonEncode(object json)
{
StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
bool success = SerializeValue(json, builder);
return (success ? builder.ToString() : null);
}
protected static Hashtable ParseObject(char[] json, ref int index, ref bool success)
{
Hashtable table = new Hashtable();
int token;
// {
NextToken(json, ref index);
bool done = false;
while (!done) {
token = LookAhead(json, index);
if (token == JSON.TOKEN_NONE) {
success = false;
return null;
} else if (token == JSON.TOKEN_COMMA) {
NextToken(json, ref index);
} else if (token == JSON.TOKEN_CURLY_CLOSE) {
NextToken(json, ref index);
return table;
} else {
// name
string name = ParseString(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != JSON.TOKEN_COLON) {
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
protected static ArrayList ParseArray(char[] json, ref int index, ref bool success)
{
ArrayList array = new ArrayList();
// [
NextToken(json, ref index);
bool done = false;
while (!done) {
int token = LookAhead(json, index);
if (token == JSON.TOKEN_NONE) {
success = false;
return null;
} else if (token == JSON.TOKEN_COMMA) {
NextToken(json, ref index);
} else if (token == JSON.TOKEN_SQUARED_CLOSE) {
NextToken(json, ref index);
break;
} else {
object value = ParseValue(json, ref index, ref success);
if (!success) {
return null;
}
array.Add(value);
}
}
return array;
}
protected static object ParseValue(char[] json, ref int index, ref bool success)
{
switch (LookAhead(json, index)) {
case JSON.TOKEN_STRING:
return ParseString(json, ref index, ref success);
case JSON.TOKEN_NUMBER:
return ParseNumber(json, ref index, ref success);
case JSON.TOKEN_CURLY_OPEN:
return ParseObject(json, ref index, ref success);
case JSON.TOKEN_SQUARED_OPEN:
return ParseArray(json, ref index, ref success);
case JSON.TOKEN_TRUE:
NextToken(json, ref index);
return true;
case JSON.TOKEN_FALSE:
NextToken(json, ref index);
return false;
case JSON.TOKEN_NULL:
NextToken(json, ref index);
return null;
case JSON.TOKEN_NONE:
break;
}
success = false;
return null;
}
protected static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
char c;
EatWhitespace(json, ref index);
// "
c = json[index++];
bool complete = false;
while (!complete) {
if (index == json.Length) {
break;
}
c = json[index++];
if (c == '"') {
complete = true;
break;
} else if (c == '\\') {
if (index == json.Length) {
break;
}
c = json[index++];
if (c == '"') {
s.Append('"');
} else if (c == '\\') {
s.Append('\\');
} else if (c == '/') {
s.Append('/');
} else if (c == 'b') {
s.Append('\b');
} else if (c == 'f') {
s.Append('\f');
} else if (c == 'n') {
s.Append('\n');
} else if (c == 'r') {
s.Append('\r');
} else if (c == 't') {
s.Append('\t');
} else if (c == 'u') {
int remainingLength = json.Length - index;
if (remainingLength >= 4) {
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) {
return "";
}
// convert the integer codepoint to a unicode char and add to string
s.Append(Char.ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
} else {
break;
}
}
} else {
s.Append(c);
}
}
if (!complete) {
success = false;
return null;
}
return s.ToString();
}
protected static double ParseNumber(char[] json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
double number;
success = Double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
index = lastIndex + 1;
return number;
}
protected static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++) {
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) {
break;
}
}
return lastIndex - 1;
}
protected static void EatWhitespace(char[] json, ref int index)
{
for (; index < json.Length; index++) {
if (" \t\n\r".IndexOf(json[index]) == -1) {
break;
}
}
}
protected static int LookAhead(char[] json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
protected static int NextToken(char[] json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length) {
return JSON.TOKEN_NONE;
}
char c = json[index];
index++;
switch (c) {
case '{':
return JSON.TOKEN_CURLY_OPEN;
case '}':
return JSON.TOKEN_CURLY_CLOSE;
case '[':
return JSON.TOKEN_SQUARED_OPEN;
case ']':
return JSON.TOKEN_SQUARED_CLOSE;
case ',':
return JSON.TOKEN_COMMA;
case '"':
return JSON.TOKEN_STRING;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '-':
return JSON.TOKEN_NUMBER;
case ':':
return JSON.TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5) {
if (json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e') {
index += 5;
return JSON.TOKEN_FALSE;
}
}
// true
if (remainingLength >= 4) {
if (json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e') {
index += 4;
return JSON.TOKEN_TRUE;
}
}
// null
if (remainingLength >= 4) {
if (json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l') {
index += 4;
return JSON.TOKEN_NULL;
}
}
return JSON.TOKEN_NONE;
}
protected static bool SerializeValue(object value, StringBuilder builder)
{
bool success = true;
if (value is string) {
success = SerializeString((string)value, builder);
} else if (value is Hashtable) {
success = SerializeObject((Hashtable)value, builder);
} else if (value is List<Hashtable>) {
success = SerializeArray((List<Hashtable>)value, builder);
} else if ((value is Boolean) && ((Boolean)value == true)) {
builder.Append("true");
} else if ((value is Boolean) && ((Boolean)value == false)) {
builder.Append("false");
} else if (value is ValueType) {
// thanks to ritchie for pointing out ValueType to me
success = SerializeNumber(Convert.ToDouble(value), builder);
} else if (value == null) {
builder.Append("null");
} else {
success = false;
}
return success;
}
protected static bool SerializeObject(Hashtable anObject, StringBuilder builder)
{
builder.Append("{");
IDictionaryEnumerator e = anObject.GetEnumerator();
bool first = true;
while (e.MoveNext()) {
string key = e.Key.ToString();
object value = e.Value;
if (!first) {
builder.Append(", ");
}
SerializeString(key, builder);
builder.Append(":");
if (!SerializeValue(value, builder)) {
return false;
}
first = false;
}
builder.Append("}");
return true;
}
protected static bool SerializeArray(List<Hashtable> anArray, StringBuilder builder)
{
builder.Append("[");
bool first = true;
for (int i = 0; i < anArray.Count; i++) {
object value = anArray[i];
if (!first) {
builder.Append(", ");
}
if (!SerializeValue(value, builder)) {
return false;
}
first = false;
}
builder.Append("]");
return true;
}
protected static bool SerializeString(string aString, StringBuilder builder)
{
builder.Append("\"");
char[] charArray = aString.ToCharArray();
for (int i = 0; i < charArray.Length; i++) {
char c = charArray[i];
if (c == '"') {
builder.Append("\\\"");
} else if (c == '\\') {
builder.Append("\\\\");
} else if (c == '\b') {
builder.Append("\\b");
} else if (c == '\f') {
builder.Append("\\f");
} else if (c == '\n') {
builder.Append("\\n");
} else if (c == '\r') {
builder.Append("\\r");
} else if (c == '\t') {
builder.Append("\\t");
} else {
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
}
}
builder.Append("\"");
return true;
}
protected static bool SerializeNumber(double number, StringBuilder builder)
{
builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture));
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using SimpleBlogDemo.Helpers;
using System.Globalization;
using SimpleBlogDemo.Models;
using System.Web.Configuration;
using System.Threading.Tasks;
using System.Net.Http;
using System.Web.Script.Serialization;
using Dropbox.Api;
namespace SimpleBlogDemo.Controllers
{
[RequireHttpsOrXForwarded]
public partial class HomeController : AsyncController
{
private UsersStore store = new UsersStore();
private UserProfile currentUser;
private string RedirectUri
{
get
{
if (this.Request.Url.Host.ToLowerInvariant() == "localhost")
{
return string.Format("http://{0}:{1}/Home/Auth", this.Request.Url.Host, this.Request.Url.Port);
}
var builder = new UriBuilder(
Uri.UriSchemeHttps,
this.Request.Url.Host);
builder.Path = "/Home/Auth";
return builder.ToString();
}
}
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
this.currentUser = this.store.CurrentUser();
base.Initialize(requestContext);
}
// GET: /Home
public async Task<ActionResult> IndexAsync()
{
if (WebSecurity.IsAuthenticated)
{
return this.RedirectToAction("Profile");
}
var blogs = new List<Blog>();
foreach (var user in store.Users)
{
var blog = await Blog.FromUserAsync(user);
if (blog != null)
{
blogs.Add(blog);
}
}
blogs.Sort((l, r) => r.MostRecent.CompareTo(l.MostRecent));
return View(blogs);
}
// GET: /Home/Register
public ActionResult Register()
{
if (WebSecurity.IsAuthenticated)
{
return this.RedirectToAction("Profile");
}
return View();
}
// POST: /Home/Register
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Register(string username, string password1, string password2, string blogname, bool remember = false)
{
if (string.IsNullOrWhiteSpace(username))
{
this.Flash("Username must not be empty.", FlashLevel.Warning);
}
else if (string.IsNullOrWhiteSpace(password1) ||
string.IsNullOrWhiteSpace(password2) ||
!string.Equals(password1, password2, StringComparison.Ordinal))
{
this.Flash("Password must not be empty and both passwords must match.", FlashLevel.Warning);
}
else if (WebSecurity.UserExists(username))
{
this.Flash(string.Format(
CultureInfo.InvariantCulture,
"Username '{0}' already exists, choose something else.",
username),
FlashLevel.Warning);
}
else
{
var parameters = new Dictionary<string, object>();
if (!string.IsNullOrEmpty(blogname))
{
parameters["BlogName"] = blogname;
}
WebSecurity.CreateUserAndAccount(username, password1, parameters, requireConfirmationToken: false);
WebSecurity.Login(username, password1, persistCookie: remember);
return this.RedirectToAction("Profile");
}
return View();
}
// Get /Home/Profile
[Authorize]
public async Task<ActionResult> ProfileAsync()
{
await Task.Delay(0);
return View(this.currentUser);
}
// Post /Home/Profile
[HttpPost, ValidateAntiForgeryToken, Authorize]
public async Task<ActionResult> ProfileAsync(UserProfile profile)
{
if (this.currentUser.ID != profile.ID)
{
return this.RedirectToAction("Index");
}
this.currentUser.BlogName = profile.BlogName;
await this.store.SaveChangesAsync();
return View(this.currentUser);
}
// POST : /Home/Disconnect
[HttpPost, ValidateAntiForgeryToken, Authorize]
public async Task<ActionResult> DisconnectAsync()
{
if (!string.IsNullOrWhiteSpace(this.currentUser.BlogName))
{
this.FlushCache(this.currentUser.BlogName);
}
this.currentUser.DropboxAccessToken = string.Empty;
await store.SaveChangesAsync();
this.Flash("This account has been disconnected from Dropbox.", FlashLevel.Success);
return this.RedirectToAction("Profile");
}
// GET: /Home/Connect
[Authorize]
public ActionResult Connect()
{
if (!string.IsNullOrWhiteSpace(this.currentUser.DropboxAccessToken))
{
return this.RedirectToAction("Index");
}
this.currentUser.ConnectState = Guid.NewGuid().ToString("N");
store.SaveChanges();
var redirect = DropboxOAuth2Helper.GetAuthorizeUri(
OAuthResponseType.Code,
MvcApplication.AppKey,
RedirectUri,
this.currentUser.ConnectState);
return Redirect(redirect.ToString());
}
// GET: /Home/Auth
[Authorize]
public async Task<ActionResult> AuthAsync(string code, string state)
{
try
{
if (this.currentUser.ConnectState != state)
{
this.Flash("There was an error connecting to Dropbox.");
return this.RedirectToAction("Index");
}
var response = await DropboxOAuth2Helper.ProcessCodeFlowAsync(
code,
MvcApplication.AppKey,
MvcApplication.AppSecret,
this.RedirectUri);
this.currentUser.DropboxAccessToken = response.AccessToken;
this.currentUser.ConnectState = string.Empty;
await this.store.SaveChangesAsync();
this.Flash("This account has been connected to Dropbox.", FlashLevel.Success);
return RedirectToAction("Profile");
}
catch(Exception e)
{
var message = string.Format(
"code: {0}\nAppKey: {1}\nAppSecret: {2}\nRedirectUri: {3}\nException : {4}",
code,
MvcApplication.AppKey,
MvcApplication.AppSecret,
this.RedirectUri,
e);
this.Flash(message, FlashLevel.Danger);
return RedirectToAction("Profile");
}
}
// POST: /Home/LogOff
[HttpPost, ValidateAntiForgeryToken]
public ActionResult LogOff()
{
if (WebSecurity.IsAuthenticated)
{
WebSecurity.Logout();
}
return RedirectToAction("Index");
}
// GET: /Home/SignIn
public ActionResult SignIn(string returnUrl=null)
{
if (WebSecurity.IsAuthenticated)
{
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Profile");
}
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult SignIn(string username, string password, string returnUrl = null, bool remember = false)
{
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
this.Flash("Incorrect username or password.", FlashLevel.Danger);
ViewBag.ReturnUrl = returnUrl;
return View();
}
if (!WebSecurity.IsAuthenticated)
{
var result = WebSecurity.Login(username, password, persistCookie: remember);
if (!result)
{
this.Flash("Incorrect username or password.", FlashLevel.Warning);
ViewBag.ReturnUrl = returnUrl;
return View();
}
else if (remember)
{
Response.Cookies.Get(".ASPXAUTH").Expires = DateTime.UtcNow.AddDays(30);
}
}
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Profile");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Zunix.Gameplay.PseudoEffects;
namespace Zunix.Gameplay
{
public abstract class GameObject
{
#region Status Properties
private bool alive = false;
public bool Alive
{
get { return alive; }
set { alive = value; }
}
#endregion
#region Graphics Properties
//private SpriteBatch spriteBatch;
//private Texture2D texture;
private Vector2 position;
private Vector2 intialposition;
//private Rectangle source;
//// All textures are invisible at first
//private Color color = new Color(0, 0, 0, 0);
//private Vector2 origin;
//private Vector2 scale;
private float rotation;
//private SpriteEffects effects = SpriteEffects.None;
//private float layer = 0.5f;
//// The X and Y size of every source frame of a loadedTexture and with the scale involved
//private Vector2 actualsize;
private float speed;
//public SpriteBatch SpriteBatch
//{
// get { return spriteBatch; }
// set { spriteBatch = value; }
//}
//public Texture2D Sprite
//{
// get { return texture; }
// set { texture = value; }
//}
public abstract Texture2D Sprite
{
get;
}
public abstract Color[] SpriteData
{
get;
}
public Vector2 Position
{
get { return position; }
set { position = value; }
}
public Vector2 IntialPosition
{
get { return intialposition; }
set { intialposition = value; }
}
public virtual float Rotation
{
get { return rotation; }
set { rotation = value; }
}
//public Rectangle Source
//{
// get { return source; }
// set { source = value; }
//}
//public Color Color
//{
// get { return color; }
// set { color = value; }
//}
///// <summary>
///// The center coordinates for the sprite by itself, not in the playing field.
///// </summary>
//public Vector2 Origin
//{
// get { return origin; }
// set { origin = value; }
//}
///// <summary>
///// Can't be changed from 1.0f unless it's set as an overload.
///// </summary>
//public Vector2 Scale
//{
// get { return scale; }
//}
//public SpriteEffects SpriteEffects
//{
// get { return effects; }
// set { effects = value; }
//}
///// <summary>
///// Default is 0.5f, but can be changed from 0.0f to 1.0f.
///// </summary>
//public float Layer
//{
// get { return layer; }
// set { layer = value; }
//}
///// <summary>
///// The ActualSize is a Vector2 for the X being the width and Y the Height of the actual
///// sprite with scale change, but without source because SourceSize works just as well.
///// </summary>
//public Vector2 ActualSize
//{
// get { return actualsize; }
//}
public Vector2 Speed { get; set; }
#endregion
#region Collision Data
protected float mass = 1f;
public float Mass
{
get { return mass; }
}
protected bool collidedThisFrame = false;
public bool CollidedThisFrame
{
get { return collidedThisFrame; }
set { collidedThisFrame = value; }
}
//public bool UpdateHull { get; set; }
//public List<Point> Hull { get; set; }
//public Dictionary<Point, bool> HullTransformed { get; set; }
//public int MinX { get; set; }
//public int MinY { get; set; }
//public int MaxX { get; set; }
//public int MaxY { get; set; }
//private BoundingSphere boundingSphere;
//public BoundingSphere BoundingSphere
//{
// get { return boundingSphere; }
// set { boundingSphere = value; }
//}
#endregion
#region Main Methods
public GameObject()
{
//this.scale = Vector2.One;
if (!alive)
{
alive = true;
if (this is PseudoEffect == false)
{
CollisionManager.Collection.Add(this);
}
}
}
//public virtual void LoadContent(SpriteBatch spriteBatch, Texture2D loadedTexture)
//{
// //this.spriteBatch = spriteBatch;
// //this.texture = loadedTexture;
// //// Find the actual size of the sprite after its been scaled
// //this.actualsize = new Vector2((int)(this.scale.X * this.texture.Width), (int)(this.scale.Y * this.texture.Height));
// //this.source = new Rectangle(0, 0, (int)this.texture.Width, (int)this.texture.Height);
// //// The "origin" of a sprite is the point
// //// halfway down its width and height.
// //this.origin = new Vector2(
// // (float)(loadedTexture.Width) / 2, (float)(loadedTexture.Height) / 2);
// MinX = texture.Width;
// MinY = texture.Height;
// MaxX = -texture.Width;
// MaxY = -texture.Height;
// //boundingSphere.Center = new Vector3(position, 0);
// //boundingSphere.Radius = (float)Math.Sqrt(texture.Width * texture.Width + texture.Height * texture.Height) / 2.0f;
//}
//public virtual void LoadContent(SpriteBatch spriteBatch, Texture2D loadedTexture, Vector2 inputedscale)
//{
// //this.spriteBatch = spriteBatch;
// //this.texture = loadedTexture;
// //// If the X or Y is greater than 1 or less than 0 set the scale to 1
// //if (inputedscale.X >= 0.0f & inputedscale.X <= 1.0f)
// //{
// // if (inputedscale.Y >= 0.0f & inputedscale.Y <= 1.0f)
// // {
// // this.scale = (Vector2)(new Vector2(240, 320) / new Vector2(240, 320)) * inputedscale;
// // }
// // else
// // {
// // this.scale = (Vector2)(new Vector2(240, 320) / new Vector2(240, 320));
// // this.scale.X *= inputedscale.X;
// // }
// //}
// //else if (inputedscale.Y >= 0.0f & inputedscale.Y <= 1.0f)
// //{
// // this.scale = (Vector2)(new Vector2(240, 320) / new Vector2(240, 320));
// // this.scale.Y *= inputedscale.Y;
// //}
// //else
// //{
// // this.scale = new Vector2(240, 320) / new Vector2(240, 320);
// //}
// //// Find the actual size of the sprite after its been scaled
// //this.actualsize = new Vector2((int)(this.scale.X * this.source.Width), (int)(this.scale.Y * this.source.Height));
// //this.source = new Rectangle(0, 0, (int)this.texture.Width, (int)this.texture.Height); ;
// //// The "origin" of a sprite is the point
// //// halfway down its width and height.
// //this.origin = new Vector2(
// // loadedTexture.Width / 2, loadedTexture.Height / 2);
// MinX = texture.Width;
// MinY = texture.Height;
// MaxX = -texture.Width;
// MaxY = -texture.Height;
// //CollisionMath.CalcHull(this);
// //boundingSphere.Center = new Vector3(position, 0);
// //boundingSphere.Radius = (float)Math.Sqrt(texture.Width * texture.Width + texture.Height * texture.Height) / 2.0f;
//}
#region Updating Methods
/// <summary>
/// Update the gameplay object.
/// </summary>
/// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
public virtual void Update(float elapsedTime)
{
collidedThisFrame = false;
}
#endregion
//public virtual void Draw()
//{
// this.spriteBatch.Draw(this.texture, this.position, this.source, this.color, this.rotation, this.origin, this.scale, this.effects, this.layer);
//}
//public virtual void Draw(SpriteBatch spriteBatch)
//{
// spriteBatch.Draw(this.texture, this.position, this.source, this.color, this.rotation, this.origin, this.scale, this.effects, this.layer);
//}
#endregion
#region Drawing Methods
/// <summary>
/// Draw the gameplay object.
/// </summary>
/// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
/// <param name="spriteBatch">The SpriteBatch object used to draw.</param>
/// <param name="sprite">The texture used to draw this object.</param>
/// <param name="color">The color of the sprite.</param>
public virtual void Draw(float elapsedTime, SpriteBatch spriteBatch,
Texture2D sprite, Color color)
{
if ((spriteBatch != null) && (sprite != null))
{
spriteBatch.Draw(sprite, position, null, color, rotation,
new Vector2(sprite.Width / 2f, sprite.Height / 2f),
1f, SpriteEffects.None, 0f);
}
}
/// <summary>
/// Draw the gameplay object.
/// </summary>
/// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
/// <param name="spriteBatch">The SpriteBatch object used to draw.</param>
/// <param name="sprite">The texture used to draw this object.</param>
/// <param name="sourceRectangle">The source rectangle.</param>
/// <param name="color">The color of the sprite.</param>
public virtual void Draw(float elapsedTime, SpriteBatch spriteBatch,
Texture2D sprite, Rectangle? sourceRectangle, Color color)
{
if ((spriteBatch != null) && (sprite != null))
{
spriteBatch.Draw(sprite, position, sourceRectangle, color, rotation,
new Vector2(sprite.Width / 2f, sprite.Height / 2f),
1f, SpriteEffects.None, 0f);
}
}
#endregion
#region Interaction Methods
/// <summary>
/// Defines the interaction between this GameObject and
/// a target GameObject when they touch.
/// </summary>
/// <param name="target">The GameObject that is touching this one.</param>
/// <returns>True if the objects meaningfully interacted.</returns>
public virtual bool Touch(GameObject target)
{
return true;
}
/// <summary>
/// Damage this object by the amount provided.
/// </summary>
/// <remarks>
/// This function is provided in lieu of a Life mutation property to allow
/// classes of objects to restrict which kinds of objects may damage them,
/// and under what circumstances they may be damaged.
/// </remarks>
/// <param name="source">The GameObject responsible for the damage.</param>
/// <param name="damageAmount">The amount of damage.</param>
/// <returns>If true, this object was damaged.</returns>
public virtual bool Damage(GameObject source, float damageAmount)
{
return false;
}
/// <summary>
/// Kills this object, in response to the given GameObject.
/// </summary>
/// <param name="source">The GameObject responsible for the kill.</param>
/// <param name="cleanupOnly">
/// If true, the object kills without any further effects.
/// </param>
public virtual void Kill(GameObject source, bool cleanupOnly)
{
// deactivate the object
if (alive)
{
alive = false;
}
}
#endregion
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Buffers.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocol.Entities;
using Thrift.Transport;
#pragma warning disable IDE0079 // unnecessary suppression
#pragma warning disable IDE0066 // use switch expression
namespace Thrift.Protocol
{
// ReSharper disable once InconsistentNaming
public class TBinaryProtocol : TProtocol
{
protected const uint VersionMask = 0xffff0000;
protected const uint Version1 = 0x80010000;
protected bool StrictRead;
protected bool StrictWrite;
// minimize memory allocations by means of an preallocated bytes buffer
// The value of 128 is arbitrarily chosen, the required minimum size must be sizeof(long)
private readonly byte[] PreAllocatedBuffer = new byte[128];
public TBinaryProtocol(TTransport trans)
: this(trans, false, true)
{
}
public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite)
: base(trans)
{
StrictRead = strictRead;
StrictWrite = strictWrite;
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (StrictWrite)
{
var version = Version1 | (uint) message.Type;
await WriteI32Async((int) version, cancellationToken);
await WriteStringAsync(message.Name, cancellationToken);
await WriteI32Async(message.SeqID, cancellationToken);
}
else
{
await WriteStringAsync(message.Name, cancellationToken);
await WriteByteAsync((sbyte) message.Type, cancellationToken);
await WriteI32Async(message.SeqID, cancellationToken);
}
}
public override Task WriteMessageEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override Task WriteStructEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await WriteByteAsync((sbyte) field.Type, cancellationToken);
await WriteI16Async(field.ID, cancellationToken);
}
public override Task WriteFieldEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async Task WriteFieldStopAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await WriteByteAsync((sbyte) TType.Stop, cancellationToken);
}
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
PreAllocatedBuffer[0] = (byte)map.KeyType;
PreAllocatedBuffer[1] = (byte)map.ValueType;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken);
await WriteI32Async(map.Count, cancellationToken);
}
public override Task WriteMapEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await WriteByteAsync((sbyte) list.ElementType, cancellationToken);
await WriteI32Async(list.Count, cancellationToken);
}
public override Task WriteListEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await WriteByteAsync((sbyte) set.ElementType, cancellationToken);
await WriteI32Async(set.Count, cancellationToken);
}
public override Task WriteSetEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await WriteByteAsync(b ? (sbyte) 1 : (sbyte) 0, cancellationToken);
}
public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
PreAllocatedBuffer[0] = (byte)b;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
}
public override async Task WriteI16Async(short i16, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
BinaryPrimitives.WriteInt16BigEndian(PreAllocatedBuffer, i16);
await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken);
}
public override async Task WriteI32Async(int i32, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
BinaryPrimitives.WriteInt32BigEndian(PreAllocatedBuffer, i32);
await Trans.WriteAsync(PreAllocatedBuffer, 0, 4, cancellationToken);
}
public override async Task WriteI64Async(long i64, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
BinaryPrimitives.WriteInt64BigEndian(PreAllocatedBuffer, i64);
await Trans.WriteAsync(PreAllocatedBuffer, 0, 8, cancellationToken);
}
public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await WriteI64Async(BitConverter.DoubleToInt64Bits(d), cancellationToken);
}
public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await WriteI32Async(bytes.Length, cancellationToken);
await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var message = new TMessage();
var size = await ReadI32Async(cancellationToken);
if (size < 0)
{
var version = (uint) size & VersionMask;
if (version != Version1)
{
throw new TProtocolException(TProtocolException.BAD_VERSION,
$"Bad version in ReadMessageBegin: {version}");
}
message.Type = (TMessageType) (size & 0x000000ff);
message.Name = await ReadStringAsync(cancellationToken);
message.SeqID = await ReadI32Async(cancellationToken);
}
else
{
if (StrictRead)
{
throw new TProtocolException(TProtocolException.BAD_VERSION,
"Missing version in ReadMessageBegin, old client?");
}
message.Name = (size > 0) ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty;
message.Type = (TMessageType) await ReadByteAsync(cancellationToken);
message.SeqID = await ReadI32Async(cancellationToken);
}
return message;
}
public override Task ReadMessageEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return new ValueTask<TStruct>(AnonymousStruct);
}
public override Task ReadStructEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var type = (TType)await ReadByteAsync(cancellationToken);
if (type == TType.Stop)
{
return StopField;
}
return new TField {
Type = type,
ID = await ReadI16Async(cancellationToken)
};
}
public override Task ReadFieldEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var map = new TMap
{
KeyType = (TType) await ReadByteAsync(cancellationToken),
ValueType = (TType) await ReadByteAsync(cancellationToken),
Count = await ReadI32Async(cancellationToken)
};
CheckReadBytesAvailable(map);
return map;
}
public override Task ReadMapEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var list = new TList
{
ElementType = (TType) await ReadByteAsync(cancellationToken),
Count = await ReadI32Async(cancellationToken)
};
CheckReadBytesAvailable(list);
return list;
}
public override Task ReadListEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var set = new TSet
{
ElementType = (TType) await ReadByteAsync(cancellationToken),
Count = await ReadI32Async(cancellationToken)
};
CheckReadBytesAvailable(set);
return set;
}
public override Task ReadSetEndAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return await ReadByteAsync(cancellationToken) == 1;
}
public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
return (sbyte)PreAllocatedBuffer[0];
}
public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 2, cancellationToken);
var result = BinaryPrimitives.ReadInt16BigEndian(PreAllocatedBuffer);
return result;
}
public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 4, cancellationToken);
var result = BinaryPrimitives.ReadInt32BigEndian(PreAllocatedBuffer);
return result;
}
public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 8, cancellationToken);
return BinaryPrimitives.ReadInt64BigEndian(PreAllocatedBuffer);
}
public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var d = await ReadI64Async(cancellationToken);
return BitConverter.Int64BitsToDouble(d);
}
public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var size = await ReadI32Async(cancellationToken);
Transport.CheckReadBytesAvailable(size);
var buf = new byte[size];
await Trans.ReadAllAsync(buf, 0, size, cancellationToken);
return buf;
}
public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var size = await ReadI32Async(cancellationToken);
return size > 0 ? await ReadStringBodyAsync(size, cancellationToken) : string.Empty;
}
private async ValueTask<string> ReadStringBodyAsync(int size, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (size <= PreAllocatedBuffer.Length)
{
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, size, cancellationToken);
return Encoding.UTF8.GetString(PreAllocatedBuffer, 0, size);
}
Transport.CheckReadBytesAvailable(size);
var buf = new byte[size];
await Trans.ReadAllAsync(buf, 0, size, cancellationToken);
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
// Return the minimum number of bytes a type will consume on the wire
public override int GetMinSerializedSize(TType type)
{
switch (type)
{
case TType.Stop: return 0;
case TType.Void: return 0;
case TType.Bool: return sizeof(byte);
case TType.Byte: return sizeof(byte);
case TType.Double: return sizeof(double);
case TType.I16: return sizeof(short);
case TType.I32: return sizeof(int);
case TType.I64: return sizeof(long);
case TType.String: return sizeof(int); // string length
case TType.Struct: return 0; // empty struct
case TType.Map: return sizeof(int); // element count
case TType.Set: return sizeof(int); // element count
case TType.List: return sizeof(int); // element count
default: throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "unrecognized type code");
}
}
public class Factory : TProtocolFactory
{
protected bool StrictRead;
protected bool StrictWrite;
public Factory()
: this(false, true)
{
}
public Factory(bool strictRead, bool strictWrite)
{
StrictRead = strictRead;
StrictWrite = strictWrite;
}
public override TProtocol GetProtocol(TTransport trans)
{
return new TBinaryProtocol(trans, StrictRead, StrictWrite);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedVpnTunnelsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<VpnTunnels.VpnTunnelsClient> mockGrpcClient = new moq::Mock<VpnTunnels.VpnTunnelsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVpnTunnelRequest request = new GetVpnTunnelRequest
{
Region = "regionedb20d96",
VpnTunnel = "vpn_tunnelfa4123fd",
Project = "projectaa6ff846",
};
VpnTunnel expectedResponse = new VpnTunnel
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
VpnGatewayInterface = 1166485993,
Region = "regionedb20d96",
Router = "routerd55c39f3",
Status = VpnTunnel.Types.Status.Provisioning,
IkeVersion = 485306612,
PeerGcpGateway = "peer_gcp_gateway613039db",
LocalTrafficSelector =
{
"local_traffic_selector09bfbb68",
},
DetailedStatus = "detailed_status4e3163c7",
RemoteTrafficSelector =
{
"remote_traffic_selector8463a07f",
},
SharedSecret = "shared_secret3a48b317",
PeerIp = "peer_ip5b148b8e",
PeerExternalGateway = "peer_external_gatewaye60baaef",
SharedSecretHash = "shared_secret_hash3ba18c3b",
VpnGateway = "vpn_gatewayaa15de14",
Description = "description2cf9da67",
PeerExternalGatewayInterface = -994715857,
SelfLink = "self_link7e87f12d",
TargetVpnGateway = "target_vpn_gateway6c481371",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
VpnTunnelsClient client = new VpnTunnelsClientImpl(mockGrpcClient.Object, null);
VpnTunnel response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<VpnTunnels.VpnTunnelsClient> mockGrpcClient = new moq::Mock<VpnTunnels.VpnTunnelsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVpnTunnelRequest request = new GetVpnTunnelRequest
{
Region = "regionedb20d96",
VpnTunnel = "vpn_tunnelfa4123fd",
Project = "projectaa6ff846",
};
VpnTunnel expectedResponse = new VpnTunnel
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
VpnGatewayInterface = 1166485993,
Region = "regionedb20d96",
Router = "routerd55c39f3",
Status = VpnTunnel.Types.Status.Provisioning,
IkeVersion = 485306612,
PeerGcpGateway = "peer_gcp_gateway613039db",
LocalTrafficSelector =
{
"local_traffic_selector09bfbb68",
},
DetailedStatus = "detailed_status4e3163c7",
RemoteTrafficSelector =
{
"remote_traffic_selector8463a07f",
},
SharedSecret = "shared_secret3a48b317",
PeerIp = "peer_ip5b148b8e",
PeerExternalGateway = "peer_external_gatewaye60baaef",
SharedSecretHash = "shared_secret_hash3ba18c3b",
VpnGateway = "vpn_gatewayaa15de14",
Description = "description2cf9da67",
PeerExternalGatewayInterface = -994715857,
SelfLink = "self_link7e87f12d",
TargetVpnGateway = "target_vpn_gateway6c481371",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VpnTunnel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
VpnTunnelsClient client = new VpnTunnelsClientImpl(mockGrpcClient.Object, null);
VpnTunnel responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VpnTunnel responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<VpnTunnels.VpnTunnelsClient> mockGrpcClient = new moq::Mock<VpnTunnels.VpnTunnelsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVpnTunnelRequest request = new GetVpnTunnelRequest
{
Region = "regionedb20d96",
VpnTunnel = "vpn_tunnelfa4123fd",
Project = "projectaa6ff846",
};
VpnTunnel expectedResponse = new VpnTunnel
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
VpnGatewayInterface = 1166485993,
Region = "regionedb20d96",
Router = "routerd55c39f3",
Status = VpnTunnel.Types.Status.Provisioning,
IkeVersion = 485306612,
PeerGcpGateway = "peer_gcp_gateway613039db",
LocalTrafficSelector =
{
"local_traffic_selector09bfbb68",
},
DetailedStatus = "detailed_status4e3163c7",
RemoteTrafficSelector =
{
"remote_traffic_selector8463a07f",
},
SharedSecret = "shared_secret3a48b317",
PeerIp = "peer_ip5b148b8e",
PeerExternalGateway = "peer_external_gatewaye60baaef",
SharedSecretHash = "shared_secret_hash3ba18c3b",
VpnGateway = "vpn_gatewayaa15de14",
Description = "description2cf9da67",
PeerExternalGatewayInterface = -994715857,
SelfLink = "self_link7e87f12d",
TargetVpnGateway = "target_vpn_gateway6c481371",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
VpnTunnelsClient client = new VpnTunnelsClientImpl(mockGrpcClient.Object, null);
VpnTunnel response = client.Get(request.Project, request.Region, request.VpnTunnel);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<VpnTunnels.VpnTunnelsClient> mockGrpcClient = new moq::Mock<VpnTunnels.VpnTunnelsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVpnTunnelRequest request = new GetVpnTunnelRequest
{
Region = "regionedb20d96",
VpnTunnel = "vpn_tunnelfa4123fd",
Project = "projectaa6ff846",
};
VpnTunnel expectedResponse = new VpnTunnel
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
CreationTimestamp = "creation_timestamp235e59a1",
VpnGatewayInterface = 1166485993,
Region = "regionedb20d96",
Router = "routerd55c39f3",
Status = VpnTunnel.Types.Status.Provisioning,
IkeVersion = 485306612,
PeerGcpGateway = "peer_gcp_gateway613039db",
LocalTrafficSelector =
{
"local_traffic_selector09bfbb68",
},
DetailedStatus = "detailed_status4e3163c7",
RemoteTrafficSelector =
{
"remote_traffic_selector8463a07f",
},
SharedSecret = "shared_secret3a48b317",
PeerIp = "peer_ip5b148b8e",
PeerExternalGateway = "peer_external_gatewaye60baaef",
SharedSecretHash = "shared_secret_hash3ba18c3b",
VpnGateway = "vpn_gatewayaa15de14",
Description = "description2cf9da67",
PeerExternalGatewayInterface = -994715857,
SelfLink = "self_link7e87f12d",
TargetVpnGateway = "target_vpn_gateway6c481371",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VpnTunnel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
VpnTunnelsClient client = new VpnTunnelsClientImpl(mockGrpcClient.Object, null);
VpnTunnel responseCallSettings = await client.GetAsync(request.Project, request.Region, request.VpnTunnel, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
VpnTunnel responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.VpnTunnel, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Filters
{
using System;
using System.Collections.Generic;
using System.Text;
using NLog.Internal;
/// <summary>
/// Matches when the result of the calculated layout has been repeated a moment ago
/// </summary>
[Filter("whenRepeated")]
public class WhenRepeatedFilter : LayoutBasedFilter
{
private const int MaxInitialRenderBufferLength = 16384;
/// <summary>
/// How long before a filter expires, and logging is accepted again
/// </summary>
/// <docgen category='Filtering Options' order='10' />
public int TimeoutSeconds { get; set; } = 10;
/// <summary>
/// Max length of filter values, will truncate if above limit
/// </summary>
/// <docgen category='Filtering Options' order='10' />
public int MaxLength { get; set; } = 1000;
/// <summary>
/// Applies the configured action to the initial logevent that starts the timeout period.
/// Used to configure that it should ignore all events until timeout.
/// </summary>
/// <docgen category='Filtering Options' order='10' />
public bool IncludeFirst { get; set; }
/// <summary>
/// Max number of unique filter values to expect simultaneously
/// </summary>
/// <docgen category='Filtering Options' order='10' />
public int MaxFilterCacheSize { get; set; } = 50000;
/// <summary>
/// Default number of unique filter values to expect, will automatically increase if needed
/// </summary>
/// <docgen category='Filtering Options' order='10' />
public int DefaultFilterCacheSize { get; set; } = 1000;
/// <summary>
/// Insert FilterCount value into <see cref="LogEventInfo.Properties"/> when an event is no longer filtered
/// </summary>
/// <docgen category='Rendering Options' order='10' />
public string FilterCountPropertyName { get; set; }
/// <summary>
/// Append FilterCount to the <see cref="LogEventInfo.Message"/> when an event is no longer filtered
/// </summary>
/// <docgen category='Rendering Options' order='10' />
public string FilterCountMessageAppendFormat { get; set; }
/// <summary>
/// Reuse internal buffers, and doesn't have to constantly allocate new buffers
/// </summary>
/// <docgen category='Performance Options' order='10' />
[Obsolete("No longer used, and always returns true. Marked obsolete on NLog 5.0")]
public bool OptimizeBufferReuse { get => _optimizeBufferReuse ?? true; set => _optimizeBufferReuse = value ? true : (bool?)null; }
private bool? _optimizeBufferReuse;
/// <summary>
/// Default buffer size for the internal buffers
/// </summary>
/// <docgen category='Performance Options' order='10' />
public int OptimizeBufferDefaultLength { get; set; } = 1000;
internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator();
private readonly Dictionary<FilterInfoKey, FilterInfo> _repeatFilter = new Dictionary<FilterInfoKey, FilterInfo>(1000);
private readonly Stack<KeyValuePair<FilterInfoKey, FilterInfo>> _objectPool = new Stack<KeyValuePair<FilterInfoKey, FilterInfo>>(1000);
/// <summary>
/// Checks whether log event should be logged or not. In case the LogEvent has just been repeated.
/// </summary>
/// <param name="logEvent">Log event.</param>
/// <returns>
/// <see cref="FilterResult.Ignore"/> - if the log event should be ignored<br/>
/// <see cref="FilterResult.Neutral"/> - if the filter doesn't want to decide<br/>
/// <see cref="FilterResult.Log"/> - if the log event should be logged<br/>
/// .</returns>
protected override FilterResult Check(LogEventInfo logEvent)
{
FilterResult filterResult = FilterResult.Neutral;
bool obsoleteFilter = false;
lock (_repeatFilter)
{
using (var targetBuilder = ReusableLayoutBuilder.Allocate())
{
if (targetBuilder.Result.Capacity != OptimizeBufferDefaultLength)
{
// StringBuilder.Equals only works when StringBuilder.Capacity is the same
if (OptimizeBufferDefaultLength < MaxInitialRenderBufferLength)
{
OptimizeBufferDefaultLength = MaxLength;
while (OptimizeBufferDefaultLength < targetBuilder.Result.Capacity && OptimizeBufferDefaultLength < MaxInitialRenderBufferLength)
{
OptimizeBufferDefaultLength *= 2;
}
}
targetBuilder.Result.Capacity = OptimizeBufferDefaultLength;
}
FilterInfoKey filterInfoKey = RenderFilterInfoKey(logEvent, targetBuilder.Result);
FilterInfo filterInfo;
if (!_repeatFilter.TryGetValue(filterInfoKey, out filterInfo))
{
filterInfo = CreateFilterInfo(logEvent);
if (filterInfo.StringBuffer != null)
{
filterInfo.StringBuffer.ClearBuilder();
int length = Math.Min(targetBuilder.Result.Length, MaxLength);
for (int i = 0; i < length; ++i)
filterInfo.StringBuffer.Append(targetBuilder.Result[i]);
}
filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, 0);
_repeatFilter.Add(new FilterInfoKey(filterInfo.StringBuffer, filterInfoKey.StringValue, filterInfoKey.StringHashCode), filterInfo);
obsoleteFilter = true;
}
else
{
if (IncludeFirst)
{
obsoleteFilter = filterInfo.IsObsolete(logEvent.TimeStamp, TimeoutSeconds);
}
filterResult = RefreshFilterInfo(logEvent, filterInfo);
}
}
}
// Ignore the first log-event, and wait until next timeout expiry
if (IncludeFirst && obsoleteFilter)
{
filterResult = Action;
}
return filterResult;
}
/// <summary>
/// Uses object pooling, and prunes stale filter items when the pool runs dry
/// </summary>
private FilterInfo CreateFilterInfo(LogEventInfo logEvent)
{
FilterInfo reusableObject;
if (_objectPool.Count == 0 && _repeatFilter.Count > DefaultFilterCacheSize)
{
int aggressiveTimeoutSeconds = _repeatFilter.Count > MaxFilterCacheSize ? TimeoutSeconds * 2 / 3 : TimeoutSeconds;
PruneFilterCache(logEvent, Math.Max(1, aggressiveTimeoutSeconds));
if (_repeatFilter.Count > MaxFilterCacheSize)
{
PruneFilterCache(logEvent, Math.Max(1, TimeoutSeconds / 2));
}
}
if (_objectPool.Count == 0)
{
reusableObject = new FilterInfo(new StringBuilder(OptimizeBufferDefaultLength));
}
else
{
reusableObject = _objectPool.Pop().Value;
// StringBuilder.Equals only works when StringBuilder.Capacity is the same
if (reusableObject.StringBuffer != null && reusableObject.StringBuffer.Capacity != OptimizeBufferDefaultLength)
{
reusableObject.StringBuffer.Capacity = OptimizeBufferDefaultLength;
}
}
return reusableObject;
}
/// <summary>
/// Remove stale filter-value from the cache, and fill them into the pool for reuse
/// </summary>
private void PruneFilterCache(LogEventInfo logEvent, int aggressiveTimeoutSeconds)
{
foreach (var filterPair in _repeatFilter)
{
if (filterPair.Value.IsObsolete(logEvent.TimeStamp, aggressiveTimeoutSeconds))
{
_objectPool.Push(filterPair);
}
}
foreach (var filterPair in _objectPool)
{
_repeatFilter.Remove(filterPair.Key);
}
if (_repeatFilter.Count * 2 > DefaultFilterCacheSize && DefaultFilterCacheSize < MaxFilterCacheSize)
{
DefaultFilterCacheSize *= 2;
}
while (_objectPool.Count != 0 && _objectPool.Count > DefaultFilterCacheSize)
{
_objectPool.Pop();
}
}
/// <summary>
/// Renders the Log Event into a filter value, that is used for checking if just repeated
/// </summary>
private FilterInfoKey RenderFilterInfoKey(LogEventInfo logEvent, StringBuilder targetBuilder)
{
if (targetBuilder != null)
{
Layout.Render(logEvent, targetBuilder);
if (targetBuilder.Length > MaxLength)
targetBuilder.Length = MaxLength;
return new FilterInfoKey(targetBuilder, null);
}
string value = Layout.Render(logEvent) ?? string.Empty;
if (value.Length > MaxLength)
value = value.Substring(0, MaxLength);
return new FilterInfoKey(null, value);
}
/// <summary>
/// Repeated LogEvent detected. Checks if it should activate filter-action
/// </summary>
private FilterResult RefreshFilterInfo(LogEventInfo logEvent, FilterInfo filterInfo)
{
if (filterInfo.HasExpired(logEvent.TimeStamp, TimeoutSeconds) || logEvent.Level.Ordinal > filterInfo.LogLevel.Ordinal)
{
int filterCount = filterInfo.FilterCount;
if (filterCount > 0 && filterInfo.IsObsolete(logEvent.TimeStamp, TimeoutSeconds))
{
filterCount = 0;
}
filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, 0);
if (filterCount > 0)
{
if (!string.IsNullOrEmpty(FilterCountPropertyName))
{
if (!logEvent.Properties.TryGetValue(FilterCountPropertyName, out var otherFilterCount))
{
logEvent.Properties[FilterCountPropertyName] = filterCount;
}
else if (otherFilterCount is int i)
{
filterCount = Math.Max(i, filterCount);
logEvent.Properties[FilterCountPropertyName] = filterCount;
}
}
if (!string.IsNullOrEmpty(FilterCountMessageAppendFormat) && logEvent.Message != null)
{
logEvent.Message += string.Format(FilterCountMessageAppendFormat, filterCount.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
}
return FilterResult.Neutral;
}
filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, filterInfo.FilterCount + 1);
return Action;
}
/// <summary>
/// Filter Value State (mutable)
/// </summary>
private class FilterInfo
{
public FilterInfo(StringBuilder stringBuilder)
{
StringBuffer = stringBuilder;
}
public void Refresh(LogLevel logLevel, DateTime logTimeStamp, int filterCount)
{
if (filterCount == 0)
{
LastLogTime = logTimeStamp;
LogLevel = logLevel;
}
else if (LogLevel is null || logLevel.Ordinal > LogLevel.Ordinal)
{
LogLevel = logLevel;
}
LastFilterTime = logTimeStamp;
FilterCount = filterCount;
}
public bool IsObsolete(DateTime logEventTime, int timeoutSeconds)
{
if (FilterCount == 0)
{
return HasExpired(logEventTime, timeoutSeconds);
}
return (logEventTime - LastFilterTime).TotalSeconds > timeoutSeconds && HasExpired(logEventTime, timeoutSeconds * 2);
}
public bool HasExpired(DateTime logEventTime, int timeoutSeconds)
{
return (logEventTime - LastLogTime).TotalSeconds > timeoutSeconds;
}
public StringBuilder StringBuffer { get; }
public LogLevel LogLevel { get; private set; }
private DateTime LastLogTime { get; set; }
private DateTime LastFilterTime { get; set; }
public int FilterCount { get; private set; }
}
/// <summary>
/// Filter Lookup Key (immutable)
/// </summary>
private struct FilterInfoKey : IEquatable<FilterInfoKey>
{
private readonly StringBuilder _stringBuffer;
public readonly string StringValue;
public readonly int StringHashCode;
public FilterInfoKey(StringBuilder stringBuffer, string stringValue, int? stringHashCode = null)
{
_stringBuffer = stringBuffer;
StringValue = stringValue;
if (stringHashCode.HasValue)
{
StringHashCode = stringHashCode.Value;
}
else if (stringBuffer != null)
{
int hashCode = stringBuffer.Length.GetHashCode();
int hashCodeCount = Math.Min(stringBuffer.Length, 100);
for (int i = 0; i < hashCodeCount; ++i)
hashCode = hashCode ^ stringBuffer[i].GetHashCode();
StringHashCode = hashCode;
}
else
{
StringHashCode = StringComparer.Ordinal.GetHashCode(StringValue);
}
}
public override int GetHashCode()
{
return StringHashCode;
}
public bool Equals(FilterInfoKey other)
{
if (StringValue != null)
{
return string.Equals(StringValue, other.StringValue, StringComparison.Ordinal);
}
if (_stringBuffer != null && other._stringBuffer != null)
{
// StringBuilder.Equals only works when StringBuilder.Capacity is the same
if (_stringBuffer.Capacity != other._stringBuffer.Capacity)
{
return _stringBuffer.EqualTo(other._stringBuffer);
}
return _stringBuffer.Equals(other._stringBuffer);
}
return ReferenceEquals(_stringBuffer, other._stringBuffer) && ReferenceEquals(StringValue, other.StringValue);
}
public override bool Equals(object obj)
{
return obj is FilterInfoKey key && Equals(key);
}
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// 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 Rodrigo B. de Oliveira 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
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class DeclarationStatement : Statement
{
protected Declaration _declaration;
protected Expression _initializer;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public DeclarationStatement CloneNode()
{
return (DeclarationStatement)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public DeclarationStatement CleanClone()
{
return (DeclarationStatement)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.DeclarationStatement; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnDeclarationStatement(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( DeclarationStatement)node;
if (!Node.Matches(_modifier, other._modifier)) return NoMatch("DeclarationStatement._modifier");
if (!Node.Matches(_declaration, other._declaration)) return NoMatch("DeclarationStatement._declaration");
if (!Node.Matches(_initializer, other._initializer)) return NoMatch("DeclarationStatement._initializer");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_modifier == existing)
{
this.Modifier = (StatementModifier)newNode;
return true;
}
if (_declaration == existing)
{
this.Declaration = (Declaration)newNode;
return true;
}
if (_initializer == existing)
{
this.Initializer = (Expression)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
DeclarationStatement clone = new DeclarationStatement();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
if (null != _modifier)
{
clone._modifier = _modifier.Clone() as StatementModifier;
clone._modifier.InitializeParent(clone);
}
if (null != _declaration)
{
clone._declaration = _declaration.Clone() as Declaration;
clone._declaration.InitializeParent(clone);
}
if (null != _initializer)
{
clone._initializer = _initializer.Clone() as Expression;
clone._initializer.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _modifier)
{
_modifier.ClearTypeSystemBindings();
}
if (null != _declaration)
{
_declaration.ClearTypeSystemBindings();
}
if (null != _initializer)
{
_initializer.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Declaration Declaration
{
get { return _declaration; }
set
{
if (_declaration != value)
{
_declaration = value;
if (null != _declaration)
{
_declaration.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Expression Initializer
{
get { return _initializer; }
set
{
if (_initializer != value)
{
_initializer = value;
if (null != _initializer)
{
_initializer.InitializeParent(this);
}
}
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Mshtml;
using OpenLiveWriter.PostEditor.Emoticons;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing.Behaviors
{
/// <summary>
/// Handles initiation of drag and drop for behaviors in the editor
/// </summary>
internal abstract class BehaviorDragAndDropSource : IDisposable
{
/// <summary>
/// Initialize with editor context
/// </summary>
/// <param name="context">editor context</param>
public BehaviorDragAndDropSource(IHtmlEditorComponentContext context)
{
// store reference to context
EditorContext = context;
}
#region IDisposable Members
public void Dispose()
{
}
#endregion
/// <summary>
/// Pre-process mouse messages to detect drag-and-drop of selections
/// </summary>
/// <param name="inEvtDispId">event id</param>
/// <param name="pIEventObj">event object</param>
/// <returns>S_FALSE to continue default processing, S_OK to prevent further processing</returns>
internal int PreHandleEvent(int inEvtDispId, IHTMLEventObj pIEventObj)
{
switch (inEvtDispId)
{
// pre-handle mouse events
case DISPID_HTMLELEMENTEVENTS2.ONMOUSEDOWN:
return PreHandleMouseDown(inEvtDispId, pIEventObj);
case DISPID_HTMLELEMENTEVENTS2.ONMOUSEUP:
return PreHandleMouseUp(inEvtDispId, pIEventObj);
case DISPID_HTMLELEMENTEVENTS2.ONMOUSEMOVE:
return PreHandleMouseMove(inEvtDispId, pIEventObj);
// allow all other events to pass through
default:
return HRESULT.S_FALSE;
}
}
// <summary>
/// Pre-process mouse messages to detect drag-and-drop of selections
/// </summary>
/// <param name="inEvtDispId">event id</param>
/// <param name="pIEventObj">event object</param>
/// <returns>S_FALSE to continue default processing, S_OK to prevent further processing</returns>
private int PreHandleMouseDown(int inEvtDispId, IHTMLEventObj pIEventObj)
{
// if this is a left mouse down over an existing selection then start
// watching for a drag and drop
if (CouldBeDragBegin(pIEventObj))
{
// set state for drag/drop detection
watchForDragDrop = true;
dragDropWatchStartPoint = new Point(pIEventObj.clientX, pIEventObj.clientY);
// prevent MSHTML from even knowing about the MouseDown! (otherwise he
// will capture the mouse, start drag/drop detection, and generally get
// in a very confused state)
return HRESULT.S_OK;
}
else
{
// allow default processing
return HRESULT.S_FALSE;
}
}
/// <summary>
/// Might this be a drag begin>
/// </summary>
/// <param name="pIEventObj"></param>></param>
/// <returns>true if it could be a drag begin</returns>
protected bool CouldBeDragBegin(IHTMLEventObj pIEventObj)
{
// if the left mouse button is down
if ((Control.MouseButtons & MouseButtons.Left) > 0)
{
return true;
}
else
return false;
}
// <summary>
/// Pre-process mouse messages to detect drag-and-drop of selections
/// </summary>
/// <param name="inEvtDispId">event id</param>
/// <param name="pIEventObj">event object</param>
/// <returns>S_FALSE to continue default processing, S_OK to prevent further processing</returns>
private int PreHandleMouseMove(int inEvtDispId, IHTMLEventObj pIEventObj)
{
if (watchForDragDrop)
{
// compare against drag watch start point
Point currentPoint = new Point(pIEventObj.clientX, pIEventObj.clientY);
if (DragDropHelper.PointOutsideDragSize(currentPoint, dragDropWatchStartPoint))
{
// no longer watching
watchForDragDrop = false;
DoDragDrop(pIEventObj);
}
// suppress event (MSHTML blocked from seeing mouse-moves while we are
// doing drag-drop detection and processing)
return HRESULT.S_OK;
}
else
{
// continue default processing
return HRESULT.S_FALSE;
}
}
protected abstract void DoDragDrop(IHTMLEventObj pIEventObj);
/// <summary>
/// Pre-process mouse messages to detect drag-and-drop of selections
/// </summary>
/// <param name="inEvtDispId">event id</param>
/// <param name="pIEventObj">event object</param>
/// <returns>S_FALSE to continue default processing, S_OK to prevent further processing</returns>
private int PreHandleMouseUp(int inEvtDispId, IHTMLEventObj pIEventObj)
{
// if we are watching for a drag and drop and we didn't get one then
// position the caret where the mouse originally went down
if (watchForDragDrop)
{
// no longer watching for drag drop
watchForDragDrop = false;
// handled internally, don't let MSHTML see it
return HRESULT.S_OK;
}
else
{
// do default processing
return HRESULT.S_FALSE;
}
}
protected class Undo : IDisposable
{
private IHtmlEditorComponentContext _editorContext;
public Undo(IHtmlEditorComponentContext editorContext)
{
_editorContext = editorContext;
editorContext.MarkupServices.BeginUndoUnit(Guid.NewGuid().ToString());
}
public void Dispose()
{
_editorContext.MarkupServices.EndUndoUnit();
}
}
/// <summary>
/// Editor context
/// </summary>
protected IHtmlEditorComponentContext EditorContext { get; private set; }
/// <summary>
/// Watch for a drag drop?
/// </summary>
bool watchForDragDrop = false;
/// <summary>
/// Start point to watch for drag drop from
/// </summary>
Point dragDropWatchStartPoint;
}
internal class SmartContentDragAndDropSource : BehaviorDragAndDropSource
{
public SmartContentDragAndDropSource(IHtmlEditorComponentContext context)
: base(context)
{
}
protected override void DoDragDrop(IHTMLEventObj pIEventObj)
{
SmartContentSelection smartSelection = EditorContext.Selection as SmartContentSelection;
if (smartSelection == null)
return;
// allow each of the drop source format handlers a chance to create the
// drop-source data object
IDataObject dataObject = SmartContentDataObject.CreateFrom(smartSelection.HTMLElement, EditorContext.EditorId);
// do the drag and drop
using (new Undo(EditorContext))
{
EditorContext.DoDragDrop(dataObject, DragDropEffects.Move);
}
// If the user dragged into a restrcited area(like an edit field) the markup range is destroyed
// when we strip out the html, so dont try to select it
IHTMLElement e = smartSelection.HTMLElement;
if (e.sourceIndex < 0 || e.document == null || ((IHTMLDocument2)e.document).body == null)
return;
//re-select the smartContent item now that the drag/dropis done
SmartContentSelection.SelectIfSmartContentElement(EditorContext, smartSelection.HTMLElement, smartSelection.ContentState);
// Update the area around the smart content for inline spelling
MarkupRange range = EditorContext.MarkupServices.CreateMarkupRange(smartSelection.HTMLElement, true);
EditorContext.DamageServices.AddDamage(range);
}
}
internal class DisabledImageDragAndDropSource : BehaviorDragAndDropSource
{
public DisabledImageDragAndDropSource(IHtmlEditorComponentContext context)
: base(context)
{
}
protected override void DoDragDrop(IHTMLEventObj pIEventObj)
{
IHTMLElement element = pIEventObj.srcElement;
// Make sure the element is an image.
IHTMLImgElement imgElement = element as IHTMLImgElement;
if (imgElement == null)
return;
// We'll need to uniquely identify this image when its inserted at a new spot.
string oldElementId = element.id;
element.id = Guid.NewGuid().ToString();
IDataObject dataObject = SmartContentDataObject.CreateFrom(element, EditorContext.EditorId);
// do the drag and drop
using (new Undo(EditorContext))
{
EditorContext.DoDragDrop(dataObject, DragDropEffects.Move);
}
// Revert back to the old id after drag/drop is done.
element.id = oldElementId;
}
}
public class SmartContentDataObject
{
/// <summary>
/// Attempt to create a smart content data object from the selection.
/// </summary>
/// <returns>data object (if could be created), otherwise null</returns>
public static IDataObject CreateFrom(IHTMLElement element, string editorId)
{
// create a new new data object
DataObject dataObject = new DataObject();
//add internal format
if (element != null)
{
dataObject.SetData(INTERNAL_SMART_CONTENT_DATAFORMAT, element.id);
dataObject.SetData(INSTANCE_ID_DATAFORMAT, editorId);
}
// return the data object
return dataObject;
}
public static bool IsContainedIn(IDataObject dataObject)
{
return OleDataObjectHelper.GetDataPresentSafe(dataObject, INSTANCE_ID_DATAFORMAT);
}
/// <summary>
/// Name of data format used to represent the instance id of a presentation editor
/// (used to identify an internal operation vs. a cross-process one)
/// </summary>
internal const string INSTANCE_ID_DATAFORMAT = "OpenLiveWriterInstanceId";
/// <summary>
/// Name of data format for moving around items internaly
/// </summary>
internal const string INTERNAL_SMART_CONTENT_DATAFORMAT = "OpenLiveWriterInternalSmartContent";
}
}
| |
/*
Microsoft Automatic Graph Layout,MSAGL
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
""Software""), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Windows.Forms;
using Microsoft.Msagl.Drawing;
namespace Microsoft.Msagl.GraphViewerGdi {
internal partial class SaveViewAsImageForm : Form {
readonly GViewer gViewer;
internal SaveViewAsImageForm(GViewer gViewerControl) {
InitializeComponent();
saveCurrentView.Checked = gViewerControl.SaveCurrentViewInImage;
saveTotalView.Checked = !gViewerControl.SaveCurrentViewInImage;
gViewer = gViewerControl;
CancelButton = cancelButton;
imageScale.TickStyle = TickStyle.Both;
imageScale.TickFrequency = 5;
imageScale.Minimum = 10;
imageScale.Maximum = 100;
imageScale.Value = imageScale.Minimum;
SetScaleLabelTexts();
imageScale.ValueChanged += imageScale_ValueChanged;
saveCurrentView.CheckedChanged += saveCurrentView_CheckedChanged;
toolTip.SetToolTip(saveInTextBox, "The default file format is JPG");
saveInTextBox.Text = "*.jpg";
}
double ImageScale {
get {
double span = imageScale.Maximum - imageScale.Minimum;
double l = (imageScale.Value - imageScale.Minimum)/span;
return 1.0 + l*9;
}
}
string FileName {
get { return saveInTextBox.Text; }
}
void saveCurrentView_CheckedChanged(object sender, EventArgs e) {
SetScaleLabelTexts();
gViewer.SaveCurrentViewInImage = saveCurrentView.Checked;
}
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider",
MessageId = "System.String.Format(System.String,System.Object)")]
void imageScale_ValueChanged(object sender, EventArgs e) {
toolTip.SetToolTip(imageScale, String.Format("Image scale is {0}", ImageScale));
SetScaleLabelTexts();
}
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider",
MessageId = "System.String.Format(System.String,System.Object,System.Object)")]
void SetScaleLabelTexts() {
int w, h;
if (saveTotalView.Checked) {
w = (int) Math.Ceiling(gViewer.Graph.Width*ImageScale);
h = (int) Math.Ceiling(gViewer.Graph.Height*ImageScale);
}
else {
w = (int) (gViewer.SrcRect.Width*ImageScale);
h = (int) (gViewer.SrcRect.Height*ImageScale);
}
imageSizeLabel.Text = String.Format("Image size : {0} x {1}", w, h);
}
void browseButton_Click(object sender, EventArgs e) {
var saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter =
"JPG Files(*.JPG)|*.JPG|BMP Files(*.BMP)|*.BMP|GIF Files(*.GIF)|*.GIF|Png Files(*.Png)|*.Png|SVG files(*.svg)|*.SVG";
saveFileDialog.OverwritePrompt = false;
DialogResult dialogResult = saveFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK) {
saveInTextBox.Text = saveFileDialog.FileName;
okButton.Focus(); //to enable hitting the OK button
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes"),
SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions"),
SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters",
MessageId = "System.Windows.Forms.MessageBox.Show(System.String)")]
void OkButtonClick(object sender, EventArgs e) {
if (String.IsNullOrEmpty(saveInTextBox.Text)) {
MessageBox.Show("File name is not set");
return;
}
Cursor c = Cursor;
Cursor = Cursors.WaitCursor;
try {
int w, h;
if (saveCurrentView.Checked) {
w = (int) Math.Ceiling(gViewer.SrcRect.Width*ImageScale);
h = (int) Math.Ceiling(gViewer.SrcRect.Height*ImageScale);
}
else {
w = (int) Math.Ceiling(gViewer.Graph.Width*ImageScale);
h = (int) Math.Ceiling(gViewer.Graph.Height*ImageScale);
}
Bitmap bitmap = null;
string ext = GetFileNameExtension();
if (ext == ".EMF" || ext == ".WMF") DrawVectorGraphics(w, h);
else if (ext == ".SVG") SvgGraphWriter.Write(gViewer.Graph, FileName, null, null, 4);
else {
bitmap = new Bitmap(w, h, PixelFormat.Format32bppPArgb);
using (Graphics graphics = Graphics.FromImage(bitmap))
DrawGeneral(w, h, graphics);
}
AdjustFileName();
if (bitmap != null)
bitmap.Save(saveInTextBox.Text);
}
catch (Exception ex) {
MessageBox.Show("Cannot save the image: " + ex.Message);
Cursor = c;
return;
}
Cursor = c;
Close();
}
void DrawGeneral(int w, int h, Graphics graphics) {
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
if (saveCurrentView.Checked) DrawCurrent(graphics);
else DrawAll(w, h, graphics);
}
void DrawAll(int w, int h, Graphics graphics) {
//fill the whole image
graphics.FillRectangle(new SolidBrush(Draw.MsaglColorToDrawingColor(gViewer.Graph.Attr.BackgroundColor)),
new RectangleF(0, 0, w, h));
//calculate the transform
double s = ImageScale;
Graph g = gViewer.Graph;
double x = 0.5*w - s*(g.Left + 0.5*g.Width);
double y = 0.5*h + s*(g.Bottom + 0.5*g.Height);
graphics.Transform = new Matrix((float) s, 0, 0, (float) -s, (float) x, (float) y);
Draw.DrawPrecalculatedLayoutObject(graphics, gViewer.DGraph);
}
void DrawCurrent(Graphics graphics) {
graphics.Transform = gViewer.CurrentTransform();
graphics.FillRectangle(new SolidBrush(Draw.MsaglColorToDrawingColor(gViewer.Graph.Attr.BackgroundColor)),
gViewer.SrcRect);
graphics.Clip = new Region(gViewer.SrcRect);
Draw.DrawPrecalculatedLayoutObject(graphics, gViewer.DGraph);
}
void DrawVectorGraphics(int w, int h) {
Graphics graphics = CreateGraphics();
IntPtr ipHdc = graphics.GetHdc();
//Create a new empty metafile from the memory stream
Stream outputStream = File.OpenWrite(FileName);
var MetafileToDisplay = new Metafile(outputStream, ipHdc, EmfType.EmfOnly);
//Now that we have a loaded metafile, we get rid of that Graphics object
graphics.ReleaseHdc(ipHdc);
graphics.Dispose();
//Reload the graphics object with the newly created metafile.
graphics = Graphics.FromImage(MetafileToDisplay);
DrawGeneral(w, h, graphics);
//Get rid of the graphics object that we created
graphics.Dispose();
outputStream.Close();
}
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower")]
void AdjustFileName() {
string ext = GetFileNameExtension();
if (ext == ".BMP" || ext == ".JPG" || ext == ".GIF" || ext == ".EMF" || ext == ".PNG" || ext == ".WMF" ||
ext == ".SVG") {
//do nothing
}
else
saveInTextBox.Text = saveInTextBox.Text.ToLower() + ".png";
}
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToUpper")]
string GetFileNameExtension() {
return Path.GetExtension(FileName).ToUpper();
}
void cancelButton_Click(object sender, EventArgs e) {
Close();
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
namespace XrmFramework.Definitions
{
[GeneratedCode("XrmFramework", "1.0")]
[EntityDefinition]
[ExcludeFromCodeCoverage]
[DefinitionManagerIgnore]
public static class TeamDefinition
{
public const string EntityName = "team";
public const string EntityCollectionName = "teams";
public const String TeamMembershipRelationName = "teammembership";
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public static class Columns
{
/// <summary>
///
/// Type : Lookup
/// Validity : Read | Create | Update | AdvancedFind
/// </summary>
[AttributeMetadata(AttributeTypeCode.Lookup)]
[CrmLookup(BusinessUnitDefinition.EntityName, BusinessUnitDefinition.Columns.Id, RelationshipName = ManyToOneRelationships.business_unit_teams)]
public const string BusinessUnitId = "businessunitid";
/// <summary>
///
/// Type : String
/// Validity : Read | Create | Update | AdvancedFind
/// </summary>
[AttributeMetadata(AttributeTypeCode.String)]
[PrimaryAttribute(PrimaryAttributeType.Name)]
[StringLength(160)]
public const string Name = "name";
/// <summary>
///
/// Type : Lookup
/// Validity : Read | Create
/// </summary>
[AttributeMetadata(AttributeTypeCode.Lookup)]
[CrmLookup("knowledgearticle", "knowledgearticleid", RelationshipName = "knowledgearticle_Teams")]
[CrmLookup("opportunity", "opportunityid", RelationshipName = "opportunity_Teams")]
public const string RegardingObjectId = "regardingobjectid";
/// <summary>
///
/// Type : Uniqueidentifier
/// Validity : Read | Create | AdvancedFind
/// </summary>
[AttributeMetadata(AttributeTypeCode.Uniqueidentifier)]
[PrimaryAttribute(PrimaryAttributeType.Id)]
public const string Id = "teamid";
/// <summary>
///
/// Type : Lookup
/// Validity : Read | Create | AdvancedFind
/// </summary>
[AttributeMetadata(AttributeTypeCode.Lookup)]
[CrmLookup("teamtemplate", "teamtemplateid", RelationshipName = "teamtemplate_Teams")]
public const string TeamTemplateId = "teamtemplateid";
/// <summary>
///
/// Type : Picklist (TypeDEquipe)
/// Validity : Read | Create | AdvancedFind
/// </summary>
[AttributeMetadata(AttributeTypeCode.Picklist)]
[OptionSet(typeof(TypeDEquipe))]
public const string TeamType = "teamtype";
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public static class ManyToManyRelationships
{
[Relationship(SystemUserDefinition.EntityName, EntityRole.Referencing, "teammembership", "systemuserid")]
public const string teammembership_association = "teammembership_association";
[Relationship("fieldsecurityprofile", EntityRole.Referencing, "teamprofiles", "fieldsecurityprofileid")]
public const string teamprofiles_association = "teamprofiles_association";
[Relationship(RoleDefinition.EntityName, EntityRole.Referencing, "teamroles", "roleid")]
public const string teamroles_association = "teamroles_association";
[Relationship("syncattributemappingprofile", EntityRole.Referencing, "teamsyncattributemappingprofiles", "syncattributemappingprofileid")]
public const string teamsyncattributemappingprofiles_association = "teamsyncattributemappingprofiles_association";
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public static class ManyToOneRelationships
{
[Relationship(BusinessUnitDefinition.EntityName, EntityRole.Referencing, "businessunitid", TeamDefinition.Columns.BusinessUnitId)]
public const string business_unit_teams = "business_unit_teams";
[Relationship("contact", EntityRole.Referencing, "regardingobjectid_contact", "")]
public const string contact_Teams = "contact_Teams";
[Relationship("knowledgearticle", EntityRole.Referencing, "regardingobjectid_knowledgearticle", TeamDefinition.Columns.RegardingObjectId)]
public const string knowledgearticle_Teams = "knowledgearticle_Teams";
[Relationship(SystemUserDefinition.EntityName, EntityRole.Referencing, "createdonbehalfby", "createdonbehalfby")]
public const string lk_team_createdonbehalfby = "lk_team_createdonbehalfby";
[Relationship(SystemUserDefinition.EntityName, EntityRole.Referencing, "modifiedonbehalfby", "modifiedonbehalfby")]
public const string lk_team_modifiedonbehalfby = "lk_team_modifiedonbehalfby";
[Relationship(SystemUserDefinition.EntityName, EntityRole.Referencing, "administratorid", "administratorid")]
public const string lk_teambase_administratorid = "lk_teambase_administratorid";
[Relationship(SystemUserDefinition.EntityName, EntityRole.Referencing, "createdby", "createdby")]
public const string lk_teambase_createdby = "lk_teambase_createdby";
[Relationship(SystemUserDefinition.EntityName, EntityRole.Referencing, "modifiedby", "modifiedby")]
public const string lk_teambase_modifiedby = "lk_teambase_modifiedby";
[Relationship("opportunity", EntityRole.Referencing, "regardingobjectid_opportunity", TeamDefinition.Columns.RegardingObjectId)]
public const string opportunity_Teams = "opportunity_Teams";
[Relationship("organization", EntityRole.Referencing, "organizationid_organization", "organizationid")]
public const string organization_teams = "organization_teams";
[Relationship("processstage", EntityRole.Referencing, "stageid_processstage", "stageid")]
public const string processstage_teams = "processstage_teams";
[Relationship("queue", EntityRole.Referencing, "queueid", "queueid")]
public const string queue_team = "queue_team";
[Relationship("teamtemplate", EntityRole.Referencing, "associatedteamtemplateid", TeamDefinition.Columns.TeamTemplateId)]
public const string teamtemplate_Teams = "teamtemplate_Teams";
[Relationship("transactioncurrency", EntityRole.Referencing, "transactioncurrencyid", "transactioncurrencyid")]
public const string TransactionCurrency_Team = "TransactionCurrency_Team";
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public static class OneToManyRelationships
{
[Relationship("importfile", EntityRole.Referenced, "ImportFile_Team", "recordsownerid")]
public const string ImportFile_Team = "ImportFile_Team";
[Relationship("lead", EntityRole.Referenced, "lead_owning_team", "owningteam")]
public const string lead_owning_team = "lead_owning_team";
[Relationship("li_inmail", EntityRole.Referenced, "li_inmail_team_owningteam", "owningteam")]
public const string li_inmail_team_owningteam = "li_inmail_team_owningteam";
[Relationship("li_message", EntityRole.Referenced, "li_message_team_owningteam", "owningteam")]
public const string li_message_team_owningteam = "li_message_team_owningteam";
[Relationship("li_pointdrivepresentationviewed", EntityRole.Referenced, "li_pointdrivepresentationviewed_team_owningteam", "owningteam")]
public const string li_pointdrivepresentationviewed_team_owningteam = "li_pointdrivepresentationviewed_team_owningteam";
[Relationship("msdyn_approval", EntityRole.Referenced, "msdyn_approval_team_owningteam", "owningteam")]
public const string msdyn_approval_team_owningteam = "msdyn_approval_team_owningteam";
[Relationship("msdyn_bookingalert", EntityRole.Referenced, "msdyn_bookingalert_team_owningteam", "owningteam")]
public const string msdyn_bookingalert_team_owningteam = "msdyn_bookingalert_team_owningteam";
[Relationship("msdyn_project", EntityRole.Referenced, "msdyn_team_msdyn_project_projectteamid", "msdyn_projectteamid")]
public const string msdyn_team_msdyn_project_projectteamid = "msdyn_team_msdyn_project_projectteamid";
[Relationship("msfp_surveyinvite", EntityRole.Referenced, "msfp_surveyinvite_team_owningteam", "owningteam")]
public const string msfp_surveyinvite_team_owningteam = "msfp_surveyinvite_team_owningteam";
[Relationship("msfp_surveyresponse", EntityRole.Referenced, "msfp_surveyresponse_team_owningteam", "owningteam")]
public const string msfp_surveyresponse_team_owningteam = "msfp_surveyresponse_team_owningteam";
[Relationship("postfollow", EntityRole.Referenced, "OwningTeam_postfollows", "owningteam")]
public const string OwningTeam_postfollows = "OwningTeam_postfollows";
[Relationship("account", EntityRole.Referenced, "team_accounts", "owningteam")]
public const string team_accounts = "team_accounts";
[Relationship("actioncardusersettings", EntityRole.Referenced, "team_actioncardusersettings", "owningteam")]
public const string team_actioncardusersettings = "team_actioncardusersettings";
[Relationship("activitypointer", EntityRole.Referenced, "team_activity", "owningteam")]
public const string team_activity = "team_activity";
[Relationship("adminsettingsentity", EntityRole.Referenced, "team_adminsettingsentity", "owningteam")]
public const string team_adminsettingsentity = "team_adminsettingsentity";
[Relationship("annotation", EntityRole.Referenced, "team_annotations", "owningteam")]
public const string team_annotations = "team_annotations";
[Relationship("appointment", EntityRole.Referenced, "team_appointment", "owningteam")]
public const string team_appointment = "team_appointment";
[Relationship("asyncoperation", EntityRole.Referenced, "team_asyncoperation", "owningteam")]
public const string team_asyncoperation = "team_asyncoperation";
[Relationship("asyncoperation", EntityRole.Referenced, "Team_AsyncOperations", "regardingobjectid")]
public const string Team_AsyncOperations = "Team_AsyncOperations";
[Relationship("bookableresource", EntityRole.Referenced, "team_bookableresource", "owningteam")]
public const string team_bookableresource = "team_bookableresource";
[Relationship("bookableresourcebooking", EntityRole.Referenced, "team_bookableresourcebooking", "owningteam")]
public const string team_bookableresourcebooking = "team_bookableresourcebooking";
[Relationship("bookableresourcebookingexchangesyncidmapping", EntityRole.Referenced, "team_bookableresourcebookingexchangesyncidmapping", "owningteam")]
public const string team_bookableresourcebookingexchangesyncidmapping = "team_bookableresourcebookingexchangesyncidmapping";
[Relationship("bookableresourcebookingheader", EntityRole.Referenced, "team_bookableresourcebookingheader", "owningteam")]
public const string team_bookableresourcebookingheader = "team_bookableresourcebookingheader";
[Relationship("bookableresourcecategory", EntityRole.Referenced, "team_bookableresourcecategory", "owningteam")]
public const string team_bookableresourcecategory = "team_bookableresourcecategory";
[Relationship("bookableresourcecategoryassn", EntityRole.Referenced, "team_bookableresourcecategoryassn", "owningteam")]
public const string team_bookableresourcecategoryassn = "team_bookableresourcecategoryassn";
[Relationship("bookableresourcecharacteristic", EntityRole.Referenced, "team_bookableresourcecharacteristic", "owningteam")]
public const string team_bookableresourcecharacteristic = "team_bookableresourcecharacteristic";
[Relationship("bookableresourcegroup", EntityRole.Referenced, "team_bookableresourcegroup", "owningteam")]
public const string team_bookableresourcegroup = "team_bookableresourcegroup";
[Relationship("bookingstatus", EntityRole.Referenced, "team_bookingstatus", "owningteam")]
public const string team_bookingstatus = "team_bookingstatus";
[Relationship("bulkdeletefailure", EntityRole.Referenced, "Team_BulkDeleteFailures", "regardingobjectid")]
public const string Team_BulkDeleteFailures = "Team_BulkDeleteFailures";
[Relationship("bulkoperation", EntityRole.Referenced, "team_BulkOperation", "owningteam")]
public const string team_BulkOperation = "team_BulkOperation";
[Relationship("bulkoperationlog", EntityRole.Referenced, "team_bulkoperationlog", "owningteam")]
public const string team_bulkoperationlog = "team_bulkoperationlog";
[Relationship("campaignactivity", EntityRole.Referenced, "team_campaignactivity", "owningteam")]
public const string team_campaignactivity = "team_campaignactivity";
[Relationship("campaignresponse", EntityRole.Referenced, "team_campaignresponse", "owningteam")]
public const string team_campaignresponse = "team_campaignresponse";
[Relationship("campaign", EntityRole.Referenced, "team_Campaigns", "owningteam")]
public const string team_Campaigns = "team_Campaigns";
[Relationship("cgo_intervention", EntityRole.Referenced, "team_cgo_intervention", "owningteam")]
public const string team_cgo_intervention = "team_cgo_intervention";
[Relationship("cgo_servicecontract", EntityRole.Referenced, "team_cgo_servicecontract", "owningteam")]
public const string team_cgo_servicecontract = "team_cgo_servicecontract";
[Relationship("cgo_testpowerapps", EntityRole.Referenced, "team_cgo_testpowerapps", "owningteam")]
public const string team_cgo_testpowerapps = "team_cgo_testpowerapps";
[Relationship("cgo_testunmanaged", EntityRole.Referenced, "team_cgo_testunmanaged", "owningteam")]
public const string team_cgo_testunmanaged = "team_cgo_testunmanaged";
[Relationship("channelaccessprofile", EntityRole.Referenced, "team_channelaccessprofile", "owningteam")]
public const string team_channelaccessprofile = "team_channelaccessprofile";
[Relationship("characteristic", EntityRole.Referenced, "team_characteristic", "owningteam")]
public const string team_characteristic = "team_characteristic";
[Relationship("connection", EntityRole.Referenced, "team_connections1", "record1id")]
public const string team_connections1 = "team_connections1";
[Relationship("connection", EntityRole.Referenced, "team_connections2", "record2id")]
public const string team_connections2 = "team_connections2";
[Relationship("connector", EntityRole.Referenced, "team_connector", "owningteam")]
public const string team_connector = "team_connector";
[Relationship("contact", EntityRole.Referenced, "team_contacts", "owningteam")]
public const string team_contacts = "team_contacts";
[Relationship("contractdetail", EntityRole.Referenced, "team_contractdetail", "owningteam")]
public const string team_contractdetail = "team_contractdetail";
[Relationship("convertrule", EntityRole.Referenced, "team_convertrule", "owningteam")]
public const string team_convertrule = "team_convertrule";
[Relationship("customeropportunityrole", EntityRole.Referenced, "team_customer_opportunity_roles", "owningteam")]
public const string team_customer_opportunity_roles = "team_customer_opportunity_roles";
[Relationship("customerrelationship", EntityRole.Referenced, "team_customer_relationship", "owningteam")]
public const string team_customer_relationship = "team_customer_relationship";
[Relationship("duplicaterecord", EntityRole.Referenced, "Team_DuplicateBaseRecord", "baserecordid")]
public const string Team_DuplicateBaseRecord = "Team_DuplicateBaseRecord";
[Relationship("duplicaterecord", EntityRole.Referenced, "Team_DuplicateMatchingRecord", "duplicaterecordid")]
public const string Team_DuplicateMatchingRecord = "Team_DuplicateMatchingRecord";
[Relationship("duplicaterule", EntityRole.Referenced, "team_DuplicateRules", "owningteam")]
public const string team_DuplicateRules = "team_DuplicateRules";
[Relationship("dynamicpropertyinstance", EntityRole.Referenced, "team_DynamicPropertyInstance", "owningteam")]
public const string team_DynamicPropertyInstance = "team_DynamicPropertyInstance";
[Relationship("email", EntityRole.Referenced, "team_email", "owningteam")]
public const string team_email = "team_email";
[Relationship("template", EntityRole.Referenced, "team_email_templates", "owningteam")]
public const string team_email_templates = "team_email_templates";
[Relationship("emailserverprofile", EntityRole.Referenced, "team_emailserverprofile", "owningteam")]
public const string team_emailserverprofile = "team_emailserverprofile";
[Relationship("entitlement", EntityRole.Referenced, "team_entitlement", "owningteam")]
public const string team_entitlement = "team_entitlement";
[Relationship("entitlementchannel", EntityRole.Referenced, "team_entitlementchannel", "owningteam")]
public const string team_entitlementchannel = "team_entitlementchannel";
[Relationship("entitlemententityallocationtypemapping", EntityRole.Referenced, "team_entitlemententityallocationtypemapping", "owningteam")]
public const string team_entitlemententityallocationtypemapping = "team_entitlemententityallocationtypemapping";
[Relationship("entityanalyticsconfig", EntityRole.Referenced, "team_entityanalyticsconfig", "owningteam")]
public const string team_entityanalyticsconfig = "team_entityanalyticsconfig";
[Relationship("exchangesyncidmapping", EntityRole.Referenced, "team_exchangesyncidmapping", "owningteam")]
public const string team_exchangesyncidmapping = "team_exchangesyncidmapping";
[Relationship("externalparty", EntityRole.Referenced, "team_externalparty", "owningteam")]
public const string team_externalparty = "team_externalparty";
[Relationship("fax", EntityRole.Referenced, "team_fax", "owningteam")]
public const string team_fax = "team_fax";
[Relationship("goal", EntityRole.Referenced, "team_goal", "owningteam")]
public const string team_goal = "team_goal";
[Relationship("goal", EntityRole.Referenced, "team_goal_goalowner", "goalownerid")]
public const string team_goal_goalowner = "team_goal_goalowner";
[Relationship("goalrollupquery", EntityRole.Referenced, "team_goalrollupquery", "owningteam")]
public const string team_goalrollupquery = "team_goalrollupquery";
[Relationship("importdata", EntityRole.Referenced, "team_ImportData", "owningteam")]
public const string team_ImportData = "team_ImportData";
[Relationship("importfile", EntityRole.Referenced, "team_ImportFiles", "owningteam")]
public const string team_ImportFiles = "team_ImportFiles";
[Relationship("importlog", EntityRole.Referenced, "team_ImportLogs", "owningteam")]
public const string team_ImportLogs = "team_ImportLogs";
[Relationship("importmap", EntityRole.Referenced, "team_ImportMaps", "owningteam")]
public const string team_ImportMaps = "team_ImportMaps";
[Relationship("import", EntityRole.Referenced, "team_Imports", "owningteam")]
public const string team_Imports = "team_Imports";
[Relationship("incidentresolution", EntityRole.Referenced, "team_incidentresolution", "owningteam")]
public const string team_incidentresolution = "team_incidentresolution";
[Relationship("incident", EntityRole.Referenced, "team_incidents", "owningteam")]
public const string team_incidents = "team_incidents";
[Relationship("interactionforemail", EntityRole.Referenced, "team_new_interactionforemail", "owningteam")]
public const string team_interactionforemail = "team_interactionforemail";
[Relationship("invoicedetail", EntityRole.Referenced, "team_invoicedetail", "owningteam")]
public const string team_invoicedetail = "team_invoicedetail";
[Relationship("invoice", EntityRole.Referenced, "team_invoices", "owningteam")]
public const string team_invoices = "team_invoices";
[Relationship("knowledgearticle", EntityRole.Referenced, "team_knowledgearticle", "owningteam")]
public const string team_knowledgearticle = "team_knowledgearticle";
[Relationship("knowledgearticleincident", EntityRole.Referenced, "team_knowledgearticleincident", "owningteam")]
public const string team_knowledgearticleincident = "team_knowledgearticleincident";
[Relationship("letter", EntityRole.Referenced, "team_letter", "owningteam")]
public const string team_letter = "team_letter";
[Relationship("list", EntityRole.Referenced, "team_list", "owningteam")]
public const string team_list = "team_list";
[Relationship("mailbox", EntityRole.Referenced, "team_mailbox", "owningteam")]
public const string team_mailbox = "team_mailbox";
[Relationship("mailboxtrackingcategory", EntityRole.Referenced, "team_mailboxtrackingcategory", "owningteam")]
public const string team_mailboxtrackingcategory = "team_mailboxtrackingcategory";
[Relationship("mailboxtrackingfolder", EntityRole.Referenced, "team_mailboxtrackingfolder", "owningteam")]
public const string team_mailboxtrackingfolder = "team_mailboxtrackingfolder";
[Relationship("msdyn_accountpricelist", EntityRole.Referenced, "team_msdyn_accountpricelist", "owningteam")]
public const string team_msdyn_accountpricelist = "team_msdyn_accountpricelist";
[Relationship("msdyn_actioncardregarding", EntityRole.Referenced, "team_msdyn_actioncardregarding", "owningteam")]
public const string team_msdyn_actioncardregarding = "team_msdyn_actioncardregarding";
[Relationship("msdyn_actioncardrolesetting", EntityRole.Referenced, "team_msdyn_actioncardrolesetting", "owningteam")]
public const string team_msdyn_actioncardrolesetting = "team_msdyn_actioncardrolesetting";
[Relationship("msdyn_actual", EntityRole.Referenced, "team_msdyn_actual", "owningteam")]
public const string team_msdyn_actual = "team_msdyn_actual";
[Relationship("msdyn_agreement", EntityRole.Referenced, "team_msdyn_agreement", "owningteam")]
public const string team_msdyn_agreement = "team_msdyn_agreement";
[Relationship("msdyn_agreementbookingdate", EntityRole.Referenced, "team_msdyn_agreementbookingdate", "owningteam")]
public const string team_msdyn_agreementbookingdate = "team_msdyn_agreementbookingdate";
[Relationship("msdyn_agreementbookingincident", EntityRole.Referenced, "team_msdyn_agreementbookingincident", "owningteam")]
public const string team_msdyn_agreementbookingincident = "team_msdyn_agreementbookingincident";
[Relationship("msdyn_agreementbookingproduct", EntityRole.Referenced, "team_msdyn_agreementbookingproduct", "owningteam")]
public const string team_msdyn_agreementbookingproduct = "team_msdyn_agreementbookingproduct";
[Relationship("msdyn_agreementbookingservice", EntityRole.Referenced, "team_msdyn_agreementbookingservice", "owningteam")]
public const string team_msdyn_agreementbookingservice = "team_msdyn_agreementbookingservice";
[Relationship("msdyn_agreementbookingservicetask", EntityRole.Referenced, "team_msdyn_agreementbookingservicetask", "owningteam")]
public const string team_msdyn_agreementbookingservicetask = "team_msdyn_agreementbookingservicetask";
[Relationship("msdyn_agreementbookingsetup", EntityRole.Referenced, "team_msdyn_agreementbookingsetup", "owningteam")]
public const string team_msdyn_agreementbookingsetup = "team_msdyn_agreementbookingsetup";
[Relationship("msdyn_agreementinvoicedate", EntityRole.Referenced, "team_msdyn_agreementinvoicedate", "owningteam")]
public const string team_msdyn_agreementinvoicedate = "team_msdyn_agreementinvoicedate";
[Relationship("msdyn_agreementinvoiceproduct", EntityRole.Referenced, "team_msdyn_agreementinvoiceproduct", "owningteam")]
public const string team_msdyn_agreementinvoiceproduct = "team_msdyn_agreementinvoiceproduct";
[Relationship("msdyn_agreementinvoicesetup", EntityRole.Referenced, "team_msdyn_agreementinvoicesetup", "owningteam")]
public const string team_msdyn_agreementinvoicesetup = "team_msdyn_agreementinvoicesetup";
[Relationship("msdyn_agreementsubstatus", EntityRole.Referenced, "team_msdyn_agreementsubstatus", "owningteam")]
public const string team_msdyn_agreementsubstatus = "team_msdyn_agreementsubstatus";
[Relationship("msdyn_aiconfiguration", EntityRole.Referenced, "team_msdyn_aiconfiguration", "owningteam")]
public const string team_msdyn_aiconfiguration = "team_msdyn_aiconfiguration";
[Relationship("msdyn_aifptrainingdocument", EntityRole.Referenced, "team_msdyn_aifptrainingdocument", "owningteam")]
public const string team_msdyn_aifptrainingdocument = "team_msdyn_aifptrainingdocument";
[Relationship("msdyn_aimodel", EntityRole.Referenced, "team_msdyn_aimodel", "owningteam")]
public const string team_msdyn_aimodel = "team_msdyn_aimodel";
[Relationship("msdyn_aiodimage", EntityRole.Referenced, "team_msdyn_aiodimage", "owningteam")]
public const string team_msdyn_aiodimage = "team_msdyn_aiodimage";
[Relationship("msdyn_aiodlabel", EntityRole.Referenced, "team_msdyn_aiodlabel", "owningteam")]
public const string team_msdyn_aiodlabel = "team_msdyn_aiodlabel";
[Relationship("msdyn_aiodtrainingboundingbox", EntityRole.Referenced, "team_msdyn_aiodtrainingboundingbox", "owningteam")]
public const string team_msdyn_aiodtrainingboundingbox = "team_msdyn_aiodtrainingboundingbox";
[Relationship("msdyn_aiodtrainingimage", EntityRole.Referenced, "team_msdyn_aiodtrainingimage", "owningteam")]
public const string team_msdyn_aiodtrainingimage = "team_msdyn_aiodtrainingimage";
[Relationship("msdyn_aitemplate", EntityRole.Referenced, "team_msdyn_aitemplate", "owningteam")]
public const string team_msdyn_aitemplate = "team_msdyn_aitemplate";
[Relationship("msdyn_analysiscomponent", EntityRole.Referenced, "team_msdyn_analysiscomponent", "owningteam")]
public const string team_msdyn_analysiscomponent = "team_msdyn_analysiscomponent";
[Relationship("msdyn_analysisjob", EntityRole.Referenced, "team_msdyn_analysisjob", "owningteam")]
public const string team_msdyn_analysisjob = "team_msdyn_analysisjob";
[Relationship("msdyn_analysisresult", EntityRole.Referenced, "team_msdyn_analysisresult", "owningteam")]
public const string team_msdyn_analysisresult = "team_msdyn_analysisresult";
[Relationship("msdyn_analysisresultdetail", EntityRole.Referenced, "team_msdyn_analysisresultdetail", "owningteam")]
public const string team_msdyn_analysisresultdetail = "team_msdyn_analysisresultdetail";
[Relationship("msdyn_bookingalertstatus", EntityRole.Referenced, "team_msdyn_bookingalertstatus", "owningteam")]
public const string team_msdyn_bookingalertstatus = "team_msdyn_bookingalertstatus";
[Relationship("msdyn_bookingchange", EntityRole.Referenced, "team_msdyn_bookingchange", "owningteam")]
public const string team_msdyn_bookingchange = "team_msdyn_bookingchange";
[Relationship("msdyn_bookingjournal", EntityRole.Referenced, "team_msdyn_bookingjournal", "owningteam")]
public const string team_msdyn_bookingjournal = "team_msdyn_bookingjournal";
[Relationship("msdyn_bookingrule", EntityRole.Referenced, "team_msdyn_bookingrule", "owningteam")]
public const string team_msdyn_bookingrule = "team_msdyn_bookingrule";
[Relationship("msdyn_bookingsetupmetadata", EntityRole.Referenced, "team_msdyn_bookingsetupmetadata", "owningteam")]
public const string team_msdyn_bookingsetupmetadata = "team_msdyn_bookingsetupmetadata";
[Relationship("msdyn_bookingtimestamp", EntityRole.Referenced, "team_msdyn_bookingtimestamp", "owningteam")]
public const string team_msdyn_bookingtimestamp = "team_msdyn_bookingtimestamp";
[Relationship("msdyn_callablecontext", EntityRole.Referenced, "team_msdyn_callablecontext", "owningteam")]
public const string team_msdyn_callablecontext = "team_msdyn_callablecontext";
[Relationship("msdyn_characteristicreqforteammember", EntityRole.Referenced, "team_msdyn_characteristicreqforteammember", "owningteam")]
public const string team_msdyn_characteristicreqforteammember = "team_msdyn_characteristicreqforteammember";
[Relationship("msdyn_connector", EntityRole.Referenced, "team_msdyn_connector", "owningteam")]
public const string team_msdyn_connector = "team_msdyn_connector";
[Relationship("msdyn_contactpricelist", EntityRole.Referenced, "team_msdyn_contactpricelist", "owningteam")]
public const string team_msdyn_contactpricelist = "team_msdyn_contactpricelist";
[Relationship("msdyn_contractlinescheduleofvalue", EntityRole.Referenced, "team_msdyn_contractlinescheduleofvalue", "owningteam")]
public const string team_msdyn_contractlinescheduleofvalue = "team_msdyn_contractlinescheduleofvalue";
[Relationship("msdyn_customerasset", EntityRole.Referenced, "team_msdyn_customerasset", "owningteam")]
public const string team_msdyn_customerasset = "team_msdyn_customerasset";
[Relationship("msdyn_dataexport", EntityRole.Referenced, "team_msdyn_dataexport", "owningteam")]
public const string team_msdyn_dataexport = "team_msdyn_dataexport";
[Relationship("msdyn_delegation", EntityRole.Referenced, "team_msdyn_delegation", "owningteam")]
public const string team_msdyn_delegation = "team_msdyn_delegation";
[Relationship("msdyn_entityrankingrule", EntityRole.Referenced, "team_msdyn_entityrankingrule", "owningteam")]
public const string team_msdyn_entityrankingrule = "team_msdyn_entityrankingrule";
[Relationship("msdyn_estimate", EntityRole.Referenced, "team_msdyn_estimate", "owningteam")]
public const string team_msdyn_estimate = "team_msdyn_estimate";
[Relationship("msdyn_estimateline", EntityRole.Referenced, "team_msdyn_estimateline", "owningteam")]
public const string team_msdyn_estimateline = "team_msdyn_estimateline";
[Relationship("msdyn_expense", EntityRole.Referenced, "team_msdyn_expense", "owningteam")]
public const string team_msdyn_expense = "team_msdyn_expense";
[Relationship("msdyn_expensereceipt", EntityRole.Referenced, "team_msdyn_expensereceipt", "owningteam")]
public const string team_msdyn_expensereceipt = "team_msdyn_expensereceipt";
[Relationship("msdyn_fact", EntityRole.Referenced, "team_msdyn_fact", "owningteam")]
public const string team_msdyn_fact = "team_msdyn_fact";
[Relationship("msdyn_fieldcomputation", EntityRole.Referenced, "team_msdyn_fieldcomputation", "owningteam")]
public const string team_msdyn_fieldcomputation = "team_msdyn_fieldcomputation";
[Relationship("msdyn_fieldservicesetting", EntityRole.Referenced, "team_msdyn_fieldservicesetting", "owningteam")]
public const string team_msdyn_fieldservicesetting = "team_msdyn_fieldservicesetting";
[Relationship("msdyn_findworkevent", EntityRole.Referenced, "team_msdyn_findworkevent", "owningteam")]
public const string team_msdyn_findworkevent = "team_msdyn_findworkevent";
[Relationship("msdyn_flowcardtype", EntityRole.Referenced, "team_msdyn_flowcardtype", "owningteam")]
public const string team_msdyn_flowcardtype = "team_msdyn_flowcardtype";
[Relationship("msdyn_forecastdefinition", EntityRole.Referenced, "team_msdyn_forecastdefinition", "owningteam")]
public const string team_msdyn_forecastdefinition = "team_msdyn_forecastdefinition";
[Relationship("msdyn_forecastinstance", EntityRole.Referenced, "team_msdyn_forecastinstance", "owningteam")]
public const string team_msdyn_forecastinstance = "team_msdyn_forecastinstance";
[Relationship("msdyn_forecastrecurrence", EntityRole.Referenced, "team_msdyn_forecastrecurrence", "owningteam")]
public const string team_msdyn_forecastrecurrence = "team_msdyn_forecastrecurrence";
[Relationship("msdyn_icebreakersconfig", EntityRole.Referenced, "team_msdyn_icebreakersconfig", "owningteam")]
public const string team_msdyn_icebreakersconfig = "team_msdyn_icebreakersconfig";
[Relationship("msdyn_incidenttype", EntityRole.Referenced, "team_msdyn_incidenttype", "owningteam")]
public const string team_msdyn_incidenttype = "team_msdyn_incidenttype";
[Relationship("msdyn_incidenttypecharacteristic", EntityRole.Referenced, "team_msdyn_incidenttypecharacteristic", "owningteam")]
public const string team_msdyn_incidenttypecharacteristic = "team_msdyn_incidenttypecharacteristic";
[Relationship("msdyn_incidenttypeproduct", EntityRole.Referenced, "team_msdyn_incidenttypeproduct", "owningteam")]
public const string team_msdyn_incidenttypeproduct = "team_msdyn_incidenttypeproduct";
[Relationship("msdyn_incidenttypeservice", EntityRole.Referenced, "team_msdyn_incidenttypeservice", "owningteam")]
public const string team_msdyn_incidenttypeservice = "team_msdyn_incidenttypeservice";
[Relationship("msdyn_incidenttypeservicetask", EntityRole.Referenced, "team_msdyn_incidenttypeservicetask", "owningteam")]
public const string team_msdyn_incidenttypeservicetask = "team_msdyn_incidenttypeservicetask";
[Relationship("msdyn_integrationjob", EntityRole.Referenced, "team_msdyn_integrationjob", "owningteam")]
public const string team_msdyn_integrationjob = "team_msdyn_integrationjob";
[Relationship("msdyn_integrationjobdetail", EntityRole.Referenced, "team_msdyn_integrationjobdetail", "owningteam")]
public const string team_msdyn_integrationjobdetail = "team_msdyn_integrationjobdetail";
[Relationship("msdyn_inventoryadjustment", EntityRole.Referenced, "team_msdyn_inventoryadjustment", "owningteam")]
public const string team_msdyn_inventoryadjustment = "team_msdyn_inventoryadjustment";
[Relationship("msdyn_inventoryadjustmentproduct", EntityRole.Referenced, "team_msdyn_inventoryadjustmentproduct", "owningteam")]
public const string team_msdyn_inventoryadjustmentproduct = "team_msdyn_inventoryadjustmentproduct";
[Relationship("msdyn_inventoryjournal", EntityRole.Referenced, "team_msdyn_inventoryjournal", "owningteam")]
public const string team_msdyn_inventoryjournal = "team_msdyn_inventoryjournal";
[Relationship("msdyn_inventorytransfer", EntityRole.Referenced, "team_msdyn_inventorytransfer", "owningteam")]
public const string team_msdyn_inventorytransfer = "team_msdyn_inventorytransfer";
[Relationship("msdyn_invoicelinetransaction", EntityRole.Referenced, "team_msdyn_invoicelinetransaction", "owningteam")]
public const string team_msdyn_invoicelinetransaction = "team_msdyn_invoicelinetransaction";
[Relationship("msdyn_journal", EntityRole.Referenced, "team_msdyn_journal", "owningteam")]
public const string team_msdyn_journal = "team_msdyn_journal";
[Relationship("msdyn_journalline", EntityRole.Referenced, "team_msdyn_journalline", "owningteam")]
public const string team_msdyn_journalline = "team_msdyn_journalline";
[Relationship("msdyn_knowledgearticletemplate", EntityRole.Referenced, "team_msdyn_knowledgearticletemplate", "owningteam")]
public const string team_msdyn_knowledgearticletemplate = "team_msdyn_knowledgearticletemplate";
[Relationship("msdyn_msteamssetting", EntityRole.Referenced, "team_msdyn_msteamssetting", "owningteam")]
public const string team_msdyn_msteamssetting = "team_msdyn_msteamssetting";
[Relationship("msdyn_notesanalysisconfig", EntityRole.Referenced, "team_msdyn_notesanalysisconfig", "owningteam")]
public const string team_msdyn_notesanalysisconfig = "team_msdyn_notesanalysisconfig";
[Relationship("msdyn_opportunitylineresourcecategory", EntityRole.Referenced, "team_msdyn_opportunitylineresourcecategory", "owningteam")]
public const string team_msdyn_opportunitylineresourcecategory = "team_msdyn_opportunitylineresourcecategory";
[Relationship("msdyn_opportunitylinetransaction", EntityRole.Referenced, "team_msdyn_opportunitylinetransaction", "owningteam")]
public const string team_msdyn_opportunitylinetransaction = "team_msdyn_opportunitylinetransaction";
[Relationship("msdyn_opportunitylinetransactioncategory", EntityRole.Referenced, "team_msdyn_opportunitylinetransactioncategory", "owningteam")]
public const string team_msdyn_opportunitylinetransactioncategory = "team_msdyn_opportunitylinetransactioncategory";
[Relationship("msdyn_opportunitylinetransactionclassificatio", EntityRole.Referenced, "team_msdyn_opportunitylinetransactionclassificatio", "owningteam")]
public const string team_msdyn_opportunitylinetransactionclassificatio = "team_msdyn_opportunitylinetransactionclassificatio";
[Relationship("msdyn_opportunitypricelist", EntityRole.Referenced, "team_msdyn_opportunitypricelist", "owningteam")]
public const string team_msdyn_opportunitypricelist = "team_msdyn_opportunitypricelist";
[Relationship("msdyn_orderinvoicingdate", EntityRole.Referenced, "team_msdyn_orderinvoicingdate", "owningteam")]
public const string team_msdyn_orderinvoicingdate = "team_msdyn_orderinvoicingdate";
[Relationship("msdyn_orderinvoicingproduct", EntityRole.Referenced, "team_msdyn_orderinvoicingproduct", "owningteam")]
public const string team_msdyn_orderinvoicingproduct = "team_msdyn_orderinvoicingproduct";
[Relationship("msdyn_orderinvoicingsetup", EntityRole.Referenced, "team_msdyn_orderinvoicingsetup", "owningteam")]
public const string team_msdyn_orderinvoicingsetup = "team_msdyn_orderinvoicingsetup";
[Relationship("msdyn_orderinvoicingsetupdate", EntityRole.Referenced, "team_msdyn_orderinvoicingsetupdate", "owningteam")]
public const string team_msdyn_orderinvoicingsetupdate = "team_msdyn_orderinvoicingsetupdate";
[Relationship("msdyn_orderlineresourcecategory", EntityRole.Referenced, "team_msdyn_orderlineresourcecategory", "owningteam")]
public const string team_msdyn_orderlineresourcecategory = "team_msdyn_orderlineresourcecategory";
[Relationship("msdyn_orderlinetransaction", EntityRole.Referenced, "team_msdyn_orderlinetransaction", "owningteam")]
public const string team_msdyn_orderlinetransaction = "team_msdyn_orderlinetransaction";
[Relationship("msdyn_orderlinetransactioncategory", EntityRole.Referenced, "team_msdyn_orderlinetransactioncategory", "owningteam")]
public const string team_msdyn_orderlinetransactioncategory = "team_msdyn_orderlinetransactioncategory";
[Relationship("msdyn_orderlinetransactionclassification", EntityRole.Referenced, "team_msdyn_orderlinetransactionclassification", "owningteam")]
public const string team_msdyn_orderlinetransactionclassification = "team_msdyn_orderlinetransactionclassification";
[Relationship("msdyn_orderpricelist", EntityRole.Referenced, "team_msdyn_orderpricelist", "owningteam")]
public const string team_msdyn_orderpricelist = "team_msdyn_orderpricelist";
[Relationship("msdyn_payment", EntityRole.Referenced, "team_msdyn_payment", "owningteam")]
public const string team_msdyn_payment = "team_msdyn_payment";
[Relationship("msdyn_paymentdetail", EntityRole.Referenced, "team_msdyn_paymentdetail", "owningteam")]
public const string team_msdyn_paymentdetail = "team_msdyn_paymentdetail";
[Relationship("msdyn_paymentmethod", EntityRole.Referenced, "team_msdyn_paymentmethod", "owningteam")]
public const string team_msdyn_paymentmethod = "team_msdyn_paymentmethod";
[Relationship("msdyn_paymentterm", EntityRole.Referenced, "team_msdyn_paymentterm", "owningteam")]
public const string team_msdyn_paymentterm = "team_msdyn_paymentterm";
[Relationship("msdyn_playbookactivity", EntityRole.Referenced, "team_msdyn_playbookactivity", "owningteam")]
public const string team_msdyn_playbookactivity = "team_msdyn_playbookactivity";
[Relationship("msdyn_playbookactivityattribute", EntityRole.Referenced, "team_msdyn_playbookactivityattribute", "owningteam")]
public const string team_msdyn_playbookactivityattribute = "team_msdyn_playbookactivityattribute";
[Relationship("msdyn_playbookcategory", EntityRole.Referenced, "team_msdyn_playbookcategory", "owningteam")]
public const string team_msdyn_playbookcategory = "team_msdyn_playbookcategory";
[Relationship("msdyn_playbookinstance", EntityRole.Referenced, "team_msdyn_playbookinstance", "owningteam")]
public const string team_msdyn_playbookinstance = "team_msdyn_playbookinstance";
[Relationship("msdyn_playbooktemplate", EntityRole.Referenced, "team_msdyn_playbooktemplate", "owningteam")]
public const string team_msdyn_playbooktemplate = "team_msdyn_playbooktemplate";
[Relationship("msdyn_postalbum", EntityRole.Referenced, "team_msdyn_postalbum", "owningteam")]
public const string team_msdyn_postalbum = "team_msdyn_postalbum";
[Relationship("msdyn_postalcode", EntityRole.Referenced, "team_msdyn_postalcode", "owningteam")]
public const string team_msdyn_postalcode = "team_msdyn_postalcode";
[Relationship("msdyn_priority", EntityRole.Referenced, "team_msdyn_priority", "owningteam")]
public const string team_msdyn_priority = "team_msdyn_priority";
[Relationship("msdyn_project", EntityRole.Referenced, "team_msdyn_project", "owningteam")]
public const string team_msdyn_project = "team_msdyn_project";
[Relationship("msdyn_projectapproval", EntityRole.Referenced, "team_msdyn_projectapproval", "owningteam")]
public const string team_msdyn_projectapproval = "team_msdyn_projectapproval";
[Relationship("msdyn_projectpricelist", EntityRole.Referenced, "team_msdyn_projectpricelist", "owningteam")]
public const string team_msdyn_projectpricelist = "team_msdyn_projectpricelist";
[Relationship("msdyn_projecttask", EntityRole.Referenced, "team_msdyn_projecttask", "owningteam")]
public const string team_msdyn_projecttask = "team_msdyn_projecttask";
[Relationship("msdyn_projecttaskdependency", EntityRole.Referenced, "team_msdyn_projecttaskdependency", "owningteam")]
public const string team_msdyn_projecttaskdependency = "team_msdyn_projecttaskdependency";
[Relationship("msdyn_projecttaskstatususer", EntityRole.Referenced, "team_msdyn_projecttaskstatususer", "owningteam")]
public const string team_msdyn_projecttaskstatususer = "team_msdyn_projecttaskstatususer";
[Relationship("msdyn_projectteam", EntityRole.Referenced, "team_msdyn_projectteam", "owningteam")]
public const string team_msdyn_projectteam = "team_msdyn_projectteam";
[Relationship("msdyn_projecttransactioncategory", EntityRole.Referenced, "team_msdyn_projecttransactioncategory", "owningteam")]
public const string team_msdyn_projecttransactioncategory = "team_msdyn_projecttransactioncategory";
[Relationship("msdyn_purchaseorder", EntityRole.Referenced, "team_msdyn_purchaseorder", "owningteam")]
public const string team_msdyn_purchaseorder = "team_msdyn_purchaseorder";
[Relationship("msdyn_purchaseorderbill", EntityRole.Referenced, "team_msdyn_purchaseorderbill", "owningteam")]
public const string team_msdyn_purchaseorderbill = "team_msdyn_purchaseorderbill";
[Relationship("msdyn_purchaseorderproduct", EntityRole.Referenced, "team_msdyn_purchaseorderproduct", "owningteam")]
public const string team_msdyn_purchaseorderproduct = "team_msdyn_purchaseorderproduct";
[Relationship("msdyn_purchaseorderreceipt", EntityRole.Referenced, "team_msdyn_purchaseorderreceipt", "owningteam")]
public const string team_msdyn_purchaseorderreceipt = "team_msdyn_purchaseorderreceipt";
[Relationship("msdyn_purchaseorderreceiptproduct", EntityRole.Referenced, "team_msdyn_purchaseorderreceiptproduct", "owningteam")]
public const string team_msdyn_purchaseorderreceiptproduct = "team_msdyn_purchaseorderreceiptproduct";
[Relationship("msdyn_purchaseordersubstatus", EntityRole.Referenced, "team_msdyn_purchaseordersubstatus", "owningteam")]
public const string team_msdyn_purchaseordersubstatus = "team_msdyn_purchaseordersubstatus";
[Relationship("msdyn_quotebookingincident", EntityRole.Referenced, "team_msdyn_quotebookingincident", "owningteam")]
public const string team_msdyn_quotebookingincident = "team_msdyn_quotebookingincident";
[Relationship("msdyn_quotebookingproduct", EntityRole.Referenced, "team_msdyn_quotebookingproduct", "owningteam")]
public const string team_msdyn_quotebookingproduct = "team_msdyn_quotebookingproduct";
[Relationship("msdyn_quotebookingservice", EntityRole.Referenced, "team_msdyn_quotebookingservice", "owningteam")]
public const string team_msdyn_quotebookingservice = "team_msdyn_quotebookingservice";
[Relationship("msdyn_quotebookingservicetask", EntityRole.Referenced, "team_msdyn_quotebookingservicetask", "owningteam")]
public const string team_msdyn_quotebookingservicetask = "team_msdyn_quotebookingservicetask";
[Relationship("msdyn_quotebookingsetup", EntityRole.Referenced, "team_msdyn_quotebookingsetup", "owningteam")]
public const string team_msdyn_quotebookingsetup = "team_msdyn_quotebookingsetup";
[Relationship("msdyn_quoteinvoicingproduct", EntityRole.Referenced, "team_msdyn_quoteinvoicingproduct", "owningteam")]
public const string team_msdyn_quoteinvoicingproduct = "team_msdyn_quoteinvoicingproduct";
[Relationship("msdyn_quoteinvoicingsetup", EntityRole.Referenced, "team_msdyn_quoteinvoicingsetup", "owningteam")]
public const string team_msdyn_quoteinvoicingsetup = "team_msdyn_quoteinvoicingsetup";
[Relationship("msdyn_quotelineanalyticsbreakdown", EntityRole.Referenced, "team_msdyn_quotelineanalyticsbreakdown", "owningteam")]
public const string team_msdyn_quotelineanalyticsbreakdown = "team_msdyn_quotelineanalyticsbreakdown";
[Relationship("msdyn_quotelineresourcecategory", EntityRole.Referenced, "team_msdyn_quotelineresourcecategory", "owningteam")]
public const string team_msdyn_quotelineresourcecategory = "team_msdyn_quotelineresourcecategory";
[Relationship("msdyn_quotelinescheduleofvalue", EntityRole.Referenced, "team_msdyn_quotelinescheduleofvalue", "owningteam")]
public const string team_msdyn_quotelinescheduleofvalue = "team_msdyn_quotelinescheduleofvalue";
[Relationship("msdyn_quotelinetransaction", EntityRole.Referenced, "team_msdyn_quotelinetransaction", "owningteam")]
public const string team_msdyn_quotelinetransaction = "team_msdyn_quotelinetransaction";
[Relationship("msdyn_quotelinetransactioncategory", EntityRole.Referenced, "team_msdyn_quotelinetransactioncategory", "owningteam")]
public const string team_msdyn_quotelinetransactioncategory = "team_msdyn_quotelinetransactioncategory";
[Relationship("msdyn_quotelinetransactionclassification", EntityRole.Referenced, "team_msdyn_quotelinetransactionclassification", "owningteam")]
public const string team_msdyn_quotelinetransactionclassification = "team_msdyn_quotelinetransactionclassification";
[Relationship("msdyn_quotepricelist", EntityRole.Referenced, "team_msdyn_quotepricelist", "owningteam")]
public const string team_msdyn_quotepricelist = "team_msdyn_quotepricelist";
[Relationship("msdyn_relationshipinsightsunifiedconfig", EntityRole.Referenced, "team_msdyn_relationshipinsightsunifiedconfig", "owningteam")]
public const string team_msdyn_relationshipinsightsunifiedconfig = "team_msdyn_relationshipinsightsunifiedconfig";
[Relationship("msdyn_requirementcharacteristic", EntityRole.Referenced, "team_msdyn_requirementcharacteristic", "owningteam")]
public const string team_msdyn_requirementcharacteristic = "team_msdyn_requirementcharacteristic";
[Relationship("msdyn_requirementorganizationunit", EntityRole.Referenced, "team_msdyn_requirementorganizationunit", "owningteam")]
public const string team_msdyn_requirementorganizationunit = "team_msdyn_requirementorganizationunit";
[Relationship("msdyn_requirementresourcecategory", EntityRole.Referenced, "team_msdyn_requirementresourcecategory", "owningteam")]
public const string team_msdyn_requirementresourcecategory = "team_msdyn_requirementresourcecategory";
[Relationship("msdyn_requirementresourcepreference", EntityRole.Referenced, "team_msdyn_requirementresourcepreference", "owningteam")]
public const string team_msdyn_requirementresourcepreference = "team_msdyn_requirementresourcepreference";
[Relationship("msdyn_requirementstatus", EntityRole.Referenced, "team_msdyn_requirementstatus", "owningteam")]
public const string team_msdyn_requirementstatus = "team_msdyn_requirementstatus";
[Relationship("msdyn_resourceassignment", EntityRole.Referenced, "team_msdyn_resourceassignment", "owningteam")]
public const string team_msdyn_resourceassignment = "team_msdyn_resourceassignment";
[Relationship("msdyn_resourceassignmentdetail", EntityRole.Referenced, "team_msdyn_resourceassignmentdetail", "owningteam")]
public const string team_msdyn_resourceassignmentdetail = "team_msdyn_resourceassignmentdetail";
[Relationship("msdyn_resourcepaytype", EntityRole.Referenced, "team_msdyn_resourcepaytype", "owningteam")]
public const string team_msdyn_resourcepaytype = "team_msdyn_resourcepaytype";
[Relationship("msdyn_resourcerequest", EntityRole.Referenced, "team_msdyn_resourcerequest", "owningteam")]
public const string team_msdyn_resourcerequest = "team_msdyn_resourcerequest";
[Relationship("msdyn_resourcerequirement", EntityRole.Referenced, "team_msdyn_resourcerequirement", "owningteam")]
public const string team_msdyn_resourcerequirement = "team_msdyn_resourcerequirement";
[Relationship("msdyn_resourcerequirementdetail", EntityRole.Referenced, "team_msdyn_resourcerequirementdetail", "owningteam")]
public const string team_msdyn_resourcerequirementdetail = "team_msdyn_resourcerequirementdetail";
[Relationship("msdyn_resourceterritory", EntityRole.Referenced, "team_msdyn_resourceterritory", "owningteam")]
public const string team_msdyn_resourceterritory = "team_msdyn_resourceterritory";
[Relationship("msdyn_rma", EntityRole.Referenced, "team_msdyn_rma", "owningteam")]
public const string team_msdyn_rma = "team_msdyn_rma";
[Relationship("msdyn_rmaproduct", EntityRole.Referenced, "team_msdyn_rmaproduct", "owningteam")]
public const string team_msdyn_rmaproduct = "team_msdyn_rmaproduct";
[Relationship("msdyn_rmareceipt", EntityRole.Referenced, "team_msdyn_rmareceipt", "owningteam")]
public const string team_msdyn_rmareceipt = "team_msdyn_rmareceipt";
[Relationship("msdyn_rmareceiptproduct", EntityRole.Referenced, "team_msdyn_rmareceiptproduct", "owningteam")]
public const string team_msdyn_rmareceiptproduct = "team_msdyn_rmareceiptproduct";
[Relationship("msdyn_rmasubstatus", EntityRole.Referenced, "team_msdyn_rmasubstatus", "owningteam")]
public const string team_msdyn_rmasubstatus = "team_msdyn_rmasubstatus";
[Relationship("msdyn_rolecompetencyrequirement", EntityRole.Referenced, "team_msdyn_rolecompetencyrequirement", "owningteam")]
public const string team_msdyn_rolecompetencyrequirement = "team_msdyn_rolecompetencyrequirement";
[Relationship("msdyn_roleutilization", EntityRole.Referenced, "team_msdyn_roleutilization", "owningteam")]
public const string team_msdyn_roleutilization = "team_msdyn_roleutilization";
[Relationship("msdyn_rtv", EntityRole.Referenced, "team_msdyn_rtv", "owningteam")]
public const string team_msdyn_rtv = "team_msdyn_rtv";
[Relationship("msdyn_rtvproduct", EntityRole.Referenced, "team_msdyn_rtvproduct", "owningteam")]
public const string team_msdyn_rtvproduct = "team_msdyn_rtvproduct";
[Relationship("msdyn_rtvsubstatus", EntityRole.Referenced, "team_msdyn_rtvsubstatus", "owningteam")]
public const string team_msdyn_rtvsubstatus = "team_msdyn_rtvsubstatus";
[Relationship("msdyn_salesinsightssettings", EntityRole.Referenced, "team_msdyn_salesinsightssettings", "owningteam")]
public const string team_msdyn_salesinsightssettings = "team_msdyn_salesinsightssettings";
[Relationship("msdyn_scheduleboardsetting", EntityRole.Referenced, "team_msdyn_scheduleboardsetting", "owningteam")]
public const string team_msdyn_scheduleboardsetting = "team_msdyn_scheduleboardsetting";
[Relationship("msdyn_servicetasktype", EntityRole.Referenced, "team_msdyn_servicetasktype", "owningteam")]
public const string team_msdyn_servicetasktype = "team_msdyn_servicetasktype";
[Relationship("msdyn_shipvia", EntityRole.Referenced, "team_msdyn_shipvia", "owningteam")]
public const string team_msdyn_shipvia = "team_msdyn_shipvia";
[Relationship("msdyn_siconfig", EntityRole.Referenced, "team_msdyn_siconfig", "owningteam")]
public const string team_msdyn_siconfig = "team_msdyn_siconfig";
[Relationship("msdyn_solutionhealthrule", EntityRole.Referenced, "team_msdyn_solutionhealthrule", "owningteam")]
public const string team_msdyn_solutionhealthrule = "team_msdyn_solutionhealthrule";
[Relationship("msdyn_solutionhealthruleargument", EntityRole.Referenced, "team_msdyn_solutionhealthruleargument", "owningteam")]
public const string team_msdyn_solutionhealthruleargument = "team_msdyn_solutionhealthruleargument";
[Relationship("msdyn_systemuserschedulersetting", EntityRole.Referenced, "team_msdyn_systemuserschedulersetting", "owningteam")]
public const string team_msdyn_systemuserschedulersetting = "team_msdyn_systemuserschedulersetting";
[Relationship("msdyn_taxcode", EntityRole.Referenced, "team_msdyn_taxcode", "owningteam")]
public const string team_msdyn_taxcode = "team_msdyn_taxcode";
[Relationship("msdyn_taxcodedetail", EntityRole.Referenced, "team_msdyn_taxcodedetail", "owningteam")]
public const string team_msdyn_taxcodedetail = "team_msdyn_taxcodedetail";
[Relationship("msdyn_timeentry", EntityRole.Referenced, "team_msdyn_timeentry", "owningteam")]
public const string team_msdyn_timeentry = "team_msdyn_timeentry";
[Relationship("msdyn_timegroup", EntityRole.Referenced, "team_msdyn_timegroup", "owningteam")]
public const string team_msdyn_timegroup = "team_msdyn_timegroup";
[Relationship("msdyn_timegroupdetail", EntityRole.Referenced, "team_msdyn_timegroupdetail", "owningteam")]
public const string team_msdyn_timegroupdetail = "team_msdyn_timegroupdetail";
[Relationship("msdyn_timeoffcalendar", EntityRole.Referenced, "team_msdyn_timeoffcalendar", "owningteam")]
public const string team_msdyn_timeoffcalendar = "team_msdyn_timeoffcalendar";
[Relationship("msdyn_timeoffrequest", EntityRole.Referenced, "team_msdyn_timeoffrequest", "owningteam")]
public const string team_msdyn_timeoffrequest = "team_msdyn_timeoffrequest";
[Relationship("msdyn_transactionconnection", EntityRole.Referenced, "team_msdyn_transactionconnection", "owningteam")]
public const string team_msdyn_transactionconnection = "team_msdyn_transactionconnection";
[Relationship("msdyn_transactionorigin", EntityRole.Referenced, "team_msdyn_transactionorigin", "owningteam")]
public const string team_msdyn_transactionorigin = "team_msdyn_transactionorigin";
[Relationship("msdyn_untrackedappointment", EntityRole.Referenced, "team_msdyn_untrackedappointment", "owningteam")]
public const string team_msdyn_untrackedappointment = "team_msdyn_untrackedappointment";
[Relationship("msdyn_userworkhistory", EntityRole.Referenced, "team_msdyn_userworkhistory", "owningteam")]
public const string team_msdyn_userworkhistory = "team_msdyn_userworkhistory";
[Relationship("msdyn_wallsavedqueryusersettings", EntityRole.Referenced, "team_msdyn_wallsavedqueryusersettings", "owningteam")]
public const string team_msdyn_wallsavedqueryusersettings = "team_msdyn_wallsavedqueryusersettings";
[Relationship("msdyn_warehouse", EntityRole.Referenced, "team_msdyn_warehouse", "owningteam")]
public const string team_msdyn_warehouse = "team_msdyn_warehouse";
[Relationship("msdyn_workhourtemplate", EntityRole.Referenced, "team_msdyn_workhourtemplate", "owningteam")]
public const string team_msdyn_workhourtemplate = "team_msdyn_workhourtemplate";
[Relationship("msdyn_workorder", EntityRole.Referenced, "team_msdyn_workorder", "owningteam")]
public const string team_msdyn_workorder = "team_msdyn_workorder";
[Relationship("msdyn_workordercharacteristic", EntityRole.Referenced, "team_msdyn_workordercharacteristic", "owningteam")]
public const string team_msdyn_workordercharacteristic = "team_msdyn_workordercharacteristic";
[Relationship("msdyn_workorderincident", EntityRole.Referenced, "team_msdyn_workorderincident", "owningteam")]
public const string team_msdyn_workorderincident = "team_msdyn_workorderincident";
[Relationship("msdyn_workorderproduct", EntityRole.Referenced, "team_msdyn_workorderproduct", "owningteam")]
public const string team_msdyn_workorderproduct = "team_msdyn_workorderproduct";
[Relationship("msdyn_workorderresourcerestriction", EntityRole.Referenced, "team_msdyn_workorderresourcerestriction", "owningteam")]
public const string team_msdyn_workorderresourcerestriction = "team_msdyn_workorderresourcerestriction";
[Relationship("msdyn_workorderservice", EntityRole.Referenced, "team_msdyn_workorderservice", "owningteam")]
public const string team_msdyn_workorderservice = "team_msdyn_workorderservice";
[Relationship("msdyn_workorderservicetask", EntityRole.Referenced, "team_msdyn_workorderservicetask", "owningteam")]
public const string team_msdyn_workorderservicetask = "team_msdyn_workorderservicetask";
[Relationship("msdyn_workordersubstatus", EntityRole.Referenced, "team_msdyn_workordersubstatus", "owningteam")]
public const string team_msdyn_workordersubstatus = "team_msdyn_workordersubstatus";
[Relationship("msdyn_workordertype", EntityRole.Referenced, "team_msdyn_workordertype", "owningteam")]
public const string team_msdyn_workordertype = "team_msdyn_workordertype";
[Relationship("msfp_emailtemplate", EntityRole.Referenced, "team_msfp_emailtemplate", "owningteam")]
public const string team_msfp_emailtemplate = "team_msfp_emailtemplate";
[Relationship("msfp_question", EntityRole.Referenced, "team_msfp_question", "owningteam")]
public const string team_msfp_question = "team_msfp_question";
[Relationship("msfp_questionresponse", EntityRole.Referenced, "team_msfp_questionresponse", "owningteam")]
public const string team_msfp_questionresponse = "team_msfp_questionresponse";
[Relationship("msfp_survey", EntityRole.Referenced, "team_msfp_survey", "owningteam")]
public const string team_msfp_survey = "team_msfp_survey";
[Relationship("msfp_unsubscribedrecipient", EntityRole.Referenced, "team_msfp_unsubscribedrecipient", "owningteam")]
public const string team_msfp_unsubscribedrecipient = "team_msfp_unsubscribedrecipient";
[Relationship("opportunity", EntityRole.Referenced, "team_opportunities", "owningteam")]
public const string team_opportunities = "team_opportunities";
[Relationship("opportunityclose", EntityRole.Referenced, "team_opportunityclose", "owningteam")]
public const string team_opportunityclose = "team_opportunityclose";
[Relationship("opportunityproduct", EntityRole.Referenced, "team_opportunityproduct", "owningteam")]
public const string team_opportunityproduct = "team_opportunityproduct";
[Relationship("orderclose", EntityRole.Referenced, "team_orderclose", "owningteam")]
public const string team_orderclose = "team_orderclose";
[Relationship("salesorder", EntityRole.Referenced, "team_orders", "owningteam")]
public const string team_orders = "team_orders";
[Relationship("phonecall", EntityRole.Referenced, "team_phonecall", "owningteam")]
public const string team_phonecall = "team_phonecall";
[Relationship("postregarding", EntityRole.Referenced, "team_PostRegardings", "regardingobjectid")]
public const string team_PostRegardings = "team_PostRegardings";
[Relationship("postrole", EntityRole.Referenced, "team_PostRoles", "regardingobjectid")]
public const string team_PostRoles = "team_PostRoles";
[Relationship("principalobjectattributeaccess", EntityRole.Referenced, "team_principalobjectattributeaccess", "objectid")]
public const string team_principalobjectattributeaccess = "team_principalobjectattributeaccess";
[Relationship("principalobjectattributeaccess", EntityRole.Referenced, "team_principalobjectattributeaccess_principalid", "principalid")]
public const string team_principalobjectattributeaccess_principalid = "team_principalobjectattributeaccess_principalid";
[Relationship("processsession", EntityRole.Referenced, "team_processsession", "owningteam")]
public const string team_processsession = "team_processsession";
[Relationship("processsession", EntityRole.Referenced, "Team_ProcessSessions", "regardingobjectid")]
public const string Team_ProcessSessions = "Team_ProcessSessions";
[Relationship("channelaccessprofilerule", EntityRole.Referenced, "team_profilerule", "owningteam")]
public const string team_profilerule = "team_profilerule";
[Relationship("queueitem", EntityRole.Referenced, "team_queueitembase_workerid", "workerid")]
public const string team_queueitembase_workerid = "team_queueitembase_workerid";
[Relationship("quoteclose", EntityRole.Referenced, "team_quoteclose", "owningteam")]
public const string team_quoteclose = "team_quoteclose";
[Relationship("quotedetail", EntityRole.Referenced, "team_quotedetail", "owningteam")]
public const string team_quotedetail = "team_quotedetail";
[Relationship("quote", EntityRole.Referenced, "team_quotes", "owningteam")]
public const string team_quotes = "team_quotes";
[Relationship("ratingmodel", EntityRole.Referenced, "team_ratingmodel", "owningteam")]
public const string team_ratingmodel = "team_ratingmodel";
[Relationship("ratingvalue", EntityRole.Referenced, "team_ratingvalue", "owningteam")]
public const string team_ratingvalue = "team_ratingvalue";
[Relationship("recurringappointmentmaster", EntityRole.Referenced, "team_recurringappointmentmaster", "owningteam")]
public const string team_recurringappointmentmaster = "team_recurringappointmentmaster";
[Relationship("resourcegroup", EntityRole.Referenced, "team_resource_groups", "resourcegroupid")]
public const string team_resource_groups = "team_resource_groups";
[Relationship("resourcespec", EntityRole.Referenced, "team_resource_specs", "groupobjectid")]
public const string team_resource_specs = "team_resource_specs";
[Relationship("routingrule", EntityRole.Referenced, "team_routingrule", "owningteam")]
public const string team_routingrule = "team_routingrule";
[Relationship("routingruleitem", EntityRole.Referenced, "team_routingruleitem", "assignobjectid")]
public const string team_routingruleitem = "team_routingruleitem";
[Relationship("sales_linkedin_profileassociations", EntityRole.Referenced, "team_sales_linkedin_profileassociations", "owningteam")]
public const string team_sales_linkedin_profileassociations = "team_sales_linkedin_profileassociations";
[Relationship("salesorderdetail", EntityRole.Referenced, "team_salesorderdetail", "owningteam")]
public const string team_salesorderdetail = "team_salesorderdetail";
[Relationship("serviceappointment", EntityRole.Referenced, "team_service_appointments", "owningteam")]
public const string team_service_appointments = "team_service_appointments";
[Relationship("contract", EntityRole.Referenced, "team_service_contracts", "owningteam")]
public const string team_service_contracts = "team_service_contracts";
[Relationship("sharepointdocumentlocation", EntityRole.Referenced, "team_sharepointdocumentlocation", "owningteam")]
public const string team_sharepointdocumentlocation = "team_sharepointdocumentlocation";
[Relationship("sharepointsite", EntityRole.Referenced, "team_sharepointsite", "owningteam")]
public const string team_sharepointsite = "team_sharepointsite";
[Relationship("sla", EntityRole.Referenced, "team_slaBase", "owningteam")]
public const string team_slaBase = "team_slaBase";
[Relationship("socialactivity", EntityRole.Referenced, "team_socialactivity", "owningteam")]
public const string team_socialactivity = "team_socialactivity";
[Relationship("syncerror", EntityRole.Referenced, "team_SyncError", "owningteam")]
public const string team_SyncError = "team_SyncError";
[Relationship("syncerror", EntityRole.Referenced, "Team_SyncErrors", "regardingobjectid")]
public const string Team_SyncErrors = "Team_SyncErrors";
[Relationship("task", EntityRole.Referenced, "team_task", "owningteam")]
public const string team_task = "team_task";
[Relationship("tit_compteurparametrage", EntityRole.Referenced, "team_tit_compteurparametrage", "")]
public const string team_tit_compteurparametrage = "team_tit_compteurparametrage";
[Relationship("tit_compteurrequests", EntityRole.Referenced, "team_tit_compteurrequests", "")]
public const string team_tit_compteurrequests = "team_tit_compteurrequests";
[Relationship("tit_concurrentlocker", EntityRole.Referenced, "team_tit_concurrentlocker", "")]
public const string team_tit_concurrentlocker = "team_tit_concurrentlocker";
[Relationship("tit_counter", EntityRole.Referenced, "team_tit_counter", "")]
public const string team_tit_counter = "team_tit_counter";
[Relationship("tit_mappingfluxentrant", EntityRole.Referenced, "team_tit_mappingfluxentrant", "")]
public const string team_tit_mappingfluxentrant = "team_tit_mappingfluxentrant";
[Relationship("tit_smssetup", EntityRole.Referenced, "team_tit_smssetup", "")]
public const string team_tit_smssetup = "team_tit_smssetup";
[Relationship("userentityinstancedata", EntityRole.Referenced, "team_userentityinstancedata", "owningteam")]
public const string team_userentityinstancedata = "team_userentityinstancedata";
[Relationship("userentityuisettings", EntityRole.Referenced, "team_userentityuisettings", "owningteam")]
public const string team_userentityuisettings = "team_userentityuisettings";
[Relationship("userform", EntityRole.Referenced, "team_userform", "owningteam")]
public const string team_userform = "team_userform";
[Relationship("userquery", EntityRole.Referenced, "team_userquery", "owningteam")]
public const string team_userquery = "team_userquery";
[Relationship("userqueryvisualization", EntityRole.Referenced, "team_userqueryvisualizations", "owningteam")]
public const string team_userqueryvisualizations = "team_userqueryvisualizations";
[Relationship("workflow", EntityRole.Referenced, "team_workflow", "owningteam")]
public const string team_workflow = "team_workflow";
[Relationship("workflowlog", EntityRole.Referenced, "team_workflowlog", "owningteam")]
public const string team_workflowlog = "team_workflowlog";
[Relationship("userentityinstancedata", EntityRole.Referenced, "userentityinstancedata_team", "objectid")]
public const string userentityinstancedata_team = "userentityinstancedata_team";
}
}
[OptionSetDefinition(TeamDefinition.EntityName, TeamDefinition.Columns.TeamType)]
public enum TypeDEquipe
{
[Description("Owner")]
Proprietaire = 0,
[Description("Access")]
Acces = 1,
[Description("AAD Security Group")]
GroupeDeSecurite_AAD = 2,
[Description("AAD Office Group")]
GroupeOffice_AAD = 3,
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Abc.Zebus.Routing;
using Abc.Zebus.Util.Extensions;
namespace Abc.Zebus.Directory
{
public class PeerSubscriptionTree
{
private readonly SubscriptionNode _rootNode = new SubscriptionNode(0);
private List<Peer> _peersMatchingAllMessages = new List<Peer>();
public bool IsEmpty => _rootNode.IsEmpty && _peersMatchingAllMessages.Count == 0;
public void Add(Peer peer, BindingKey subscription)
=> UpdatePeerSubscription(peer, subscription, UpdateAction.Add);
public void Remove(Peer peer, BindingKey subscription)
=> UpdatePeerSubscription(peer, subscription, UpdateAction.Remove);
public IList<Peer> GetPeers(BindingKey routingKey)
{
var peerCollector = new PeerCollector(_peersMatchingAllMessages);
if (routingKey.IsEmpty)
{
// The message is not routable or has no routing member.
// If the tree contains any subscription with a binding key, it indicates a message definition
// mismatch between the publisher and the subscriber. In this situation, it is safer to send
// the message to the subscriber anyway.
// => Always forward the message to all peers.
_rootNode.AddAllPeers(peerCollector);
}
else
{
_rootNode.Accept(peerCollector, routingKey);
}
return peerCollector.GetPeers();
}
private void UpdatePeerSubscription(Peer peer, BindingKey subscription, UpdateAction action)
{
if (subscription.IsEmpty)
UpdatePeersMatchingAllMessages(peer, action);
else
_rootNode.Update(peer, subscription, action);
}
private void UpdatePeersMatchingAllMessages(Peer peer, UpdateAction action)
=> UpdateList(ref _peersMatchingAllMessages, peer, action);
private static void UpdateList(ref List<Peer> peers, Peer peer, UpdateAction action)
{
var newPeers = new List<Peer>(peers.Capacity);
newPeers.AddRange(peers.Where(x => x.Id != peer.Id));
if (action == UpdateAction.Add)
newPeers.Add(peer);
peers = newPeers;
}
private class PeerCollector
{
private readonly Dictionary<PeerId, Peer> _collectedPeers = new Dictionary<PeerId, Peer>();
private readonly List<Peer> _initialPeers;
public PeerCollector(List<Peer> initialPeers)
{
_initialPeers = initialPeers;
}
[SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")]
public void Offer(List<Peer> peers)
{
foreach (var peer in peers)
{
_collectedPeers[peer.Id] = peer;
}
}
public List<Peer> GetPeers()
{
if (_collectedPeers.Count == 0)
return _initialPeers;
Offer(_initialPeers);
return _collectedPeers.Values.ToList();
}
}
private class SubscriptionNode
{
private static readonly Action<SubscriptionNode, string> _removeNode = (x, part) => x.RemoveChildNode(part);
private static readonly Action<SubscriptionNode, string?> _removeSharpNode = (x, _) => x._sharpNode = null;
private static readonly Action<SubscriptionNode, string?> _removeStarNode = (x, _) => x._starNode = null;
private ConcurrentDictionary<string, SubscriptionNode>? _childNodes;
private SubscriptionNode? _sharpNode;
private SubscriptionNode? _starNode;
private readonly int _nextPartIndex;
private List<Peer> _peers = new List<Peer>();
private int _peerCountIncludingChildren;
public SubscriptionNode(int nextPartIndex)
{
_nextPartIndex = nextPartIndex;
}
public bool IsEmpty => _peerCountIncludingChildren == 0;
public void AddAllPeers(PeerCollector peerCollector)
{
peerCollector.Offer(_peers);
_sharpNode?.AddAllPeers(peerCollector);
_starNode?.AddAllPeers(peerCollector);
if (_childNodes == null)
return;
foreach (var (_, childNode) in _childNodes)
{
childNode.AddAllPeers(peerCollector);
}
}
public void Accept(PeerCollector peerCollector, BindingKey routingKey)
{
if (IsLeaf(routingKey))
{
peerCollector.Offer(_peers);
return;
}
_sharpNode?.AddAllPeers(peerCollector);
_starNode?.Accept(peerCollector, routingKey);
var nextPart = routingKey.GetPartToken(_nextPartIndex);
if (nextPart == null || _childNodes == null)
return;
if (_childNodes.TryGetValue(nextPart, out var childNode))
childNode.Accept(peerCollector, routingKey);
}
public int Update(Peer peer, BindingKey subscription, UpdateAction action)
{
if (IsLeaf(subscription))
{
var update = UpdateList(peer, action);
_peerCountIncludingChildren += update;
return update;
}
var nextPart = subscription.GetPartToken(_nextPartIndex);
if (subscription.IsSharp(_nextPartIndex) || nextPart == null)
return UpdateChildNode(GetOrCreateSharpNode(), peer, subscription, action, null, _removeSharpNode);
if (subscription.IsStar(_nextPartIndex))
return UpdateChildNode(GetOrCreateStarNode(), peer, subscription, action, null, _removeStarNode);
var childNode = GetOrAddChildNode(nextPart);
return UpdateChildNode(childNode, peer, subscription, action, nextPart, _removeNode!);
}
private int UpdateChildNode(SubscriptionNode childNode, Peer peer, BindingKey subscription, UpdateAction action, string? childNodePart, Action<SubscriptionNode, string?> remover)
{
var update = childNode.Update(peer, subscription, action);
_peerCountIncludingChildren += update;
if (childNode.IsEmpty)
remover(this, childNodePart);
return update;
}
private bool IsLeaf(BindingKey bindingKey)
{
if (_nextPartIndex == 0)
return false;
return _nextPartIndex == bindingKey.PartCount;
}
private SubscriptionNode GetOrAddChildNode(string part)
{
if (_childNodes == null)
_childNodes = new ConcurrentDictionary<string, SubscriptionNode>();
return _childNodes.GetOrAdd(part, k => new SubscriptionNode(_nextPartIndex + 1));
}
private void RemoveChildNode(string part)
=> _childNodes?.TryRemove(part, out _);
private SubscriptionNode GetOrCreateSharpNode()
=> _sharpNode ??= new SubscriptionNode(_nextPartIndex + 1);
private SubscriptionNode GetOrCreateStarNode()
=> _starNode ??= new SubscriptionNode(_nextPartIndex + 1);
private int UpdateList(Peer peer, UpdateAction action)
=> action == UpdateAction.Add
? AddToList(peer)
: RemoveFromList(peer);
private int AddToList(Peer peerToAdd)
{
var removed = false;
var newPeers = new List<Peer>(_peers.Capacity);
foreach (var peer in _peers)
{
if (peer.Id == peerToAdd.Id)
removed = true;
else
newPeers.Add(peer);
}
newPeers.Add(peerToAdd);
_peers = newPeers;
return removed ? 0 : 1;
}
private int RemoveFromList(Peer peerToRemove)
{
var removed = false;
var newPeers = new List<Peer>(_peers.Capacity);
foreach (var peer in _peers)
{
if (peer.Id == peerToRemove.Id)
removed = true;
else
newPeers.Add(peer);
}
_peers = newPeers;
return removed ? -1 : 0;
}
}
private enum UpdateAction
{
Add,
Remove,
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Parallel.Tests
{
public class TakeTakeWhileTests
{
//
// Take
//
public static IEnumerable<object[]> TakeUnorderedData(int[] counts)
{
Func<int, IEnumerable<int>> take = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct();
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), take)) yield return results;
}
public static IEnumerable<object[]> TakeData(int[] counts)
{
Func<int, IEnumerable<int>> take = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct();
foreach (object[] results in Sources.Ranges(counts.Cast<int>(), take)) yield return results;
}
[Theory]
[MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Take_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take)));
foreach (int i in query.Take(take))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void Take_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
Take_Unordered(labeled, count, take);
}
[Theory]
[MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Take(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.Take(take))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(count, Math.Max(0, take)), seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeData", (object)(new int[] { 1024 * 32 }))]
public static void Take_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
Take(labeled, count, take);
}
[Theory]
[MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Take_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take)));
Assert.All(query.Take(take).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void Take_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
Take_Unordered_NotPipelined(labeled, count, take);
}
[Theory]
[MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void Take_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.Take(take).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Min(count, Math.Max(0, take)), seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeData", (object)(new int[] { 1024 * 32 }))]
public static void Take_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
Take_NotPipelined(labeled, count, take);
}
[Fact]
public static void Take_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Take(0));
}
//
// TakeWhile
//
public static IEnumerable<object[]> TakeWhileData(int[] counts)
{
foreach (object[] results in Sources.Ranges(counts.Cast<int>()))
{
yield return new[] { results[0], results[1], new[] { 0 } };
yield return new[] { results[0], results[1], Enumerable.Range((int)results[1] / 2, ((int)results[1] - 1) / 2 + 1) };
yield return new[] { results[0], results[1], new[] { (int)results[1] - 1 } };
}
}
[Theory]
[MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take)));
foreach (int i in query.TakeWhile(x => x < take))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_Unordered(labeled, count, take);
}
[Theory]
[MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.TakeWhile(x => x < take))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(count, Math.Max(0, take)), seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile(labeled, count, take);
}
[Theory]
[MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take)));
Assert.All(query.TakeWhile(x => x < take).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_Unordered_NotPipelined(labeled, count, take);
}
[Theory]
[MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.TakeWhile(x => x < take).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Min(count, Math.Max(0, take)), seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_NotPipelined(labeled, count, take);
}
[Theory]
[MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take)));
foreach (int i in query.TakeWhile((x, index) => index < take))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_Indexed_Unordered(labeled, count, take);
}
[Theory]
[MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_Indexed(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.TakeWhile((x, index) => index < take))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(count, Math.Max(0, take)), seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_Indexed(labeled, count, take);
}
[Theory]
[MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
// For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation.
// If this test starts failing it should be updated, and possibly mentioned in release notes.
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take)));
Assert.All(query.TakeWhile((x, index) => index < take).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_Indexed_Unordered_NotPipelined(labeled, count, take);
}
[Theory]
[MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.TakeWhile((x, index) => index < take).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Min(count, Math.Max(0, take)), seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_Indexed_NotPipelined(labeled, count, take);
}
[Theory]
[MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_AllFalse(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.TakeWhile(x => false));
}
[Theory]
[OuterLoop]
[MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_AllFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_AllFalse(labeled, count, take);
}
[Theory]
[MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))]
public static void TakeWhile_AllTrue(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.TakeWhile(x => true), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_AllTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take)
{
TakeWhile_AllTrue(labeled, count, take);
}
[Theory]
[MemberData("TakeWhileData", (object)(new int[] { 2, 16 }))]
public static void TakeWhile_SomeTrue(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.TakeWhile(x => take.Contains(x)), x => Assert.Equal(seen++, x));
Assert.Equal(take.Min() > 0 ? 0 : take.Max() + 1, seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeWhileData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_SomeTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take)
{
TakeWhile_SomeTrue(labeled, count, take);
}
[Theory]
[MemberData("TakeWhileData", (object)(new int[] { 2, 16 }))]
public static void TakeWhile_SomeFalse(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.TakeWhile(x => !take.Contains(x)), x => Assert.Equal(seen++, x));
Assert.Equal(take.Min(), seen);
}
[Theory]
[OuterLoop]
[MemberData("TakeWhileData", (object)(new int[] { 1024 * 32 }))]
public static void TakeWhile_SomeFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take)
{
TakeWhile_SomeFalse(labeled, count, take);
}
[Fact]
public static void TakeWhile_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).TakeWhile(x => true));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().TakeWhile((Func<bool, bool>)null));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().TakeWhile((Func<bool, int, bool>)null));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.DataProtection.Repositories;
#pragma warning disable AZC0001 //
namespace Azure.Extensions.AspNetCore.DataProtection.Blobs
#pragma warning restore
{
/// <summary>
/// An <see cref="IXmlRepository"/> which is backed by Azure Blob Storage.
/// </summary>
/// <remarks>
/// Instances of this type are thread-safe.
/// </remarks>
internal sealed class AzureBlobXmlRepository : IXmlRepository
{
private const int ConflictMaxRetries = 5;
private static readonly TimeSpan ConflictBackoffPeriod = TimeSpan.FromMilliseconds(200);
private static readonly XName RepositoryElementName = "repository";
private static BlobHttpHeaders _blobHttpHeaders = new BlobHttpHeaders() { ContentType = "application/xml; charset=utf-8" };
private readonly Random _random;
private BlobData _cachedBlobData;
private readonly BlobClient _blobClient;
/// <summary>
/// Creates a new instance of the <see cref="AzureBlobXmlRepository"/>.
/// </summary>
/// <param name="blobClient">A <see cref="BlobClient"/> that is connected to the blob we are reading from and writing to.</param>
public AzureBlobXmlRepository(BlobClient blobClient)
{
_random = new Random();
_blobClient = blobClient;
}
/// <inheritdoc />
public IReadOnlyCollection<XElement> GetAllElements()
{
// Shunt the work onto a ThreadPool thread so that it's independent of any
// existing sync context or other potentially deadlock-causing items.
var elements = Task.Run(() => GetAllElementsAsync()).GetAwaiter().GetResult();
return new ReadOnlyCollection<XElement>(elements);
}
/// <inheritdoc />
public void StoreElement(XElement element, string friendlyName)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
// Shunt the work onto a ThreadPool thread so that it's independent of any
// existing sync context or other potentially deadlock-causing items.
Task.Run(() => StoreElementAsync(element)).GetAwaiter().GetResult();
}
private XDocument CreateDocumentFromBlob(byte[] blob)
{
using (var memoryStream = new MemoryStream(blob))
{
var xmlReaderSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Prohibit, IgnoreProcessingInstructions = true
};
using (var xmlReader = XmlReader.Create(memoryStream, xmlReaderSettings))
{
return XDocument.Load(xmlReader);
}
}
}
private async Task<IList<XElement>> GetAllElementsAsync()
{
var data = await GetLatestDataAsync().ConfigureAwait(false);
if (data == null || data.BlobContents.Length == 0)
{
// no data in blob storage
return Array.Empty<XElement>();
}
// The document will look like this:
//
// <root>
// <child />
// <child />
// ...
// </root>
//
// We want to return the first-level child elements to our caller.
var doc = CreateDocumentFromBlob(data.BlobContents);
return doc.Root.Elements().ToList();
}
private async Task<BlobData> GetLatestDataAsync()
{
// Set the appropriate AccessCondition based on what we believe the latest
// file contents to be, then make the request.
var latestCachedData = Volatile.Read(ref _cachedBlobData); // local ref so field isn't mutated under our feet
var requestCondition = (latestCachedData != null)
? new BlobRequestConditions() { IfNoneMatch = latestCachedData.ETag }
: null;
try
{
using (var memoryStream = new MemoryStream())
{
var response = await _blobClient.DownloadToAsync(
destination: memoryStream,
conditions: requestCondition).ConfigureAwait(false);
// At this point, our original cache either didn't exist or was outdated.
// We'll update it now and return the updated value
latestCachedData = new BlobData()
{
BlobContents = memoryStream.ToArray(),
ETag = response.Headers.ETag
};
}
Volatile.Write(ref _cachedBlobData, latestCachedData);
}
catch (RequestFailedException ex) when (ex.Status == 304)
{
// 304 Not Modified
// Thrown when we already have the latest cached data.
// This isn't an error; we'll return our cached copy of the data.
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
// 404 Not Found
// Thrown when no file exists in storage.
// This isn't an error; we'll delete our cached copy of data.
latestCachedData = null;
Volatile.Write(ref _cachedBlobData, latestCachedData);
}
return latestCachedData;
}
private int GetRandomizedBackoffPeriod()
{
// returns a TimeSpan in the range [0.8, 1.0) * ConflictBackoffPeriod
// not used for crypto purposes
var multiplier = 0.8 + (_random.NextDouble() * 0.2);
return (int) (multiplier * ConflictBackoffPeriod.Ticks);
}
private async Task StoreElementAsync(XElement element)
{
// holds the last error in case we need to rethrow it
ExceptionDispatchInfo lastError = null;
for (var i = 0; i < ConflictMaxRetries; i++)
{
if (i > 1)
{
// If multiple conflicts occurred, wait a small period of time before retrying
// the operation so that other writers can make forward progress.
await Task.Delay(GetRandomizedBackoffPeriod()).ConfigureAwait(false);
}
if (i > 0)
{
// If at least one conflict occurred, make sure we have an up-to-date
// view of the blob contents.
await GetLatestDataAsync().ConfigureAwait(false);
}
// Merge the new element into the document. If no document exists,
// create a new default document and inject this element into it.
var latestData = Volatile.Read(ref _cachedBlobData);
var doc = (latestData != null)
? CreateDocumentFromBlob(latestData.BlobContents)
: new XDocument(new XElement(RepositoryElementName));
doc.Root.Add(element);
// Turn this document back into a byte[].
var serializedDoc = new MemoryStream();
doc.Save(serializedDoc, SaveOptions.DisableFormatting);
serializedDoc.Position = 0;
// Generate the appropriate precondition header based on whether or not
// we believe data already exists in storage.
BlobRequestConditions requestConditions;
if (latestData != null)
{
requestConditions = new BlobRequestConditions() { IfMatch = latestData.ETag };
}
else
{
requestConditions = new BlobRequestConditions() { IfNoneMatch = ETag.All };
}
try
{
// Send the request up to the server.
var response = await _blobClient.UploadAsync(
serializedDoc,
httpHeaders: _blobHttpHeaders,
conditions: requestConditions).ConfigureAwait(false);
// If we got this far, success!
// We can update the cached view of the remote contents.
Volatile.Write(ref _cachedBlobData, new BlobData()
{
BlobContents = serializedDoc.ToArray(),
ETag = response.Value.ETag // was updated by Upload routine
});
return;
}
catch (RequestFailedException ex)
when (ex.Status == 409 || ex.Status == 412)
{
// 409 Conflict
// This error is rare but can be thrown in very special circumstances,
// such as if the blob in the process of being created. We treat it
// as equivalent to 412 for the purposes of retry logic.
// 412 Precondition Failed
// We'll get this error if another writer updated the repository and we
// have an outdated view of its contents. If this occurs, we'll just
// refresh our view of the remote contents and try again up to the max
// retry limit.
lastError = ExceptionDispatchInfo.Capture(ex);
}
}
// if we got this far, something went awry
lastError.Throw();
}
private sealed class BlobData
{
internal byte[] BlobContents;
internal ETag? ETag;
}
}
}
| |
// 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;
using System.Diagnostics.Contracts;
namespace System.Text
{
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
internal class EncoderNLS : Encoder
{
// Need a place for the last left over character, most of our encodings use this
internal char charLeftOver;
protected EncodingNLS m_encoding;
protected bool m_mustFlush;
internal bool m_throwOnOverflow;
internal int m_charsUsed;
internal EncoderFallback m_fallback;
internal EncoderFallbackBuffer m_fallbackBuffer;
internal EncoderNLS(EncodingNLS encoding)
{
m_encoding = encoding;
m_fallback = m_encoding.EncoderFallback;
Reset();
}
internal new EncoderFallback Fallback
{
get { return m_fallback; }
}
internal bool InternalHasFallbackBuffer
{
get
{
return m_fallbackBuffer != null;
}
}
public new EncoderFallbackBuffer FallbackBuffer
{
get
{
if (m_fallbackBuffer == null)
{
if (m_fallback != null)
m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
else
m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
}
return m_fallbackBuffer;
}
}
// This one is used when deserializing (like UTF7Encoding.Encoder)
internal EncoderNLS()
{
m_encoding = null;
Reset();
}
public override void Reset()
{
charLeftOver = (char)0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version
int result = -1;
fixed (char* pChars = chars)
{
result = GetByteCount(pChars + index, count, flush);
}
return result;
}
[System.Security.SecurityCritical] // auto-generated
public unsafe int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
m_mustFlush = flush;
m_throwOnOverflow = true;
return m_encoding.GetByteCount(chars, count, this);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (chars.Length == 0)
chars = new char[1];
int byteCount = bytes.Length - byteIndex;
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (char* pChars = chars)
fixed (byte* pBytes = bytes)
// Remember that charCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, flush);
}
[System.Security.SecurityCritical] // auto-generated
public unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? "byteCount" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
m_mustFlush = flush;
m_throwOnOverflow = true;
return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
}
// This method is used when your output buffer might not be large enough for the entire result.
// Just call the pointer version. (This gets bytes)
[System.Security.SecuritySafeCritical] // auto-generated
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
if (bytes.Length == 0)
bytes = new byte[1];
// Just call the pointer version (can't do this for non-msft encoders)
fixed (char* pChars = chars)
{
fixed (byte* pBytes = bytes)
{
Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush,
out charsUsed, out bytesUsed, out completed);
}
}
}
// This is the version that uses pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting bytes
[System.Security.SecurityCritical] // auto-generated
public unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
m_mustFlush = flush;
m_throwOnOverflow = false;
m_charsUsed = 0;
// Do conversion
bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
charsUsed = m_charsUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (charsUsed == charCount) && (!flush || !HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingies are now full, we can return
}
public Encoding Encoding
{
get
{
return m_encoding;
}
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our encoder?
internal virtual bool HasState
{
get
{
return (charLeftOver != (char)0);
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Internal.TypeSystem;
using Internal.IL;
namespace Internal.IL
{
//
// Corresponds to "I.12.3.2.1 The evaluation stack" in ECMA spec
//
internal enum StackValueKind
{
/// <summary>An unknow type.</summary>
Unknown,
/// <summary>Any signed or unsigned integer values that can be represented as a 32-bit entity.</summary>
Int32,
/// <summary>Any signed or unsigned integer values that can be represented as a 64-bit entity.</summary>
Int64,
/// <summary>Underlying platform pointer type represented as an integer of the appropriate size.</summary>
NativeInt,
/// <summary>Any float value.</summary>
Float,
/// <summary>A managed pointer.</summary>
ByRef,
/// <summary>An object reference.</summary>
ObjRef,
/// <summary>A value type which is not any of the primitive one.</summary>
ValueType
}
internal partial class ILImporter
{
private BasicBlock[] _basicBlocks; // Maps IL offset to basic block
private BasicBlock _currentBasicBlock;
private int _currentOffset;
private BasicBlock _pendingBasicBlocks;
//
// IL stream reading
//
private byte ReadILByte()
{
return _ilBytes[_currentOffset++];
}
private UInt16 ReadILUInt16()
{
UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8));
_currentOffset += 2;
return val;
}
private UInt32 ReadILUInt32()
{
UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24));
_currentOffset += 4;
return val;
}
private int ReadILToken()
{
return (int)ReadILUInt32();
}
private ulong ReadILUInt64()
{
ulong value = ReadILUInt32();
value |= (((ulong)ReadILUInt32()) << 32);
return value;
}
private unsafe float ReadILFloat()
{
uint value = ReadILUInt32();
return *(float*)(&value);
}
private unsafe double ReadILDouble()
{
ulong value = ReadILUInt64();
return *(double*)(&value);
}
private void SkipIL(int bytes)
{
_currentOffset += bytes;
}
//
// Basic block identification
//
private void FindBasicBlocks()
{
_basicBlocks = new BasicBlock[_ilBytes.Length];
CreateBasicBlock(0);
FindJumpTargets();
FindEHTargets();
}
private BasicBlock CreateBasicBlock(int offset)
{
BasicBlock basicBlock = _basicBlocks[offset];
if (basicBlock == null)
{
basicBlock = new BasicBlock() { StartOffset = offset };
_basicBlocks[offset] = basicBlock;
}
return basicBlock;
}
private void FindJumpTargets()
{
_currentOffset = 0;
while (_currentOffset < _ilBytes.Length)
{
MarkInstructionBoundary();
ILOpcode opCode = (ILOpcode)ReadILByte();
again:
switch (opCode)
{
case ILOpcode.ldarg_s:
case ILOpcode.ldarga_s:
case ILOpcode.starg_s:
case ILOpcode.ldloc_s:
case ILOpcode.ldloca_s:
case ILOpcode.stloc_s:
case ILOpcode.ldc_i4_s:
case ILOpcode.unaligned:
SkipIL(1);
break;
case ILOpcode.ldarg:
case ILOpcode.ldarga:
case ILOpcode.starg:
case ILOpcode.ldloc:
case ILOpcode.ldloca:
case ILOpcode.stloc:
SkipIL(2);
break;
case ILOpcode.ldc_i4:
case ILOpcode.ldc_r4:
SkipIL(4);
break;
case ILOpcode.ldc_i8:
case ILOpcode.ldc_r8:
SkipIL(8);
break;
case ILOpcode.jmp:
case ILOpcode.call:
case ILOpcode.calli:
case ILOpcode.callvirt:
case ILOpcode.cpobj:
case ILOpcode.ldobj:
case ILOpcode.ldstr:
case ILOpcode.newobj:
case ILOpcode.castclass:
case ILOpcode.isinst:
case ILOpcode.unbox:
case ILOpcode.ldfld:
case ILOpcode.ldflda:
case ILOpcode.stfld:
case ILOpcode.ldsfld:
case ILOpcode.ldsflda:
case ILOpcode.stsfld:
case ILOpcode.stobj:
case ILOpcode.box:
case ILOpcode.newarr:
case ILOpcode.ldelema:
case ILOpcode.ldelem:
case ILOpcode.stelem:
case ILOpcode.unbox_any:
case ILOpcode.refanyval:
case ILOpcode.mkrefany:
case ILOpcode.ldtoken:
case ILOpcode.ldftn:
case ILOpcode.ldvirtftn:
case ILOpcode.initobj:
case ILOpcode.constrained:
case ILOpcode.sizeof_:
SkipIL(4);
break;
case ILOpcode.prefix1:
opCode = (ILOpcode)(0x100 + ReadILByte());
goto again;
case ILOpcode.br_s:
case ILOpcode.leave_s:
{
int delta = (sbyte)ReadILByte();
CreateBasicBlock(_currentOffset + delta);
}
break;
case ILOpcode.brfalse_s:
case ILOpcode.brtrue_s:
case ILOpcode.beq_s:
case ILOpcode.bge_s:
case ILOpcode.bgt_s:
case ILOpcode.ble_s:
case ILOpcode.blt_s:
case ILOpcode.bne_un_s:
case ILOpcode.bge_un_s:
case ILOpcode.bgt_un_s:
case ILOpcode.ble_un_s:
case ILOpcode.blt_un_s:
{
int delta = (sbyte)ReadILByte();
CreateBasicBlock(_currentOffset + delta);
CreateBasicBlock(_currentOffset);
}
break;
case ILOpcode.br:
case ILOpcode.leave:
{
int delta = (int)ReadILUInt32();
CreateBasicBlock(_currentOffset + delta);
}
break;
case ILOpcode.brfalse:
case ILOpcode.brtrue:
case ILOpcode.beq:
case ILOpcode.bge:
case ILOpcode.bgt:
case ILOpcode.ble:
case ILOpcode.blt:
case ILOpcode.bne_un:
case ILOpcode.bge_un:
case ILOpcode.bgt_un:
case ILOpcode.ble_un:
case ILOpcode.blt_un:
{
int delta = (int)ReadILUInt32();
CreateBasicBlock(_currentOffset + delta);
CreateBasicBlock(_currentOffset);
}
break;
case ILOpcode.switch_:
{
uint count = ReadILUInt32();
int jmpBase = _currentOffset + (int)(4 * count);
for (uint i = 0; i < count; i++)
{
int delta = (int)ReadILUInt32();
CreateBasicBlock(jmpBase + delta);
}
CreateBasicBlock(_currentOffset);
}
break;
default:
continue;
}
}
}
private void FindEHTargets()
{
for (int i = 0; i < _exceptionRegions.Length; i++)
{
var r = _exceptionRegions[i];
CreateBasicBlock(r.ILRegion.TryOffset).TryStart = true;
if (r.ILRegion.Kind == ILExceptionRegionKind.Filter)
CreateBasicBlock(r.ILRegion.FilterOffset).FilterStart = true;
CreateBasicBlock(r.ILRegion.HandlerOffset).HandlerStart = true;
}
}
//
// Basic block importing
//
private void ImportBasicBlocks()
{
_pendingBasicBlocks = _basicBlocks[0];
while (_pendingBasicBlocks != null)
{
BasicBlock basicBlock = _pendingBasicBlocks;
_pendingBasicBlocks = basicBlock.Next;
StartImportingBasicBlock(basicBlock);
ImportBasicBlock(basicBlock);
EndImportingBasicBlock(basicBlock);
}
}
private void MarkBasicBlock(BasicBlock basicBlock)
{
if (basicBlock.EndOffset == 0)
{
// Link
basicBlock.Next = _pendingBasicBlocks;
_pendingBasicBlocks = basicBlock;
basicBlock.EndOffset = -1;
}
}
private void ImportBasicBlock(BasicBlock basicBlock)
{
_currentBasicBlock = basicBlock;
_currentOffset = basicBlock.StartOffset;
for (;;)
{
StartImportingInstruction();
ILOpcode opCode = (ILOpcode)ReadILByte();
again:
switch (opCode)
{
case ILOpcode.nop:
ImportNop();
break;
case ILOpcode.break_:
ImportBreak();
break;
case ILOpcode.ldarg_0:
case ILOpcode.ldarg_1:
case ILOpcode.ldarg_2:
case ILOpcode.ldarg_3:
ImportLoadVar(opCode - ILOpcode.ldarg_0, true);
break;
case ILOpcode.ldloc_0:
case ILOpcode.ldloc_1:
case ILOpcode.ldloc_2:
case ILOpcode.ldloc_3:
ImportLoadVar(opCode - ILOpcode.ldloc_0, false);
break;
case ILOpcode.stloc_0:
case ILOpcode.stloc_1:
case ILOpcode.stloc_2:
case ILOpcode.stloc_3:
ImportStoreVar(opCode - ILOpcode.stloc_0, false);
break;
case ILOpcode.ldarg_s:
ImportLoadVar(ReadILByte(), true);
break;
case ILOpcode.ldarga_s:
ImportAddressOfVar(ReadILByte(), true);
break;
case ILOpcode.starg_s:
ImportStoreVar(ReadILByte(), true);
break;
case ILOpcode.ldloc_s:
ImportLoadVar(ReadILByte(), false);
break;
case ILOpcode.ldloca_s:
ImportAddressOfVar(ReadILByte(), false);
break;
case ILOpcode.stloc_s:
ImportStoreVar(ReadILByte(), false);
break;
case ILOpcode.ldnull:
ImportLoadNull();
break;
case ILOpcode.ldc_i4_m1:
ImportLoadInt(-1, StackValueKind.Int32);
break;
case ILOpcode.ldc_i4_0:
case ILOpcode.ldc_i4_1:
case ILOpcode.ldc_i4_2:
case ILOpcode.ldc_i4_3:
case ILOpcode.ldc_i4_4:
case ILOpcode.ldc_i4_5:
case ILOpcode.ldc_i4_6:
case ILOpcode.ldc_i4_7:
case ILOpcode.ldc_i4_8:
ImportLoadInt(opCode - ILOpcode.ldc_i4_0, StackValueKind.Int32);
break;
case ILOpcode.ldc_i4_s:
ImportLoadInt((sbyte)ReadILByte(), StackValueKind.Int32);
break;
case ILOpcode.ldc_i4:
ImportLoadInt((int)ReadILUInt32(), StackValueKind.Int32);
break;
case ILOpcode.ldc_i8:
ImportLoadInt((long)ReadILUInt64(), StackValueKind.Int64);
break;
case ILOpcode.ldc_r4:
ImportLoadFloat(ReadILFloat());
break;
case ILOpcode.ldc_r8:
ImportLoadFloat(ReadILDouble());
break;
case ILOpcode.dup:
ImportDup();
break;
case ILOpcode.pop:
ImportPop();
break;
case ILOpcode.jmp:
ImportJmp(ReadILToken());
break;
case ILOpcode.call:
ImportCall(opCode, ReadILToken());
break;
case ILOpcode.calli:
ImportCalli(ReadILToken());
break;
case ILOpcode.ret:
ImportReturn();
return;
case ILOpcode.br_s:
case ILOpcode.brfalse_s:
case ILOpcode.brtrue_s:
case ILOpcode.beq_s:
case ILOpcode.bge_s:
case ILOpcode.bgt_s:
case ILOpcode.ble_s:
case ILOpcode.blt_s:
case ILOpcode.bne_un_s:
case ILOpcode.bge_un_s:
case ILOpcode.bgt_un_s:
case ILOpcode.ble_un_s:
case ILOpcode.blt_un_s:
{
int delta = (sbyte)ReadILByte();
ImportBranch(opCode + (ILOpcode.br - ILOpcode.br_s),
_basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br_s) ? _basicBlocks[_currentOffset] : null);
}
return;
case ILOpcode.br:
case ILOpcode.brfalse:
case ILOpcode.brtrue:
case ILOpcode.beq:
case ILOpcode.bge:
case ILOpcode.bgt:
case ILOpcode.ble:
case ILOpcode.blt:
case ILOpcode.bne_un:
case ILOpcode.bge_un:
case ILOpcode.bgt_un:
case ILOpcode.ble_un:
case ILOpcode.blt_un:
{
int delta = (int)ReadILUInt32();
ImportBranch(opCode,
_basicBlocks[_currentOffset + delta], (opCode != ILOpcode.br) ? _basicBlocks[_currentOffset] : null);
}
return;
case ILOpcode.switch_:
{
uint count = ReadILUInt32();
int jmpBase = _currentOffset + (int)(4 * count);
int[] jmpDelta = new int[count];
for (uint i = 0; i < count; i++)
jmpDelta[i] = (int)ReadILUInt32();
ImportSwitchJump(jmpBase, jmpDelta, _basicBlocks[_currentOffset]);
}
return;
case ILOpcode.ldind_i1:
ImportLoadIndirect(WellKnownType.SByte);
break;
case ILOpcode.ldind_u1:
ImportLoadIndirect(WellKnownType.Byte);
break;
case ILOpcode.ldind_i2:
ImportLoadIndirect(WellKnownType.Int16);
break;
case ILOpcode.ldind_u2:
ImportLoadIndirect(WellKnownType.UInt16);
break;
case ILOpcode.ldind_i4:
ImportLoadIndirect(WellKnownType.Int32);
break;
case ILOpcode.ldind_u4:
ImportLoadIndirect(WellKnownType.UInt32);
break;
case ILOpcode.ldind_i8:
ImportLoadIndirect(WellKnownType.Int64);
break;
case ILOpcode.ldind_i:
ImportLoadIndirect(WellKnownType.IntPtr);
break;
case ILOpcode.ldind_r4:
ImportLoadIndirect(WellKnownType.Single);
break;
case ILOpcode.ldind_r8:
ImportLoadIndirect(WellKnownType.Double);
break;
case ILOpcode.ldind_ref:
ImportLoadIndirect(null);
break;
case ILOpcode.stind_ref:
ImportStoreIndirect(null);
break;
case ILOpcode.stind_i1:
ImportStoreIndirect(WellKnownType.SByte);
break;
case ILOpcode.stind_i2:
ImportStoreIndirect(WellKnownType.Int16);
break;
case ILOpcode.stind_i4:
ImportStoreIndirect(WellKnownType.Int32);
break;
case ILOpcode.stind_i8:
ImportStoreIndirect(WellKnownType.Int64);
break;
case ILOpcode.stind_r4:
ImportStoreIndirect(WellKnownType.Single);
break;
case ILOpcode.stind_r8:
ImportStoreIndirect(WellKnownType.Double);
break;
case ILOpcode.add:
case ILOpcode.sub:
case ILOpcode.mul:
case ILOpcode.div:
case ILOpcode.div_un:
case ILOpcode.rem:
case ILOpcode.rem_un:
case ILOpcode.and:
case ILOpcode.or:
case ILOpcode.xor:
ImportBinaryOperation(opCode);
break;
case ILOpcode.shl:
case ILOpcode.shr:
case ILOpcode.shr_un:
ImportShiftOperation(opCode);
break;
case ILOpcode.neg:
case ILOpcode.not:
ImportUnaryOperation(opCode);
break;
case ILOpcode.conv_i1:
ImportConvert(WellKnownType.Byte, false, false);
break;
case ILOpcode.conv_i2:
ImportConvert(WellKnownType.Int16, false, false);
break;
case ILOpcode.conv_i4:
ImportConvert(WellKnownType.Int32, false, false);
break;
case ILOpcode.conv_i8:
ImportConvert(WellKnownType.Int64, false, false);
break;
case ILOpcode.conv_r4:
ImportConvert(WellKnownType.Single, false, false);
break;
case ILOpcode.conv_r8:
ImportConvert(WellKnownType.Double, false, false);
break;
case ILOpcode.conv_u4:
ImportConvert(WellKnownType.UInt32, false, false);
break;
case ILOpcode.conv_u8:
ImportConvert(WellKnownType.UInt64, false, false);
break;
case ILOpcode.callvirt:
ImportCall(opCode, ReadILToken());
break;
case ILOpcode.cpobj:
ImportCpOpj(ReadILToken());
break;
case ILOpcode.ldobj:
ImportLoadIndirect(ReadILToken());
break;
case ILOpcode.ldstr:
ImportLoadString(ReadILToken());
break;
case ILOpcode.newobj:
ImportCall(opCode, ReadILToken());
break;
case ILOpcode.castclass:
case ILOpcode.isinst:
ImportCasting(opCode, ReadILToken());
break;
case ILOpcode.conv_r_un:
ImportConvert(WellKnownType.Double, false, true);
break;
case ILOpcode.unbox:
ImportUnbox(ReadILToken(), opCode);
break;
case ILOpcode.throw_:
ImportThrow();
return;
case ILOpcode.ldfld:
ImportLoadField(ReadILToken(), false);
break;
case ILOpcode.ldflda:
ImportAddressOfField(ReadILToken(), false);
break;
case ILOpcode.stfld:
ImportStoreField(ReadILToken(), false);
break;
case ILOpcode.ldsfld:
ImportLoadField(ReadILToken(), true);
break;
case ILOpcode.ldsflda:
ImportAddressOfField(ReadILToken(), true);
break;
case ILOpcode.stsfld:
ImportStoreField(ReadILToken(), true);
break;
case ILOpcode.stobj:
ImportStoreIndirect(ReadILToken());
break;
case ILOpcode.conv_ovf_i1_un:
ImportConvert(WellKnownType.SByte, true, true);
break;
case ILOpcode.conv_ovf_i2_un:
ImportConvert(WellKnownType.Int16, true, true);
break;
case ILOpcode.conv_ovf_i4_un:
ImportConvert(WellKnownType.Int32, true, true);
break;
case ILOpcode.conv_ovf_i8_un:
ImportConvert(WellKnownType.Int64, true, true);
break;
case ILOpcode.conv_ovf_u1_un:
ImportConvert(WellKnownType.Byte, true, true);
break;
case ILOpcode.conv_ovf_u2_un:
ImportConvert(WellKnownType.UInt16, true, true);
break;
case ILOpcode.conv_ovf_u4_un:
ImportConvert(WellKnownType.UInt32, true, true);
break;
case ILOpcode.conv_ovf_u8_un:
ImportConvert(WellKnownType.UInt64, true, true);
break;
case ILOpcode.conv_ovf_i_un:
ImportConvert(WellKnownType.IntPtr, true, true);
break;
case ILOpcode.conv_ovf_u_un:
ImportConvert(WellKnownType.UIntPtr, true, true);
break;
case ILOpcode.box:
ImportBox(ReadILToken());
break;
case ILOpcode.newarr:
ImportNewArray(ReadILToken());
break;
case ILOpcode.ldlen:
ImportLoadLength();
break;
case ILOpcode.ldelema:
ImportAddressOfElement(ReadILToken());
break;
case ILOpcode.ldelem_i1:
ImportLoadElement(WellKnownType.SByte);
break;
case ILOpcode.ldelem_u1:
ImportLoadElement(WellKnownType.Byte);
break;
case ILOpcode.ldelem_i2:
ImportLoadElement(WellKnownType.Int16);
break;
case ILOpcode.ldelem_u2:
ImportLoadElement(WellKnownType.UInt16);
break;
case ILOpcode.ldelem_i4:
ImportLoadElement(WellKnownType.Int32);
break;
case ILOpcode.ldelem_u4:
ImportLoadElement(WellKnownType.UInt32);
break;
case ILOpcode.ldelem_i8:
ImportLoadElement(WellKnownType.Int64);
break;
case ILOpcode.ldelem_i:
ImportLoadElement(WellKnownType.IntPtr);
break;
case ILOpcode.ldelem_r4:
ImportLoadElement(WellKnownType.Single);
break;
case ILOpcode.ldelem_r8:
ImportLoadElement(WellKnownType.Double);
break;
case ILOpcode.ldelem_ref:
ImportLoadElement(null);
break;
case ILOpcode.stelem_i:
ImportStoreElement(WellKnownType.IntPtr);
break;
case ILOpcode.stelem_i1:
ImportStoreElement(WellKnownType.SByte);
break;
case ILOpcode.stelem_i2:
ImportStoreElement(WellKnownType.Int16);
break;
case ILOpcode.stelem_i4:
ImportStoreElement(WellKnownType.Int32);
break;
case ILOpcode.stelem_i8:
ImportStoreElement(WellKnownType.Int32);
break;
case ILOpcode.stelem_r4:
ImportStoreElement(WellKnownType.Single);
break;
case ILOpcode.stelem_r8:
ImportStoreElement(WellKnownType.Double);
break;
case ILOpcode.stelem_ref:
ImportStoreElement(null);
break;
case ILOpcode.ldelem:
ImportLoadElement(ReadILToken());
break;
case ILOpcode.stelem:
ImportStoreElement(ReadILToken());
break;
case ILOpcode.unbox_any:
ImportUnbox(ReadILToken(), opCode);
break;
case ILOpcode.conv_ovf_i1:
ImportConvert(WellKnownType.SByte, true, false);
break;
case ILOpcode.conv_ovf_u1:
ImportConvert(WellKnownType.Byte, true, false);
break;
case ILOpcode.conv_ovf_i2:
ImportConvert(WellKnownType.Int16, true, false);
break;
case ILOpcode.conv_ovf_u2:
ImportConvert(WellKnownType.UInt16, true, false);
break;
case ILOpcode.conv_ovf_i4:
ImportConvert(WellKnownType.Int32, true, false);
break;
case ILOpcode.conv_ovf_u4:
ImportConvert(WellKnownType.UInt32, true, false);
break;
case ILOpcode.conv_ovf_i8:
ImportConvert(WellKnownType.Int64, true, false);
break;
case ILOpcode.conv_ovf_u8:
ImportConvert(WellKnownType.UInt64, true, false);
break;
case ILOpcode.refanyval:
ImportRefAnyVal(ReadILToken());
break;
case ILOpcode.ckfinite:
ImportCkFinite();
break;
case ILOpcode.mkrefany:
ImportMkRefAny(ReadILToken());
break;
case ILOpcode.ldtoken:
ImportLdToken(ReadILToken());
break;
case ILOpcode.conv_u2:
ImportConvert(WellKnownType.UInt16, false, false);
break;
case ILOpcode.conv_u1:
ImportConvert(WellKnownType.Byte, false, false);
break;
case ILOpcode.conv_i:
ImportConvert(WellKnownType.IntPtr, false, false);
break;
case ILOpcode.conv_ovf_i:
ImportConvert(WellKnownType.IntPtr, true, false);
break;
case ILOpcode.conv_ovf_u:
ImportConvert(WellKnownType.UIntPtr, true, false);
break;
case ILOpcode.add_ovf:
case ILOpcode.add_ovf_un:
case ILOpcode.mul_ovf:
case ILOpcode.mul_ovf_un:
case ILOpcode.sub_ovf:
case ILOpcode.sub_ovf_un:
ImportBinaryOperation(opCode);
break;
case ILOpcode.endfinally:
ImportEndFinally();
return;
case ILOpcode.leave:
{
int delta = (int)ReadILUInt32();
ImportLeave(_basicBlocks[_currentOffset + delta]);
}
return;
case ILOpcode.leave_s:
{
int delta = (sbyte)ReadILByte();
ImportLeave(_basicBlocks[_currentOffset + delta]);
}
return;
case ILOpcode.stind_i:
ImportStoreIndirect(WellKnownType.IntPtr);
break;
case ILOpcode.conv_u:
ImportConvert(WellKnownType.UIntPtr, false, false);
break;
case ILOpcode.prefix1:
opCode = (ILOpcode)(0x100 + ReadILByte());
goto again;
case ILOpcode.arglist:
ImportArgList();
break;
case ILOpcode.ceq:
case ILOpcode.cgt:
case ILOpcode.cgt_un:
case ILOpcode.clt:
case ILOpcode.clt_un:
ImportCompareOperation(opCode);
break;
case ILOpcode.ldftn:
case ILOpcode.ldvirtftn:
ImportLdFtn(ReadILToken(), opCode);
break;
case ILOpcode.ldarg:
ImportLoadVar(ReadILUInt16(), true);
break;
case ILOpcode.ldarga:
ImportAddressOfVar(ReadILUInt16(), true);
break;
case ILOpcode.starg:
ImportStoreVar(ReadILUInt16(), true);
break;
case ILOpcode.ldloc:
ImportLoadVar(ReadILUInt16(), false);
break;
case ILOpcode.ldloca:
ImportAddressOfVar(ReadILUInt16(), false);
break;
case ILOpcode.stloc:
ImportStoreVar(ReadILUInt16(), false);
break;
case ILOpcode.localloc:
ImportLocalAlloc();
break;
case ILOpcode.endfilter:
ImportEndFilter();
return;
case ILOpcode.unaligned:
ImportUnalignedPrefix(ReadILByte());
continue;
case ILOpcode.volatile_:
ImportVolatilePrefix();
continue;
case ILOpcode.tail:
ImportTailPrefix();
continue;
case ILOpcode.initobj:
ImportInitObj(ReadILToken());
break;
case ILOpcode.constrained:
ImportConstrainedPrefix(ReadILToken());
continue;
case ILOpcode.cpblk:
ImportCpBlk();
break;
case ILOpcode.initblk:
ImportInitBlk();
break;
case ILOpcode.no:
ImportNoPrefix(ReadILByte());
continue;
case ILOpcode.rethrow:
ImportRethrow();
return;
case ILOpcode.sizeof_:
ImportSizeOf(ReadILToken());
break;
case ILOpcode.refanytype:
ImportRefAnyType();
break;
case ILOpcode.readonly_:
ImportReadOnlyPrefix();
continue;
default:
throw new BadImageFormatException("Invalid opcode");
}
BasicBlock nextBasicBlock = _basicBlocks[_currentOffset];
if (nextBasicBlock != null)
{
ImportFallthrough(nextBasicBlock);
return;
}
EndImportingInstruction();
}
}
private void ImportLoadIndirect(WellKnownType wellKnownType)
{
ImportLoadIndirect(GetWellKnownType(wellKnownType));
}
private void ImportStoreIndirect(WellKnownType wellKnownType)
{
ImportStoreIndirect(GetWellKnownType(wellKnownType));
}
private void ImportLoadElement(WellKnownType wellKnownType)
{
ImportLoadElement(GetWellKnownType(wellKnownType));
}
private void ImportStoreElement(WellKnownType wellKnownType)
{
ImportStoreElement(GetWellKnownType(wellKnownType));
}
}
}
|